#!/usr/bin/env python3
"""
Genera mini-siti statici per ogni lead e li deploya su Netlify.
"""
import csv, os, re, subprocess
from pathlib import Path
from jinja2 import Template

CSV_PATH = "leads_raw.csv"
BASE_DIR = Path.cwd()

TEMPLATE_HTML = """<!DOCTYPE html>
<html lang="it">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>{{ name }} - Demo</title>
  <meta name="description" content="Sito di prova per {{ name }} ({{ category }})">
  <style>
    body { font-family: system-ui, sans-serif; max-width: 600px; margin: 2rem auto; padding: 1rem; line-height: 1.6; }
    h1 { color: #1a1a2e; }
    .contact { background: #f5f5f5; padding: 1rem; border-radius: 8px; margin-top: 1rem; }
    .cta { display: inline-block; background: #1a1a2e; color: white; padding: 0.75rem 1.5rem; border-radius: 6px; text-decoration: none; margin-top: 1rem; }
  </style>
</head>
<body>
  <h1>{{ name }}</h1>
  <p>Categoria: {{ category }}</p>
  <p>Indirizzo: {{ address }}</p>
  <div class="contact">
    <p><strong>Telefono:</strong> {{ phone }}</p>
    <p><strong>Email:</strong> {{ email }}</p>
  </div>
  <a href="#" class="cta">Richiedi il sito completo</a>
</body>
</html>
"""

def slugify(s: str) -> str:
    return re.sub(r"[^a-z0-9]+", "-", s.lower()).strip("-")

def create_site(lead: dict) -> Path:
    folder = BASE_DIR / f"site_{slugify(lead['name'])}"
    folder.mkdir(parents=True, exist_ok=True)
    html = Template(TEMPLATE_HTML).render(**lead)
    (folder / "index.html").write_text(html, encoding="utf-8")
    return folder

def deploy_to_netlify(site_path: Path):
    token = os.environ.get("NETLIFY_TOKEN") or os.environ.get("NETLIFY_AUTH_TOKEN")
    if not token:
        print("⚠️ NETLIFY_TOKEN/NETLIFY_AUTH_TOKEN non definito, salto deploy")
        return
    # Usa l'auth token invece dell'opzione --token (non supportato da netlify-cli v2+)
    cmd = ["netlify", "deploy", "--prod", "--dir", str(site_path), "--auth", token]
    try:
        subprocess.run(cmd, check=True, capture_output=True, text=True)
        print(f"✅ Deployed {site_path.name} su Netlify")
    except subprocess.CalledProcessError as e:
        print(f"❌ Deploy failed for {site_path.name}: {e.stderr}")

def main():
    if not Path(CSV_PATH).exists():
        print(f"❌ {CSV_PATH} non trovato. Esegui prima scraper_maps.py")
        return
    
    with open(CSV_PATH, newline="", encoding="utf-8") as f:
        leads = list(csv.DictReader(f))
    
    print(f"🔍 Generating sites for {len(leads)} leads...")
    for lead in leads:
        site_path = create_site(lead)
        print(f"✅ Created: {site_path.name}")
        deploy_to_netlify(site_path)

if __name__ == "__main__":
    main()