#!/usr/bin/env python3
"""
Ghost Agency Follow-up - Invia follow-up automatici a 3 e 7 giorni.
"""

import os
import smtplib
import sqlite3
import random
import time
from datetime import datetime, timedelta
from email.message import EmailMessage
from pathlib import Path

BREVO_HOST = "smtp-relay.brevo.com"
BREVO_PORT = 587
BREVO_USER = os.environ.get("BREVO_USER")
BREVO_PASS = os.environ.get("BREVO_PASS")
FROM_EMAIL = os.environ.get("FROM_EMAIL", BREVO_USER)
FROM_NAME = "Amraj Singh"
DB_PATH = Path("leads.db")

if not BREVO_USER or not BREVO_PASS:
    print("❌ BREVO_USER e BREVO_PASS richiesti")
    exit(1)

def get_due_leads(con):
    """Lead che hanno ricevuto email 3+ giorni fa e non hanno follow-up"""
    three_days_ago = (datetime.utcnow() - timedelta(days=3)).isoformat()
    return con.execute("""
        SELECT id, name, category, email, mockup_url, sent_at
        FROM leads
        WHERE status = 'sent' 
        AND sent_at < ?
        AND followed_up_at IS NULL
        AND email IS NOT NULL
        LIMIT 20
    """, (three_days_ago,)).fetchall()

def get_week_due_leads(con):
    """Lead per follow-up a 7 giorni"""
    seven_days_ago = (datetime.utcnow() - timedelta(days=7)).isoformat()
    return con.execute("""
        SELECT id, name, category, email, mockup_url, sent_at
        FROM leads
        WHERE status = 'sent'
        AND sent_at < ?
        AND followed_up_at IS NOT NULL
        AND followed_up_at < sent_at  -- solo se non già fatto il 2° follow-up
        AND email IS NOT NULL
        LIMIT 20
    """, (seven_days_ago,)).fetchall()

def send_followup(lead, followup_number):
    name = lead["name"] or "la vostra attività"
    if followup_number == 1:
        subject = f"Re: sito per {name}"
        body = f"""Ciao,

torno solo per non lasciare la cosa a metà.

Il sito per {name} è sempre qui: {lead['mockup_url']}
Se lo volete, fatemi sapere entro la settimana — poi lo tolgo dal server.
Se non vi interessa, ditemi anche solo "no" e chiudo il discorso.

Buona giornata,
{FROM_NAME}
"""
    else:
        subject = f"Re: sito per {name} (ultimo messaggio)"
        body = f"""Ciao,

ultimo messaggio per {name}. Il mockup è ancora qui: {lead['mockup_url']}

Se non vi serve, non vi disturbo più. Se cambiate idea, rispondete pure.

{FROM_NAME}
"""
    msg = EmailMessage()
    msg["From"] = f"{FROM_NAME} <{FROM_EMAIL}>"
    msg["To"] = lead["email"]
    msg["Subject"] = subject
    msg["Reply-To"] = FROM_EMAIL
    msg.set_content(body)
    return msg

def send_email(msg):
    with smtplib.SMTP(BREVO_HOST, BREVO_PORT, timeout=30) as s:
        s.starttls()
        s.login(BREVO_USER, BREVO_PASS)
        s.send_message(msg)

def main():
    con = sqlite3.connect(DB_PATH)
    
    # Follow-up a 3 giorni
    due_3 = get_due_leads(con)
    print(f"📬 Follow-up 3 giorni: {len(due_3)} lead")
    
    for lid, name, cat, email, mockup, sent_at in due_3:
        lead = {"name": name, "category": cat, "email": email, "mockup_url": mockup}
        try:
            send_email(send_followup(lead, 1))
            con.execute("UPDATE leads SET followed_up_at = ? WHERE id = ?", 
                       (datetime.utcnow().isoformat(), lid))
            con.commit()
            print(f"[+] Follow-up 1 → {email}")
        except Exception as e:
            print(f"[!] {email}: {e}")
        time.sleep(random.randint(90, 240))
    
    # Follow-up a 7 giorni (solo se non già fatto)
    due_7 = get_week_due_leads(con)
    print(f"📬 Follow-up 7 giorni: {len(due_7)} lead")
    
    for lid, name, cat, email, mockup, sent_at in due_7:
        lead = {"name": name, "category": cat, "email": email, "mockup_url": mockup}
        try:
            send_email(send_followup(lead, 2))
            con.execute("UPDATE leads SET followed_up_at = ? WHERE id = ?", 
                       (datetime.utcnow().isoformat(), lid))
            con.commit()
            print(f"[+] Follow-up 2 → {email}")
        except Exception as e:
            print(f"[!] {email}: {e}")
        time.sleep(random.randint(90, 240))

if __name__ == "__main__":
    main()