#!/usr/bin/env python3
"""
FLHIP Send Report Email
Manually trigger the weekly email report with cost breakdown
Usage: python send_report.py [--days 7]
"""

import argparse
import sys
from db_handler import get_recent_leads, get_connection
from email_sender import send_lead_email


def main():
    parser = argparse.ArgumentParser(description='Send FLHIP Lead Report Email')
    parser.add_argument('--days', type=int, default=7, help='Number of days to include (default: 7)')
    parser.add_argument('--dry-run', action='store_true', help='Show stats without sending email')
    args = parser.parse_args()
    
    print("=" * 60)
    print("FLHIP SEND REPORT EMAIL")
    print("=" * 60)
    
    # Get leads
    leads = get_recent_leads(days=args.days)
    print(f"[INFO] Found {len(leads)} leads from past {args.days} days")
    
    # Get processing counts for cost calculation
    conn = get_connection()
    if not conn:
        print("[ERROR] Could not connect to database")
        sys.exit(1)
    
    cursor = conn.cursor()
    
    # Count records created in timeframe
    cursor.execute(f'''
        SELECT COUNT(*) FROM restaurant_leads_usa2 
        WHERE created_at >= DATE_SUB(NOW(), INTERVAL {args.days} DAY)
    ''')
    articles_processed = cursor.fetchone()[0]
    
    # Count geo lookups (has lat/lng, created in timeframe)
    cursor.execute(f'''
        SELECT COUNT(*) FROM restaurant_leads_usa2 
        WHERE lat IS NOT NULL AND lat != 0 
        AND created_at >= DATE_SUB(NOW(), INTERVAL {args.days} DAY)
    ''')
    geo_processed = cursor.fetchone()[0]
    
    # Count contact enrichments (has phone or email, created in timeframe)
    cursor.execute(f'''
        SELECT COUNT(*) FROM restaurant_leads_usa2 
        WHERE (phone IS NOT NULL AND phone != '' OR contact_email IS NOT NULL AND contact_email != '')
        AND created_at >= DATE_SUB(NOW(), INTERVAL {args.days} DAY)
    ''')
    contact_processed = cursor.fetchone()[0]
    
    cursor.close()
    conn.close()
    
    # Calculate costs (padded for overhead)
    # Google Geocoding: $0.008 per lookup (padded from $0.005)
    # Claude main processing: $0.02 per article (padded from $0.015)
    # Claude contact enrichment: $0.015 per record (padded from $0.012)
    stats = {
        'total': articles_processed,
        'inserted': len(leads),
        'duplicates': 0,
        'errors': 0,
        'geo_processed': geo_processed,
        'contact_processed': contact_processed,
        'costs': {
            'google_geocoding': geo_processed * 0.008,
            'claude_main': articles_processed * 0.02,
            'claude_contact': contact_processed * 0.015
        }
    }
    
    total_cost = stats['costs']['google_geocoding'] + stats['costs']['claude_main'] + stats['costs']['claude_contact']
    
    print(f"\n[STATS]")
    print(f"   Articles processed: {articles_processed}")
    print(f"   Geo lookups: {geo_processed}")
    print(f"   Contact enrichments: {contact_processed}")
    
    print(f"\n[COST BREAKDOWN]")
    print(f"   Google Geocoding: ${stats['costs']['google_geocoding']:.2f} ({geo_processed} @ $0.008/ea)")
    print(f"   Claude Articles:  ${stats['costs']['claude_main']:.2f} ({articles_processed} @ $0.02/ea)")
    print(f"   Claude Contacts:  ${stats['costs']['claude_contact']:.2f} ({contact_processed} @ $0.015/ea)")
    print(f"   ----------------------------------------")
    print(f"   TOTAL:            ${total_cost:.2f}")
    
    if args.dry_run:
        print(f"\n[DRY RUN] Email not sent")
        return
    
    print(f"\n[SENDING] Sending email with {len(leads)} leads...")
    success = send_lead_email(leads, stats)
    
    if success:
        print("[OK] Email sent successfully!")
    else:
        print("[ERROR] Failed to send email")
        sys.exit(1)


if __name__ == "__main__":
    main()
