#!/usr/bin/env python3
"""
Quick test - process only first 3 leads
"""
import sys
sys.path.insert(0, '/home/ubuntu/GhostAgency')

# Import the functions we need
from ghost_radar_v3 import *
import time

# Monkey-patch to only process 3 leads
original_run_radar = run_radar

def quick_test():
    print(f"\n{'='*60}")
    print(f" GHOST AGENCY RADAR v3 - QUICK TEST (3 leads)")
    print(f"{'='*60}\n")
    
    create_seed_if_missing()
    
    with open(SEED_CSV, newline="", encoding="utf-8") as f:
        reader = csv.DictReader(f)
        leads = list(reader)[:3]  # ONLY FIRST 3
    
    print(f"[*] Caricate {len(leads)} attività dal seed (test mode)\n")
    
    existing_emails = set()
    sent_file = OUTPUT_DIR / "sent_emails.json"
    if sent_file.exists():
        with open(sent_file) as f:
            sent_emails = set(json.load(f))
        existing_emails = {e.lower() for e in sent_emails}
    
    valid_leads = []
    call_leads = []
    
    for i, row in enumerate(leads, 1):
        nome = row["nome"].strip()
        telefono = row["telefono"].strip()
        indirizzo = row["indirizzo"].strip()
        categoria = row["categoria"].strip()
        
        print(f"\n[{i}/{len(leads)}] {nome} ({categoria})")
        
        email, source = find_email_for_lead(nome, telefono, indirizzo, categoria)
        
        if email:
            email_lower = email.lower()
            if email_lower in existing_emails:
                print(f"    [=] Già in database: {email}")
                continue
            
            lead = {
                "Nome": nome,
                "Email": email,
                "Telefono": telefono,
                "Indirizzo": indirizzo,
                "Categoria": categoria,
                "Fonte": source,
                "Data": datetime.now().strftime("%Y-%m-%d")
            }
            valid_leads.append(lead)
            existing_emails.add(email_lower)
            print(f"    [+] LEAD CON EMAIL: {nome} | {email} ({source})")
        else:
            lead = {
                "Nome": nome,
                "Telefono": telefono,
                "Indirizzo": indirizzo,
                "Categoria": categoria,
                "Data": datetime.now().strftime("%Y-%m-%d")
            }
            call_leads.append(lead)
            print(f"    [-] CALL LIST: {nome} | {telefono}")
        
        time.sleep(SCRAPE_DELAY)
    
    print(f"\n{'='*60}")
    print(f"RISULTATO TEST: {len(valid_leads)} lead con email, {len(call_leads)} call list")
    print(f"{'='*60}")
    
    # Save test output
    if valid_leads:
        timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
        filename = f"leads_parma_{timestamp}_test.csv"
        filepath = OUTPUT_DIR / filename
        
        fieldnames = ["Nome", "Email", "Telefono", "Indirizzo", "Categoria", "Fonte", "Data"]
        with open(filepath, "w", newline="", encoding="utf-8") as f:
            writer = csv.DictWriter(f, fieldnames=fieldnames)
            writer.writeheader()
            writer.writerows(valid_leads)
        print(f"[+] Salvati {len(valid_leads)} lead in {filename}")

if __name__ == "__main__":
    quick_test()