#!/usr/bin/env python3
"""
FLHIP Weekly Lead Report - Email Sender
========================================
Sends weekly lead summary for RESTAURANTS and HOTELS to specified recipients.
Includes API cost tracking.

Usage:
    python3 email_weekly_report.py
    python3 email_weekly_report.py --test  # Send test email
    python3 email_weekly_report.py --days 7  # Leads from last 7 days
"""

import os
import argparse
import logging
import smtplib
import mysql.connector
import csv
import io
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email import encoders
from datetime import datetime, timedelta
from dotenv import load_dotenv
from pathlib import Path

# Load environment variables
load_dotenv()

# Setup logging
log_dir = Path("logs")
log_dir.mkdir(exist_ok=True)
logging.basicConfig(
    level=logging.INFO,
    format="%(asctime)s - %(levelname)s - %(message)s",
    handlers=[
        logging.FileHandler(log_dir / f"email_report_{datetime.now().strftime('%Y%m%d')}.log"),
        logging.StreamHandler()
    ]
)

# =============================================================================
# CONFIGURATION
# =============================================================================

# Email recipients
RECIPIENTS = [
    "mail@maryleeweir.com",
    "ken@flhip.com"
]

# Email settings - using environment variables for security
SMTP_HOST = os.getenv("SMTP_HOST", "smtp.gmail.com")
SMTP_PORT = int(os.getenv("SMTP_PORT", "587"))
SMTP_USER = os.getenv("SMTP_USER", "")
SMTP_PASSWORD = os.getenv("SMTP_PASSWORD", "")
FROM_EMAIL = os.getenv("FROM_EMAIL", SMTP_USER)

# Database configuration
db_config = {
    "host": os.getenv("DB_HOST"),
    "user": os.getenv("DB_USER"),
    "password": os.getenv("DB_PASSWORD"),
    "database": os.getenv("DB_NAME"),
    "charset": "utf8mb4",
    "use_unicode": True,
}

# Table names
RESTAURANT_TABLE = "restaurant_leads_usa2"
HOTEL_TABLE = "hotel_leads_usa"

# API Cost Estimates (per unit)
API_COSTS = {
    'claude_article': 0.01,       # Per article processed by Claude (~$4 for 349)
    'claude_contact_batch': 2.50, # Per batch of ~31 contacts enriched with web search
    'google_geocoding': 0.00,     # Free tier
}

# =============================================================================
# DATABASE FUNCTIONS
# =============================================================================

def get_connection():
    """Get database connection"""
    try:
        conn = mysql.connector.connect(**db_config)
        return conn
    except Exception as e:
        logging.error(f"Database connection error: {e}")
        return None


def get_weekly_leads(days=7, table_name=RESTAURANT_TABLE):
    """Get leads from the past N days for a specific table"""
    conn = get_connection()
    if not conn:
        return [], {}
    
    cursor = conn.cursor(dictionary=True)
    cutoff_date = datetime.now() - timedelta(days=days)
    
    # Get leads - updated for new schema (no future_intent_status)
    query = f"""
        SELECT 
            id, business, city, state, county, address, zip,
            opening_date, standardized_opening_date, lead_stage,
            contact_name, phone, contact_email, internet_info,
            info_source, notes, confidence, created_at
        FROM {table_name}
        WHERE created_at >= %s
          AND (flagged_for_deletion IS NULL OR flagged_for_deletion = 0)
          AND business IS NOT NULL
        ORDER BY 
            CASE lead_stage 
                WHEN 'LATE' THEN 1 
                WHEN 'MID' THEN 2 
                WHEN 'EARLY' THEN 3 
                ELSE 4 
            END,
            created_at DESC
    """
    
    cursor.execute(query, (cutoff_date,))
    leads = cursor.fetchall()
    
    # Get statistics - updated for new schema
    stats_query = f"""
        SELECT 
            COUNT(*) as total_processed,
            SUM(CASE WHEN lead_stage = 'EARLY' THEN 1 ELSE 0 END) as early_stage,
            SUM(CASE WHEN lead_stage = 'MID' THEN 1 ELSE 0 END) as mid_stage,
            SUM(CASE WHEN lead_stage = 'LATE' THEN 1 ELSE 0 END) as late_stage,
            SUM(CASE WHEN phone IS NOT NULL AND phone != '' THEN 1 ELSE 0 END) as has_phone,
            SUM(CASE WHEN contact_email IS NOT NULL AND contact_email != '' THEN 1 ELSE 0 END) as has_email,
            SUM(CASE WHEN confidence = 'HIGH' THEN 1 ELSE 0 END) as high_confidence,
            SUM(CASE WHEN confidence = 'MEDIUM' THEN 1 ELSE 0 END) as medium_confidence
        FROM {table_name}
        WHERE created_at >= %s
          AND (flagged_for_deletion IS NULL OR flagged_for_deletion = 0)
    """
    
    cursor.execute(stats_query, (cutoff_date,))
    stats = cursor.fetchone()
    
    cursor.close()
    conn.close()
    
    return leads, stats


def get_leads_by_state(days=7, table_name=RESTAURANT_TABLE):
    """Get lead count by state"""
    conn = get_connection()
    if not conn:
        return []
    
    cursor = conn.cursor(dictionary=True)
    cutoff_date = datetime.now() - timedelta(days=days)
    
    query = f"""
        SELECT state, COUNT(*) as count
        FROM {table_name}
        WHERE created_at >= %s
          AND (flagged_for_deletion IS NULL OR flagged_for_deletion = 0)
          AND state IS NOT NULL AND state != ''
        GROUP BY state
        ORDER BY count DESC
        LIMIT 15
    """
    
    cursor.execute(query, (cutoff_date,))
    results = cursor.fetchall()
    
    cursor.close()
    conn.close()
    
    return results


def estimate_api_costs(restaurant_stats, hotel_stats, contact_enriched=50):
    """Estimate API costs for the week"""
    
    restaurant_count = restaurant_stats.get('total_processed') or 0
    hotel_count = hotel_stats.get('total_processed') or 0
    
    # Claude article processing (both restaurant and hotel)
    claude_article_cost = (restaurant_count + hotel_count) * API_COSTS['claude_article']
    
    # Contact enrichment (batches of ~31)
    contact_batches = (contact_enriched + 30) // 31
    contact_cost = contact_batches * API_COSTS['claude_contact_batch']
    
    # Google geocoding is free
    geocoding_cost = 0.00
    
    total_cost = claude_article_cost + contact_cost + geocoding_cost
    
    return {
        'claude_article': claude_article_cost,
        'claude_contact': contact_cost,
        'geocoding': geocoding_cost,
        'total': total_cost,
        'breakdown': {
            'articles_processed': restaurant_count + hotel_count,
            'contact_batches': contact_batches,
            'contacts_enriched': contact_enriched
        }
    }


def create_leads_csv(leads, lead_type="restaurant"):
    """Create CSV file content from leads"""
    if not leads:
        return None
    
    output = io.StringIO()
    
    fieldnames = [
        'id', 'business', 'lead_stage', 'city', 'state', 'county', 
        'address', 'zip', 'opening_date', 'standardized_opening_date',
        'contact_name', 'phone', 'contact_email', 'internet_info',
        'info_source', 'notes', 'confidence', 'created_at'
    ]
    
    writer = csv.DictWriter(output, fieldnames=fieldnames, extrasaction='ignore')
    writer.writeheader()
    
    for lead in leads:
        row = {}
        for key in fieldnames:
            value = lead.get(key)
            if isinstance(value, datetime):
                row[key] = value.strftime('%Y-%m-%d %H:%M:%S')
            else:
                row[key] = value
        writer.writerow(row)
    
    return output.getvalue()


# =============================================================================
# EMAIL FORMATTING
# =============================================================================

def format_lead_html(lead, lead_type="restaurant"):
    """Format a single lead as HTML"""
    # Use text labels instead of emojis for better email compatibility
    stage_label = {
        'EARLY': '[EARLY]',
        'MID': '[MID]', 
        'LATE': '[HOT]'
    }.get(lead.get('lead_stage'), '')
    
    type_label = '[R]' if lead_type == 'restaurant' else '[H]'
    
    stage = lead.get('lead_stage') or 'Unknown'
    business = lead.get('business') or 'Unknown'
    city = lead.get('city') or ''
    state = lead.get('state') or ''
    location = f"{city}, {state}" if city and state else city or state or 'Location TBD'
    
    opening = lead.get('standardized_opening_date') or lead.get('opening_date') or 'TBD'
    contact = lead.get('contact_name') or ''
    phone = lead.get('phone') or ''
    email = lead.get('contact_email') or ''
    website = lead.get('internet_info') or ''
    source = lead.get('info_source') or ''
    confidence = lead.get('confidence') or ''
    
    contact_info = []
    if contact:
        contact_info.append(f"<strong>Contact:</strong> {contact}")
    if phone:
        contact_info.append(f"<strong>Phone:</strong> {phone}")
    if email:
        contact_info.append(f"<strong>Email:</strong> {email}")
    if website:
        display_url = website[:50] + '...' if len(website) > 50 else website
        contact_info.append(f"<strong>Web:</strong> <a href='{website}'>{display_url}</a>")
    
    contact_html = "<br>".join(contact_info) if contact_info else "<em>No contact info yet</em>"
    
    border_color = '#28a745' if stage == 'LATE' else '#ffc107' if stage == 'MID' else '#17a2b8'
    
    return f"""
    <div style="border: 1px solid #ddd; border-left: 4px solid {border_color}; padding: 15px; margin: 10px 0; border-radius: 4px;">
        <h3 style="margin: 0 0 10px 0; color: #333;">{stage_label} {business}</h3>
        <p style="margin: 5px 0; color: #666;">
            <strong>Location:</strong> {location}<br>
            <strong>Opening:</strong> {opening}<br>
            <strong>Stage:</strong> {stage}
            {f' | <strong>Confidence:</strong> {confidence}' if confidence else ''}
        </p>
        <p style="margin: 10px 0; font-size: 0.9em;">
            {contact_html}
        </p>
        {f'<p style="margin: 5px 0; font-size: 0.85em;"><a href="{source}">Source Article</a></p>' if source else ''}
    </div>
    """


def create_section_html(leads, stage, stage_name, emoji, lead_type="restaurant"):
    """Create HTML section for a lead stage"""
    stage_leads = [l for l in leads if l.get('lead_stage') == stage][:20]
    count = len([l for l in leads if l.get('lead_stage') == stage])
    
    if not stage_leads:
        return f'<p>No {stage} stage leads this week</p>'
    
    html = ''.join(format_lead_html(l, lead_type) for l in stage_leads)
    if count > 20:
        html += f'<p style="color: #666; font-style: italic;">... and {count - 20} more</p>'
    return html


def create_email_content(restaurant_leads, restaurant_stats, restaurant_states,
                         hotel_leads, hotel_stats, hotel_states, 
                         api_costs, days):
    """Create HTML and plain text email content"""
    
    now = datetime.now()
    week_start = now - timedelta(days=days)
    
    # Restaurant statistics
    r_total = restaurant_stats.get('total_processed') or 0
    r_early = restaurant_stats.get('early_stage') or 0
    r_mid = restaurant_stats.get('mid_stage') or 0
    r_late = restaurant_stats.get('late_stage') or 0
    r_phone = restaurant_stats.get('has_phone') or 0
    r_email = restaurant_stats.get('has_email') or 0
    
    # Hotel statistics
    h_total = hotel_stats.get('total_processed') or 0
    h_early = hotel_stats.get('early_stage') or 0
    h_mid = hotel_stats.get('mid_stage') or 0
    h_late = hotel_stats.get('late_stage') or 0
    h_phone = hotel_stats.get('has_phone') or 0
    h_email = hotel_stats.get('has_email') or 0
    
    # API costs
    cost_total = api_costs.get('total', 0)
    cost_article = api_costs.get('claude_article', 0)
    cost_contact = api_costs.get('claude_contact', 0)
    articles_processed = api_costs.get('breakdown', {}).get('articles_processed', 0)
    contacts_enriched = api_costs.get('breakdown', {}).get('contacts_enriched', 0)
    
    # HTML Version
    html = f"""
    <!DOCTYPE html>
    <html>
    <head>
        <style>
            body {{ font-family: Arial, sans-serif; max-width: 900px; margin: 0 auto; padding: 20px; background: #f5f5f5; }}
            .header {{ background: linear-gradient(135deg, #2c3e50, #3498db); color: white; padding: 25px; border-radius: 8px; margin-bottom: 20px; }}
            .stats {{ display: flex; flex-wrap: wrap; gap: 10px; margin: 20px 0; }}
            .stat-box {{ background: #f8f9fa; padding: 15px; border-radius: 8px; text-align: center; min-width: 100px; flex: 1; }}
            .stat-number {{ font-size: 28px; font-weight: bold; color: #2c3e50; }}
            .stat-label {{ font-size: 11px; color: #666; text-transform: uppercase; }}
            .section {{ background: white; margin: 20px 0; padding: 20px; border-radius: 8px; box-shadow: 0 2px 4px rgba(0,0,0,0.1); }}
            .section-title {{ border-bottom: 2px solid #3498db; padding-bottom: 10px; color: #2c3e50; margin-top: 0; }}
            table {{ width: 100%; border-collapse: collapse; margin: 10px 0; }}
            th, td {{ padding: 10px; text-align: left; border-bottom: 1px solid #eee; }}
            th {{ background: #f8f9fa; font-weight: 600; }}
            .cost-box {{ background: #fff3cd; border: 1px solid #ffc107; padding: 15px; border-radius: 8px; margin: 10px 0; }}
            .cost-total {{ font-size: 24px; font-weight: bold; color: #856404; }}
            .two-column {{ display: flex; gap: 20px; flex-wrap: wrap; }}
            .two-column > div {{ flex: 1; min-width: 300px; }}
        </style>
    </head>
    <body>
        <div class="header">
            <h1 style="margin: 0;">FLHIP Weekly Lead Report</h1>
            <p style="margin: 10px 0 0 0; opacity: 0.9; font-size: 18px;">
                {week_start.strftime('%B %d')} - {now.strftime('%B %d, %Y')}
            </p>
        </div>
        
        <!-- SUMMARY STATS -->
        <div class="section">
            <h2 class="section-title">Weekly Summary</h2>
            <div class="stats">
                <div class="stat-box" style="background: #e8f4fd; border-left: 4px solid #3498db;">
                    <div class="stat-number">{r_total}</div>
                    <div class="stat-label">Restaurant Leads</div>
                </div>
                <div class="stat-box" style="background: #fef4e8; border-left: 4px solid #f39c12;">
                    <div class="stat-number">{h_total}</div>
                    <div class="stat-label">Hotel Leads</div>
                </div>
                <div class="stat-box" style="background: #e8fdf4; border-left: 4px solid #27ae60;">
                    <div class="stat-number">{r_phone + h_phone}</div>
                    <div class="stat-label">With Phone</div>
                </div>
                <div class="stat-box" style="background: #f4e8fd; border-left: 4px solid #9b59b6;">
                    <div class="stat-number">{r_email + h_email}</div>
                    <div class="stat-label">With Email</div>
                </div>
            </div>
        </div>
        
        <!-- API COSTS -->
        <div class="section">
            <h2 class="section-title">API Costs This Week</h2>
            <div class="cost-box">
                <div style="display: flex; justify-content: space-between; align-items: center;">
                    <div>
                        <div class="cost-total">${cost_total:.2f}</div>
                        <div style="color: #856404; font-size: 12px;">Estimated Total Cost</div>
                    </div>
                    <div style="text-align: right; font-size: 14px; color: #666;">
                        <div>Claude Article Processing: ${cost_article:.2f} ({articles_processed} articles)</div>
                        <div>Claude Contact Enrichment: ${cost_contact:.2f} ({contacts_enriched} contacts)</div>
                        <div>Google Geocoding: $0.00 (free tier)</div>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- RESTAURANT SECTION -->
        <div class="section">
            <h2 class="section-title">Restaurant Leads ({r_total} total)</h2>
            
            <h3>Lead Stages</h3>
            <div class="stats">
                <div class="stat-box">
                    <div class="stat-number" style="color: #17a2b8;">{r_early}</div>
                    <div class="stat-label">EARLY (Planning)</div>
                </div>
                <div class="stat-box">
                    <div class="stat-number" style="color: #ffc107;">{r_mid}</div>
                    <div class="stat-label">MID (Construction)</div>
                </div>
                <div class="stat-box">
                    <div class="stat-number" style="color: #28a745;">{r_late}</div>
                    <div class="stat-label">LATE (Opening Soon)</div>
                </div>
            </div>
            
            <h3>Top States</h3>
            <table>
                <tr><th>State</th><th>Count</th></tr>
                {''.join(f"<tr><td>{s['state']}</td><td>{s['count']}</td></tr>" for s in restaurant_states[:10])}
            </table>
            
            <h3>HOT LEADS - Opening Soon ({r_late} leads)</h3>
            {create_section_html(restaurant_leads, 'LATE', 'Late', '', 'restaurant')}
            
            <h3>In Progress ({r_mid} leads)</h3>
            {create_section_html(restaurant_leads, 'MID', 'Mid', '', 'restaurant')}
            
            <h3>Early Stage ({r_early} leads)</h3>
            {create_section_html(restaurant_leads, 'EARLY', 'Early', '', 'restaurant')}
        </div>
        
        <!-- HOTEL SECTION -->
        <div class="section">
            <h2 class="section-title">Hotel Leads ({h_total} total)</h2>
            
            <h3>Lead Stages</h3>
            <div class="stats">
                <div class="stat-box">
                    <div class="stat-number" style="color: #17a2b8;">{h_early}</div>
                    <div class="stat-label">EARLY (Planning)</div>
                </div>
                <div class="stat-box">
                    <div class="stat-number" style="color: #ffc107;">{h_mid}</div>
                    <div class="stat-label">MID (Construction)</div>
                </div>
                <div class="stat-box">
                    <div class="stat-number" style="color: #28a745;">{h_late}</div>
                    <div class="stat-label">LATE (Opening Soon)</div>
                </div>
            </div>
            
            <h3>Top States</h3>
            <table>
                <tr><th>State</th><th>Count</th></tr>
                {''.join(f"<tr><td>{s['state']}</td><td>{s['count']}</td></tr>" for s in hotel_states[:10]) if hotel_states else '<tr><td colspan="2">No hotel leads by state</td></tr>'}
            </table>
            
            <h3>HOT LEADS - Opening Soon ({h_late} leads)</h3>
            {create_section_html(hotel_leads, 'LATE', 'Late', '', 'hotel')}
            
            <h3>In Progress ({h_mid} leads)</h3>
            {create_section_html(hotel_leads, 'MID', 'Mid', '', 'hotel')}
            
            <h3>Early Stage ({h_early} leads)</h3>
            {create_section_html(hotel_leads, 'EARLY', 'Early', '', 'hotel')}
        </div>
        
        <hr style="margin: 30px 0; border: none; border-top: 1px solid #ddd;">
        <p style="color: #666; font-size: 12px; text-align: center;">
            Generated by FLHIP v4.2.0 on {now.strftime('%Y-%m-%d %H:%M:%S')}<br>
            Total leads this report: {len(restaurant_leads) + len(hotel_leads)} ({len(restaurant_leads)} restaurants, {len(hotel_leads)} hotels)
        </p>
    </body>
    </html>
    """
    
    # Plain text version
    text = f"""
FLHIP Weekly Lead Report
{week_start.strftime('%B %d')} - {now.strftime('%B %d, %Y')}
{'='*60}

WEEKLY SUMMARY
--------------
Restaurant Leads: {r_total}
Hotel Leads: {h_total}
With Phone: {r_phone + h_phone}
With Email: {r_email + h_email}

API COSTS THIS WEEK
-------------------
Total: ${cost_total:.2f}
  - Claude Article Processing: ${cost_article:.2f} ({articles_processed} articles)
  - Claude Contact Enrichment: ${cost_contact:.2f} ({contacts_enriched} contacts)
  - Google Geocoding: $0.00 (free tier)

RESTAURANT LEADS ({r_total})
----------------------------
Lead Stages:
  EARLY (Planning): {r_early}
  MID (Construction): {r_mid}
  LATE (Opening Soon): {r_late}

Top States:
{chr(10).join(f"  {s['state']}: {s['count']}" for s in restaurant_states[:10])}

HOTEL LEADS ({h_total})
-----------------------
Lead Stages:
  EARLY (Planning): {h_early}
  MID (Construction): {h_mid}
  LATE (Opening Soon): {h_late}

Generated: {now.strftime('%Y-%m-%d %H:%M:%S')}
Total leads: {len(restaurant_leads) + len(hotel_leads)}
"""
    
    return html, text


# =============================================================================
# EMAIL SENDING
# =============================================================================

def send_email(subject, html_content, text_content, recipients, attachments=None):
    """Send email via SMTP with optional attachments"""
    
    if not SMTP_USER or not SMTP_PASSWORD:
        logging.error("[ERROR] SMTP credentials not configured!")
        logging.error("Set SMTP_USER and SMTP_PASSWORD in your .env file")
        return False
    
    msg = MIMEMultipart('mixed')
    msg['Subject'] = subject
    msg['From'] = FROM_EMAIL
    msg['To'] = ', '.join(recipients)
    
    # Create alternative part for text/html
    alt_part = MIMEMultipart('alternative')
    alt_part.attach(MIMEText(text_content, 'plain'))
    alt_part.attach(MIMEText(html_content, 'html'))
    msg.attach(alt_part)
    
    # Attach files if provided
    if attachments:
        for filename, content in attachments.items():
            if content:
                csv_attachment = MIMEBase('text', 'csv')
                csv_attachment.set_payload(content)
                encoders.encode_base64(csv_attachment)
                csv_attachment.add_header('Content-Disposition', f'attachment; filename="{filename}"')
                msg.attach(csv_attachment)
                logging.info(f"[ATTACH] {filename}")
    
    try:
        with smtplib.SMTP(SMTP_HOST, SMTP_PORT) as server:
            server.starttls()
            server.login(SMTP_USER, SMTP_PASSWORD)
            server.sendmail(FROM_EMAIL, recipients, msg.as_string())
        
        logging.info(f"[OK] Email sent to: {', '.join(recipients)}")
        return True
        
    except Exception as e:
        logging.error(f"[ERROR] Failed to send email: {e}")
        return False


# =============================================================================
# MAIN
# =============================================================================

def main():
    parser = argparse.ArgumentParser(description="FLHIP Weekly Email Report")
    parser.add_argument("--days", type=int, default=7, help="Days to include in report")
    parser.add_argument("--test", action="store_true", help="Send test email")
    parser.add_argument("--preview", action="store_true", help="Preview without sending")
    parser.add_argument("--recipients", nargs="+", help="Override recipients")
    parser.add_argument("--contacts-enriched", type=int, default=50, help="Number of contacts enriched (for cost calc)")
    
    args = parser.parse_args()
    
    logging.info(f"Generating report for last {args.days} days...")
    
    # Get RESTAURANT data
    logging.info("Fetching restaurant leads...")
    restaurant_leads, restaurant_stats = get_weekly_leads(args.days, RESTAURANT_TABLE)
    restaurant_states = get_leads_by_state(args.days, RESTAURANT_TABLE)
    logging.info(f"Found {len(restaurant_leads)} restaurant leads")
    
    # Get HOTEL data
    logging.info("Fetching hotel leads...")
    hotel_leads, hotel_stats = get_weekly_leads(args.days, HOTEL_TABLE)
    hotel_states = get_leads_by_state(args.days, HOTEL_TABLE)
    logging.info(f"Found {len(hotel_leads)} hotel leads")
    
    # Calculate API costs
    api_costs = estimate_api_costs(restaurant_stats, hotel_stats, args.contacts_enriched)
    logging.info(f"Estimated API cost: ${api_costs['total']:.2f}")
    
    # Create content
    html, text = create_email_content(
        restaurant_leads, restaurant_stats, restaurant_states,
        hotel_leads, hotel_stats, hotel_states,
        api_costs, args.days
    )
    
    # Subject line
    total_leads = len(restaurant_leads) + len(hotel_leads)
    now = datetime.now()
    subject = f"FLHIP Weekly: {len(restaurant_leads)} Restaurants + {len(hotel_leads)} Hotels ({now.strftime('%m/%d/%Y')})"
    
    if args.preview:
        print("\n" + "="*60)
        print("PREVIEW MODE - Email would contain:")
        print("="*60)
        print(f"Subject: {subject}")
        print(f"Recipients: {args.recipients or RECIPIENTS}")
        print(f"\nStats:")
        print(f"  Restaurants: {len(restaurant_leads)}")
        print(f"  Hotels: {len(hotel_leads)}")
        print(f"  Est. API Cost: ${api_costs['total']:.2f}")
        print("\nPlain text preview:")
        print(text[:2000] + "..." if len(text) > 2000 else text)
        return
    
    # Create CSV attachments
    attachments = {}
    
    restaurant_csv = create_leads_csv(restaurant_leads, "restaurant")
    if restaurant_csv:
        attachments[f"flhip_restaurants_{datetime.now().strftime('%Y%m%d')}.csv"] = restaurant_csv
        logging.info(f"[CSV] Created restaurant CSV with {len(restaurant_leads)} leads")
    
    hotel_csv = create_leads_csv(hotel_leads, "hotel")
    if hotel_csv:
        attachments[f"flhip_hotels_{datetime.now().strftime('%Y%m%d')}.csv"] = hotel_csv
        logging.info(f"[CSV] Created hotel CSV with {len(hotel_leads)} leads")
    
    # Send
    recipients = args.recipients or RECIPIENTS
    
    if args.test:
        subject = "[TEST] " + subject
        logging.info("Sending TEST email...")
    
    success = send_email(subject, html, text, recipients, attachments)
    
    if success:
        logging.info("[OK] Weekly report sent successfully!")
    else:
        logging.error("[ERROR] Failed to send weekly report")
        exit(1)


if __name__ == "__main__":
    main()
