#!/usr/bin/env python3
"""
Ghost Agency Mockup Generator v2 - Siti ricchi per conversione.
- Foto placeholder reali (Unsplash source)
- Orari, indirizzo, telefono integrati
- Bottone WhatsApp diretto
- Form contatti → webhook Telegram
- Varianti colore per settore
- SEO meta tags
"""
import csv, os, re, subprocess
from pathlib import Path
from jinja2 import Template

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

# Palette colori per settore
SECTOR_COLORS = {
    "ristorante": {"primary": "#c0392b", "secondary": "#e74c3c", "accent": "#f39c12", "bg": "#fdf2f2"},
    "dentista": {"primary": "#1e3a8a", "secondary": "#3b82f6", "accent": "#06b6d4", "bg": "#eff6ff"},
    "palestra": {"primary": "#166534", "secondary": "#22c55e", "accent": "#84cc16", "bg": "#f0fdf4"},
    "parrucchiere": {"primary": "#9d174d", "secondary": "#ec4899", "accent": "#f43f5e", "bg": "#fdf2f8"},
    "avvocato": {"primary": "#1e293b", "secondary": "#334155", "accent": "#64748b", "bg": "#f8fafc"},
    "idraulico": {"primary": "#075985", "secondary": "#0ea5e9", "accent": "#22d3ee", "bg": "#f0f9ff"},
    "estetista": {"primary": "#86198f", "secondary": "#d946ef", "accent": "#f0abfc", "bg": "#faf5ff"},
}
DEFAULT_COLORS = {"primary": "#1a1a2e", "secondary": "#333", "accent": "#6366f1", "bg": "#f5f5f5"}

# Foto placeholder per settore (Unsplash source - veloce, no API key)
SECTOR_IMAGES = {
    "ristorante": "https://images.unsplash.com/photo-1517248135467-4c7edcad34c4?w=800&q=80",
    "dentista": "https://images.unsplash.com/photo-1606811842175-8b5a1c9e2b0e?w=800&q=80",
    "palestra": "https://images.unsplash.com/photo-1534438327276-14e5300c3a48?w=800&q=80",
    "parrucchiere": "https://images.unsplash.com/photo-1560066984-138dadb4c035?w=800&q=80",
    "avvocato": "https://images.unsplash.com/photo-1589829545856-d10d557cf95f?w=800&q=80",
    "idraulico": "https://images.unsplash.com/photo-1607472586893-edb57bdc0e39?w=800&q=80",
    "estetista": "https://images.unsplash.com/photo-1616394584738-fc6e612e71b9?w=800&q=80",
}
DEFAULT_IMAGE = "https://images.unsplash.com/photo-1497366216548-37526070297c?w=800&q=80"

# Orari standard per settore
SECTOR_HOURS = {
    "ristorante": {"lun-ven": "12:00-15:00, 19:00-23:00", "sab": "12:00-15:00, 19:00-23:30", "dom": "Chiuso"},
    "dentista": {"lun-ven": "09:00-13:00, 14:30-19:00", "sab": "09:00-13:00", "dom": "Chiuso"},
    "palestra": {"lun-ven": "06:00-23:00", "sab": "08:00-20:00", "dom": "09:00-18:00"},
    "parrucchiere": {"lun-ven": "09:00-19:00", "sab": "09:00-18:00", "dom": "Chiuso"},
    "avvocato": {"lun-ven": "09:00-13:00, 14:30-18:30", "sab": "Su appuntamento", "dom": "Chiuso"},
    "idraulico": {"lun-ven": "08:00-18:00", "sab": "08:00-13:00", "dom": "Solo emergenze"},
    "estetista": {"lun-ven": "09:00-19:00", "sab": "09:00-18:00", "dom": "Chiuso"},
}

TEMPLATE_HTML = """<!DOCTYPE html>
<html lang="it">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta name="description" content="{{ meta_description }}">
  <meta name="theme-color" content="{{ colors.primary }}">
  <title>{{ name }} - {{ category_title }} a {{ city_display }}</title>
  <meta property="og:title" content="{{ name }} - {{ category_title }}">
  <meta property="og:description" content="{{ meta_description }}">
  <meta property="og:image" content="{{ hero_image }}">
  <meta property="og:type" content="website">
  <link rel="preconnect" href="https://images.unsplash.com">
  <link rel="preconnect" href="https://api.telegram.org">
  <style>
    * { box-sizing: border-box; margin: 0; padding: 0; }
    :root {
      --primary: {{ colors.primary }};
      --secondary: {{ colors.secondary }};
      --accent: {{ colors.accent }};
      --bg: {{ colors.bg }};
      --text: #1a1a2e;
      --text-light: #64748b;
      --white: #ffffff;
    }
    body {
      font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
      line-height: 1.6;
      color: var(--text);
      background: var(--bg);
    }
    .hero {
      position: relative;
      height: 60vh;
      min-height: 350px;
      max-height: 500px;
      background: linear-gradient(135deg, var(--primary) 0%, var(--secondary) 100%),
                  url('{{ hero_image }}') center/cover no-repeat;
      background-blend-mode: overlay;
      display: flex;
      align-items: flex-end;
      padding: 2rem;
      color: var(--white);
    }
    .hero::before {
      content: '';
      position: absolute;
      inset: 0;
      background: linear-gradient(180deg, transparent 40%, rgba(0,0,0,0.7) 100%);
    }
    .hero-content { position: relative; z-index: 1; max-width: 800px; margin: 0 auto; width: 100%; }
    .hero h1 { font-size: clamp(2rem, 5vw, 3.5rem); font-weight: 800; margin-bottom: 0.5rem; text-shadow: 0 2px 8px rgba(0,0,0,0.3); }
    .hero .category-badge {
      display: inline-block;
      background: rgba(255,255,255,0.2);
      backdrop-filter: blur(10px);
      padding: 0.5rem 1.5rem;
      border-radius: 50px;
      font-size: 1rem;
      font-weight: 600;
    }
    .container { max-width: 1000px; margin: 0 auto; padding: 2rem; }
    .grid { display: grid; grid-template-columns: 1fr 1fr; gap: 2rem; margin-top: 2rem; }
    @media (max-width: 768px) { .grid { grid-template-columns: 1fr; } }
    .card {
      background: var(--white);
      border-radius: 16px;
      padding: 2rem;
      box-shadow: 0 4px 24px rgba(0,0,0,0.08);
      border: 1px solid rgba(0,0,0,0.05);
      transition: transform 0.2s, box-shadow 0.2s;
    }
    .card:hover { transform: translateY(-4px); box-shadow: 0 12px 40px rgba(0,0,0,0.12); }
    .card h2 { font-size: 1.25rem; font-weight: 700; color: var(--primary); margin-bottom: 1rem; display: flex; align-items: center; gap: 0.5rem; }
    .card h2::before { content: ''; width: 8px; height: 8px; border-radius: 50%; background: var(--accent); }
    .info-row { display: flex; align-items: flex-start; gap: 1rem; margin-bottom: 1rem; padding-bottom: 1rem; border-bottom: 1px solid #f1f5f9; }
    .info-row:last-child { border-bottom: none; margin-bottom: 0; padding-bottom: 0; }
    .info-icon { width: 40px; height: 40px; border-radius: 12px; background: var(--bg); display: flex; align-items: center; justify-content: center; color: var(--primary); flex-shrink: 0; }
    .info-content h3 { font-size: 0.875rem; font-weight: 600; color: var(--text-light); margin-bottom: 0.25rem; }
    .info-content p { font-size: 1rem; color: var(--text); }
    .hours-table { width: 100%; border-collapse: collapse; }
    .hours-table td { padding: 0.75rem 0; border-bottom: 1px solid #f1f5f9; }
    .hours-table td:first-child { font-weight: 600; color: var(--text); width: 40%; }
    .hours-table td:last-child { color: var(--text-light); text-align: right; }
    .hours-table tr:last-child td { border-bottom: none; }
    .cta-section { text-align: center; margin: 3rem 0; padding: 2rem; background: linear-gradient(135deg, var(--primary) 0%, var(--secondary) 100%); border-radius: 16px; color: var(--white); }
    .cta-section h2 { font-size: 1.5rem; margin-bottom: 0.5rem; }
    .cta-section p { opacity: 0.9; margin-bottom: 1.5rem; }
    .btn {
      display: inline-flex;
      align-items: center;
      gap: 0.5rem;
      padding: 1rem 2rem;
      border-radius: 12px;
      font-weight: 700;
      font-size: 1.1rem;
      text-decoration: none;
      transition: all 0.2s;
      border: none;
      cursor: pointer;
    }
    .btn-primary { background: var(--white); color: var(--primary); box-shadow: 0 4px 20px rgba(0,0,0,0.2); }
    .btn-primary:hover { transform: translateY(-2px); box-shadow: 0 8px 30px rgba(0,0,0,0.3); }
    .btn-whatsapp { background: #25d366; color: var(--white); }
    .btn-whatsapp:hover { background: #128c7e; transform: translateY(-2px); }
    .btn-group { display: flex; gap: 1rem; justify-content: center; flex-wrap: wrap; }
    .form-section { background: var(--white); border-radius: 16px; padding: 2rem; box-shadow: 0 4px 24px rgba(0,0,0,0.08); }
    .form-group { margin-bottom: 1.5rem; }
    .form-group label { display: block; font-weight: 600; margin-bottom: 0.5rem; color: var(--text); }
    .form-group input, .form-group textarea {
      width: 100%; padding: 1rem; border: 2px solid #e2e8f0; border-radius: 10px;
      font-size: 1rem; font-family: inherit; transition: border-color 0.2s, box-shadow 0.2s;
    }
    .form-group input:focus, .form-group textarea:focus {
      outline: none; border-color: var(--primary); box-shadow: 0 0 0 3px color-mix(in srgb, var(--primary) 20%, transparent);
    }
    .form-group textarea { min-height: 120px; resize: vertical; }
    .trust-signals { display: flex; gap: 2rem; justify-content: center; flex-wrap: wrap; margin-top: 3rem; padding-top: 2rem; border-top: 1px solid #e2e8f0; }
    .trust-item { text-align: center; color: var(--text-light); font-size: 0.875rem; }
    .trust-item svg { width: 32px; height: 32px; margin-bottom: 0.5rem; color: var(--accent); }
    footer { text-align: center; padding: 2rem; color: var(--text-light); font-size: 0.875rem; border-top: 1px solid #e2e8f0; margin-top: 3rem; }
    .mockup-badge {
      position: fixed; bottom: 1rem; right: 1rem;
      background: rgba(0,0,0,0.8); color: white;
      padding: 0.5rem 1rem; border-radius: 8px;
      font-size: 0.75rem; z-index: 1000;
      backdrop-filter: blur(10px);
    }
    @keyframes fadeInUp { from { opacity: 0; transform: translateY(20px); } to { opacity: 1; transform: translateY(0); } }
    .animate-in { animation: fadeInUp 0.6s ease-out forwards; }
    .delay-1 { animation-delay: 0.1s; opacity: 0; }
    .delay-2 { animation-delay: 0.2s; opacity: 0; }
    .delay-3 { animation-delay: 0.3s; opacity: 0; }
  </style>
</head>
<body>
  <div class="hero animate-in">
    <div class="hero-content">
      <h1>{{ name }}</h1>
      <span class="category-badge">{{ category_title }} a {{ city_display }}</span>
    </div>
  </div>

  <div class="container">
    <div class="grid">
      <div class="card animate-in delay-1">
        <h2>📍 Contatti e Orari</h2>
        {% if address %}
        <div class="info-row">
          <div class="info-icon"><svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 10c0 7-9 13-9 13s-9-6-9-13a9 9 0 0 1 18 0z"></path><circle cx="12" cy="10" r="3"></circle></svg></div>
          <div class="info-content"><h3>Indirizzo</h3><p>{{ address }}</p></div>
        </div>
        {% endif %}
        {% if phone %}
        <div class="info-row">
          <div class="info-icon"><svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M22 16.92v3a2 2 0 0 1-2.18 2 19.79 19.79 0 0 1-8.63-3.07 19.5 19.5 0 0 1-6-6 19.79 19.79 0 0 1-3.07-8.67A2 2 0 0 1 4.11 2h3a2 2 0 0 1 2 1.72 12.84 12.84 0 0 0 .7 2.81 2 2 0 0 1-.45 2.11L8.09 9.91a16 16 0 0 0 6 6l1.27-1.27a2 2 0 0 1 2.11-.45 12.84 12.84 0 0 0 2.81.7A2 2 0 0 1 22 16.92z"></svg></div>
          <div class="info-content"><h3>Telefono</h3><p><a href="tel:{{ phone }}" style="color: inherit; text-decoration: none;">{{ phone }}</a></p></div>
        </div>
        {% endif %}
        {% if email %}
        <div class="info-row">
          <div class="info-icon"><svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M4 4h16c1.1 0 2 .9 2 2v12c0 1.1-.9 2-2 2H4c-1.1 0-2-.9-2-2V6c0-1.1.9-2 2-2z"></path><polyline points="22,6 12,13 2,6"></polyline></svg></div>
          <div class="info-content"><h3>Email</h3><p><a href="mailto:{{ email }}" style="color: inherit; text-decoration: none;">{{ email }}</a></p></div>
        </div>
        {% endif %}
        <div class="info-row">
          <div class="info-icon"><svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="4" width="18" height="18" rx="2" ry="2"></rect><line x1="16" y1="2" x2="16" y2="6"></line><line x1="8" y1="2" x2="8" y2="6"></line><line x1="3" y1="10" x2="21" y2="10"></line></svg></div>
          <div class="info-content">
            <h3>Orari di apertura</h3>
            <table class="hours-table">
              <tr><td>Lunedì - Venerdì</td><td>{{ hours.lun_ven }}</td></tr>
              <tr><td>Sabato</td><td>{{ hours.sab }}</td></tr>
              <tr><td>Domenica</td><td>{{ hours.dom }}</td></tr>
            </table>
          </div>
        </div>
      </div>

      <div class="card animate-in delay-2">
        <h2>💬 Contattaci Subito</h2>
        <div class="btn-group" style="flex-direction: column;">
          {% if phone %}
          <a href="https://wa.me/{{ phone_wa }}" class="btn btn-whatsapp" target="_blank" rel="noopener">
            <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="currentColor"><path d="M17.472 14.382c-.297-.149-1.758-.867-2.03-.967-.273-.099-.471-.148-.67.15-.197.297-.767.966-.94 1.164-.173.199-.347.223-.644.075-.297-.15-1.255-.463-2.39-1.475-.883-.788-1.48-1.48-1.653-1.68-.173-.2-.017-.271.085-.362.098-.093.198-.147.306-.147.12 0 .256.047.378.047.12 0 .085-.053-.022-.164-.107-.216-.653-.82-1.203-1.723-.377-.63-.63-1.263-.763-1.388-.173-.173-.359-.173-.53 0-.21.21-.624.528-1.246 1.15-.642.642-1.202 1.26-1.202 1.388 0 .108.017.198.067.287.038.09.21.22.452.553.21.29.47.815.65 1.336.228.64.518 1.31.748 1.95.23.64.36 1.267.44 1.5.09.23.05.3-.086.455-.17.17-.37.22-.717.075-.25-.1-.972-.888-1.15-1.1-.149-.17-.15-.186-.307-.002l-.92.92c-.105.115-.218.2-.314.265-.202.133-.52.265-.91.214-.478-.057-1.14-.34-1.48-.722-.32-.37-.52-.815-.58-1.17-.04-.27.13-.57.44-.82.34-.27.78-.52 1.22-.79.44-.26.91-.48 1.33-.68.51-.22 1.03-.41 1.57-.54.5-.14 1.1-.27 1.6-.41.54-.15 1.08-.18 1.63-.1.55.08 1.28.06 1.75.02.28 0 .36-.23.57-.46.3-.3.53-.94.53-1.65V10.5c0-.55-.18-1.1-.46-1.6-.3-.5-.77-1-1.4-1.4-.63-.4-1.4-.63-1.6-.77-.4-.13-.9-.2-.1.5-.1.4.4.7 1.1.7.4 0 .7-.17 1-.37.33-.21.72-.47 1.1-.77.38-.3.7-.73 1.1-1.2.4-.47.7-1.07.9-1.6.2-.53.3-1.1.3-1.6 0-.47-.1-.8-.23-1.13-.14-.3-.46-.46-.78-.46-.25 0-.48.08-.7.22-.22.14-.52.38-.8.62-.28.24-.54.55-.78.9-.24.35-.4.78-.54 1.2-.14.43-.1.9-.02 1.3.08.4.28.8.52 1.2.24.4.52.84.85 1.25.33.41.7.85 1.1 1.3.4.45.82.93 1.2 1.4.38.47.75 1 .75 1.6 0 .48-.1.94-.23 1.37-.13.43-.27.83-.4.98-.13.14-.13.13-.3.13s-.18-.02-.27-.1c-.1-.1-.2-.2-.3-.3-.1-.1-.2-.1-.3 0-.1.1-.15.2-.3.3-.33.24-.68.35-1.03.35-.3 0-.6-.1-.9-.25-.3-.15-.6-.34-.9-.57-.3-.23-.6-.5-.85-.8-.25-.3-.45-.65-.6-1.05-.15-.4-.2-.85-.1-1.25.1-.4.3-.7.6-.95.3-.25.7-.4 1.1-.5.4-.1.8-.1 1.2 0 .4.1.7.3 1 .5.3.2.5.5.7.9.2.4.3.9.3 1.3 0 .5-.1 1-.1 1.5 0 .6.2 1.2.5 1.7.3.5.7.9 1.2 1.2.5.3 1 .5 1.5.6.5.1 1 .05 1.5-.1.5-.15 1-.4 1.4-.8.4-.4.7-.9.9-1.5.2-.6.2-1.3.1-1.9 0-.1-.05-.2-.1-.3-.05-.1-.1-.2-.2-.3-.1-.1-.2-.2-.3-.3-.1-.1-.2-.1-.3 0z"></path></svg>
            Scrivimi su WhatsApp
          </a>
          {% endif %}
          <a href="tel:{{ phone }}" class="btn btn-primary" style="justify-content: center;">
            <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M22 16.92v3a2 2 0 0 1-2.18 2 19.79 19.79 0 0 1-8.63-3.07 19.5 19.5 0 0 1-6-6 19.79 19.79 0 0 1-3.07-8.67A2 2 0 0 1 4.11 2h3a2 2 0 0 1 2 1.72 12.84 12.84 0 0 0 .7 2.81 2 2 0 0 1-.45 2.11L8.09 9.91a16 16 0 0 0 6 6l1.27-1.27a2 2 0 0 1 2.11-.45 12.84 12.84 0 0 0 2.81.7A2 2 0 0 1 22 16.92z"></svg>
            Chiama ora
          </a>
        </div>
      </div>
    </div>

    <div class="cta-section animate-in delay-3">
      <h2>Vuoi il sito completo?</h2>
      <p>Trasformiamo questo mockup in un sito professionale: SEO, prenotazioni online, blog, multilingua.</p>
      <div class="btn-group">
        <a href="#contatti" class="btn btn-primary">Richiedi preventivo gratuito</a>
        {% if phone %}
        <a href="https://wa.me/{{ phone_wa }}" class="btn btn-whatsapp" target="_blank" rel="noopener">
          <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="currentColor"><path d="M17.472 14.382c-.297-.149-1.758-.867-2.03-.967-.273-.099-.471-.148-.67.15-.197.297-.767.966-.94 1.164-.173.199-.347.223-.644.075-.297-.15-1.255-.463-2.39-1.475-.883-.788-1.48-1.48-1.653-1.68-.173-.2-.017-.271.085-.362.098-.093.198-.147.306-.147.12 0 .256.047.378.047.12 0 .085-.053-.022-.164-.107-.216-.653-.82-1.203-1.723-.377-.63-.63-1.263-.763-1.388-.173-.173-.359-.173-.53 0-.21.21-.624.528-1.246 1.15-.642.642-1.202 1.26-1.202 1.388 0 .108.017.198.067.287.038.09.21.22.452.553.21.29.47.815.65 1.336.228.64.518 1.31.748 1.95.23.64.36 1.267.44 1.5.09.23.05.3-.086.455-.17.17-.37.22-.717.075-.25-.1-.972-.888-1.15-1.1-.149-.17-.15-.186-.307-.002l-.92.92c-.105.115-.218.2-.314.265-.202.133-.52.265-.91.214-.478-.057-1.14-.34-1.48-.722-.32-.37-.52-.815-.58-1.17-.04-.27.13-.57.44-.82.34-.27.78-.52 1.22-.79.44-.26.91-.48 1.33-.68.51-.22 1.03-.41 1.57-.54.5-.14 1.1-.27 1.6-.41.54-.15 1.08-.18 1.63-.1.55.08 1.28.06 1.75.02.28 0 .36-.23.57-.46.3-.3.53-.94.53-1.65V10.5c0-.55-.18-1.1-.46-1.6-.3-.5-.77-1-1.4-1.4-.63-.4-1.4-.63-1.6-.77-.4-.13-.9-.2-.1.5-.1.4.4.7 1.1.7.4 0 .7-.17 1-.37.33-.21.72-.47 1.1-.77.38-.3.7-.73 1.1-1.2.4-.47.7-1.07.9-1.6.2-.53.3-1.1.3-1.6 0-.47-.1-.8-.23-1.13-.14-.3-.46-.46-.78-.46-.25 0-.48.08-.7.22-.22.14-.52.38-.8.62-.28.24-.54.55-.78.9-.24.35-.4.78-.54 1.2-.14.43-.1.9-.02 1.3.08.4.28.8.52 1.2.24.4.52.84.85 1.25.33.41.7.85 1.1 1.3.4.45.82.93 1.2 1.4.38.47.75 1 .75 1.6 0 .48-.1.94-.23 1.37-.13.43-.27.83-.4.98-.13.14-.13.13-.3.13s-.18-.02-.27-.1c-.1-.1-.2-.2-.3-.3-.1-.1-.2-.1-.3 0-.1.1-.15.2-.3.3-.33.24-.68.35-1.03.35-.3 0-.6-.1-.9-.25-.3-.15-.6-.34-.9-.57-.3-.23-.6-.5-.85-.8-.25-.3-.45-.65-.6-1.05-.15-.4-.2-.85-.1-1.25.1-.4.3-.7.6-.95.3-.25.7-.4 1.1-.5.4-.1.8-.1 1.2 0 .4.1.7.3 1 .5.3.2.5.5.7.9.2.4.3.9.3 1.3 0 .5-.1 1-.1 1.5 0 .6.2 1.2.5 1.7.3.5.7.9 1.2 1.2.5.3 1 .5 1.5.6.5.1 1 .05 1.5-.1.5-.15 1-.4 1.4-.8.4-.4.7-.9.9-1.5.2-.6.2-1.3.1-1.9 0-.1-.05-.2-.1-.3-.05-.1-.1-.2-.2-.3-.1-.1-.2-.2-.3-.3-.1-.1-.2-.2-.3-.3z"></path></svg>
          Parla su WhatsApp
        </a>
        {% endif %}
      </div>
    </div>

    <div class="form-section animate-in" id="contatti">
      <h2 style="font-size: 1.5rem; margin-bottom: 1.5rem; color: var(--primary);">📝 Richiedi il tuo sito completo</h2>
      <form id="contactForm" action="https://api.telegram.org/bot{{ telegram_bot_token }}/sendMessage" method="POST" target="_blank">
        <input type="hidden" name="chat_id" value="{{ telegram_chat_id }}">
        <input type="hidden" name="parse_mode" value="HTML">
        <input type="hidden" name="text" value="
🆕 <b>Nuova richiesta sito</b>
🏢 <b>Attività:</b> {{ name }}
📍 <b>Categoria:</b> {{ category }}
📞 <b>Telefono:</b> {{ phone }}
📧 <b>Email:</b> {{ email }}
🌐 <b>Mockup:</b> {{ mockup_url }}
💬 <b>Messaggio:</b> {{ message_placeholder }}
        ">
        <div class="form-group">
          <label for="nome">Il tuo nome</label>
          <input type="text" id="nome" name="nome" placeholder="Mario Rossi" required>
        </div>
        <div class="form-group">
          <label for="telefono">Telefono</label>
          <input type="tel" id="telefono" name="telefono" placeholder="+39 3XX XXXXXXX" value="{{ phone }}" required>
        </div>
        <div class="form-group">
          <label for="email">Email</label>
          <input type="email" id="email" name="email" placeholder="mario@esempio.it" value="{{ email }}" required>
        </div>
        <div class="form-group">
          <label for="messaggio">Cosa ti serve? (opzionale)</label>
          <textarea id="messaggio" name="messaggio" placeholder="Es: Vorrei un sito con prenotazioni online, menu digitale, blog ricette..."></textarea>
        </div>
        <button type="submit" class="btn btn-primary" style="width: 100%; justify-content: center; font-size: 1.1rem; padding: 1.25rem;">
          <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="22" y1="2" x2="11" y2="13"></line><polygon points="22 2 15 22 11 13 2 9 22 2"></polygon></svg>
          Invia richiesta - Ti rispondo in 24h
        </button>
      </form>
    </div>

    <div class="trust-signals">
      <div class="trust-item">
        <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"></path></svg>
        <div>Pagamento sicuro</div>
      </div>
      <div class="trust-item">
        <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><rect x="2" y="3" width="20" height="14" rx="2"></rect><line x1="8" y1="21" x2="16" y2="21"></line><line x1="12" y1="17" x2="12" y2="21"></line></svg>
        <div>Online in 24h</div>
      </div>
      <div class="trust-item">
        <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M21 12.79A9 9 0 1 1 14.21 3 7 7 0 0 0 21 12.79z"></path></svg>
        <div>SEO incluso</div>
      </div>
      <div class="trust-item">
        <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M18 8A6 6 0 0 0 6 8c0 7-3 9-3 9h18s-3-2-3-9"></path><path d="M13.73 21a2 2 0 0 1-3.46 0"></path></svg>
        <div>Supporto 7/7</div>
      </div>
    </div>
  </div>

  <footer>
    <p>Mockup dimostrativo per <strong>{{ name }}</strong> • Sito completo a 350€ una tantum • <a href="mailto:{{ FROM_EMAIL }}" style="color: var(--accent);">Contattaci</a></p>
    <p style="margin-top: 0.5rem; font-size: 0.75rem;">Ghost Agency • Siti web per attività locali • Questo è un mockup, non un sito in produzione</p>
  </footer>

  <div class="mockup-badge">🔧 Modalità Demo</div>

  <script>
    // Smooth scroll per link interni
    document.querySelectorAll('a[href^="#"]').forEach(anchor => {
      anchor.addEventListener('click', function(e) {
        e.preventDefault();
        document.querySelector(this.getAttribute('href')).scrollIntoView({ behavior: 'smooth' });
      });
    });
    // IntersectionObserver per animazioni scroll
    const observer = new IntersectionObserver((entries) => {
      entries.forEach(entry => {
        if (entry.isIntersecting) entry.target.classList.add('animate-in');
      });
    }, { threshold: 0.1 });
    document.querySelectorAll('.card, .cta-section, .form-section').forEach(el => observer.observe(el));
  </script>
</body>
</html>
"""

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

def get_colors(category: str) -> dict:
    return SECTOR_COLORS.get(category.lower(), DEFAULT_COLORS)

def get_hero_image(category: str) -> str:
    return SECTOR_IMAGES.get(category.lower(), DEFAULT_IMAGE)

def get_hours(category: str) -> dict:
    return SECTOR_HOURS.get(category.lower(), {"lun_ven": "Su appuntamento", "sab": "Su appuntamento", "dom": "Chiuso"})

def normalize_phone(phone: str) -> str:
    """Normalizza telefono per link tel: e wa.me"""
    if not phone:
        return ""
    # Rimuovi tutto tranne numeri e +
    cleaned = re.sub(r"[^\d+]", "", phone)
    if cleaned.startswith("+39"):
        return cleaned[3:]
    elif cleaned.startswith("39"):
        return cleaned[2:]
    return cleaned

def create_site(lead: dict) -> Path:
    category = lead.get("category", "").lower()
    colors = get_colors(category)
    hero_image = get_hero_image(category)
    hours = get_hours(category)
    phone = lead.get("phone", "")
    phone_wa = normalize_phone(phone)
    
    # Dati per il template
    template_data = {
        **lead,
        "colors": colors,
        "hero_image": hero_image,
        "hours": hours,
        "phone_wa": phone_wa,
        "category_title": category.capitalize(),
        "city_display": lead.get("city") or "Parma",
        "meta_description": f"Sito web per {lead.get('name', '')} - {category.capitalize()} a {lead.get('city') or 'Parma'}. Mockup demo gratuito.",
        "telegram_bot_token": os.environ.get("TELEGRAM_BOT_TOKEN", "YOUR_BOT_TOKEN"),
        "telegram_chat_id": os.environ.get("TELEGRAM_CHAT_ID", "YOUR_CHAT_ID"),
        "mockup_url": f"https://{slugify(lead.get('name', ''))}.netlify.app",
        "FROM_EMAIL": os.environ.get("FROM_EMAIL", "voipamraj@gmail.com"),
        "message_placeholder": "Messaggio del cliente dal form..."
    }
    
    folder = BASE_DIR / f"site_{slugify(lead.get('name', ''))}"
    folder.mkdir(parents=True, exist_ok=True)
    html = Template(TEMPLATE_HTML).render(**template_data)
    (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
    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 rich 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()