"""
FLHIP Scraper v3 - Hotel Email Sender
Sends weekly hotel lead summary to client
"""

import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from datetime import datetime
from hotel_config import EMAIL_CONFIG


def format_leads_html(leads: list[dict], stats: dict) -> str:
    """Format hotel leads as HTML email body."""
    
    now = datetime.now().strftime("%B %d, %Y")
    
    html = f"""
    <html>
    <head>
        <style>
            body {{ font-family: Arial, sans-serif; line-height: 1.4; color: #333; font-size: 12px; }}
            h1 {{ color: #2c5282; }}
            h2 {{ color: #4a5568; border-bottom: 1px solid #e2e8f0; padding-bottom: 8px; }}
            .stats {{ background: #f7fafc; padding: 15px; border-radius: 8px; margin: 20px 0; }}
            .stat {{ display: inline-block; margin-right: 30px; }}
            .stat-value {{ font-size: 24px; font-weight: bold; color: #2c5282; }}
            .stat-label {{ font-size: 12px; color: #718096; }}
            table {{ border-collapse: collapse; width: 100%; margin: 20px 0; font-size: 11px; }}
            th {{ background: #4a5568; color: white; padding: 8px; text-align: left; }}
            td {{ border: 1px solid #e2e8f0; padding: 6px; vertical-align: top; }}
            tr:nth-child(even) {{ background: #f7fafc; }}
            .footer {{ margin-top: 30px; padding-top: 20px; border-top: 1px solid #e2e8f0; font-size: 12px; color: #718096; }}
        </style>
    </head>
    <body>
        <h1>FLHIP Weekly Hotel Leads</h1>
        <p>Report generated: {now}</p>
        
        <div class="stats">
            <div class="stat">
                <div class="stat-value">{stats.get('inserted', 0)}</div>
                <div class="stat-label">New Hotel Leads</div>
            </div>
            <div class="stat">
                <div class="stat-value">{stats.get('duplicates', 0)}</div>
                <div class="stat-label">Duplicates Skipped</div>
            </div>
            <div class="stat">
                <div class="stat-value">{stats.get('total', 0)}</div>
                <div class="stat-label">Articles Processed</div>
            </div>
        </div>
        
        <h2>New Hotel Opening Leads</h2>
    """
    
    if not leads:
        html += "<p>No new hotel leads found this week.</p>"
    else:
        html += """
        <table>
            <tr>
                <th>County</th>
                <th>Hotel Name</th>
                <th>Address</th>
                <th>City</th>
                <th>State</th>
                <th>Zip</th>
                <th>Lat</th>
                <th>Long</th>
                <th>Phone</th>
                <th>Contact Name</th>
                <th>Contact E-mail</th>
                <th>Info Source</th>
                <th>Internet Info</th>
                <th>Opening Date</th>
                <th>Notes</th>
            </tr>
        """
        
        for lead in leads:
            business = lead.get('business') or lead.get('business_name') or ''
            
            html += f"""
            <tr>
                <td>{lead.get('county') or ''}</td>
                <td>{business}</td>
                <td>{lead.get('address') or ''}</td>
                <td>{lead.get('city') or ''}</td>
                <td>{lead.get('state') or ''}</td>
                <td>{lead.get('zip') or ''}</td>
                <td>{lead.get('lat') or ''}</td>
                <td>{lead.get('lng') or ''}</td>
                <td>{lead.get('phone') or ''}</td>
                <td>{lead.get('contact_name') or ''}</td>
                <td>{lead.get('contact_email') or ''}</td>
                <td>{lead.get('info_source') or ''}</td>
                <td>{lead.get('internet_info') or ''}</td>
                <td>{lead.get('opening_date') or ''}</td>
                <td>{lead.get('notes') or ''}</td>
            </tr>
            """
        
        html += "</table>"
    
    html += f"""
        <div class="footer">
            <p style="margin-top: 15px;">Generated by FLHIP Hotel Scraper v3</p>
            <p>Owner: Ken Roberts - <a href="mailto:ken@flhip.com">ken@flhip.com</a></p>
            <p>Technical Support: <a href="mailto:projects@verowebconsulting.com">projects@verowebconsulting.com</a></p>
        </div>
    </body>
    </html>
    """
    
    return html


def format_leads_text(leads: list[dict], stats: dict) -> str:
    """Format hotel leads as plain text email body."""
    
    now = datetime.now().strftime("%B %d, %Y")
    
    text = f"""
FLHIP Weekly Hotel Leads
Report generated: {now}

SUMMARY
-------
New Hotel Leads: {stats.get('inserted', 0)}
Duplicates Skipped: {stats.get('duplicates', 0)}
Articles Processed: {stats.get('total', 0)}

NEW HOTEL OPENING LEADS
-----------------------
"""
    
    if not leads:
        text += "No new hotel leads found this week.\n"
    else:
        for i, lead in enumerate(leads, 1):
            business = lead.get('business') or lead.get('business_name') or ''
            text += f"""
{i}. {business}
   Address: {lead.get('address') or ''}
   City: {lead.get('city') or ''}, {lead.get('state') or ''} {lead.get('zip') or ''}
   Opening Date: {lead.get('opening_date') or ''}
   Phone: {lead.get('phone') or ''}
   Contact: {lead.get('contact_name') or ''}
   Email: {lead.get('contact_email') or ''}
   Source: {lead.get('info_source') or ''}
   Notes: {lead.get('notes') or ''}
"""
    
    text += """
---
Generated by FLHIP Hotel Scraper v3
Owner: Ken Roberts - ken@flhip.com
Technical Support: projects@verowebconsulting.com
"""
    
    return text


def send_lead_email(leads: list[dict], stats: dict) -> bool:
    """Send the weekly hotel lead email."""
    
    if not EMAIL_CONFIG.get("smtp_user") or not EMAIL_CONFIG.get("to_addresses"):
        print("Email not configured - skipping send")
        return False
    
    try:
        # Create message
        msg = MIMEMultipart("alternative")
        msg["Subject"] = f"FLHIP Weekly Hotel Leads: {stats.get('inserted', 0)} New Hotel Openings"
        msg["From"] = EMAIL_CONFIG["from_address"]
        msg["To"] = ", ".join(EMAIL_CONFIG["to_addresses"])
        
        # Attach both plain text and HTML versions
        text_part = MIMEText(format_leads_text(leads, stats), "plain", "utf-8")
        html_part = MIMEText(format_leads_html(leads, stats), "html", "utf-8")
        
        msg.attach(text_part)
        msg.attach(html_part)
        
        # Send
        with smtplib.SMTP(EMAIL_CONFIG["smtp_host"], EMAIL_CONFIG["smtp_port"]) as server:
            server.starttls()
            server.login(EMAIL_CONFIG["smtp_user"], EMAIL_CONFIG["smtp_password"])
            server.send_message(msg)
        
        print(f"Hotel email sent to {len(EMAIL_CONFIG['to_addresses'])} recipients")
        return True
        
    except Exception as e:
        print(f"Email error: {e}")
        return False


if __name__ == "__main__":
    # Test with sample data
    sample_leads = [
        {
            "business": "Marriott Downtown",
            "city": "Austin",
            "state": "TX",
            "address": "500 Congress Ave",
            "zip": "78701",
            "opening_date": "2026-04-15",
            "contact_name": "John Smith",
            "contact_email": "john@marriott.com",
            "phone": "512-555-0123",
            "info_source": "https://example.com/article",
            "internet_info": "https://google.com/alerts/feeds/...",
            "notes": "250-room hotel with rooftop bar and conference center"
        }
    ]
    
    sample_stats = {
        "total": 50,
        "inserted": 10,
        "duplicates": 5,
        "errors": 0
    }
    
    html = format_leads_html(sample_leads, sample_stats)
    with open("/tmp/hotel_email_preview.html", "w") as f:
        f.write(html)
    print("Hotel email preview saved to /tmp/hotel_email_preview.html")
    
    text = format_leads_text(sample_leads, sample_stats)
    print(text)
