"""
Genesis Gold Pipeline — Landing Page Generator
================================================
Generates industry-specific landing pages using Gemini API.
Produces standalone HTML with Tailwind CSS, voice widget injection,
SEO meta tags, and LocalBusiness schema markup.

Usage:
    from generate_site import generate_landing_page
    html = generate_landing_page("tradiechatbots.com.au")
"""

import os
import sys
import re
import logging
import json
from pathlib import Path
from typing import Optional

sys.path.insert(0, str(Path(__file__).parent))
from prompt_templates import get_domain_config, VERTICALS, PALETTES, CITIES

logger = logging.getLogger("gold_pipeline.generate_site")

# ---------------------------------------------------------------------------
# Telnyx voice widget snippet
# ---------------------------------------------------------------------------

VOICE_WIDGET_SNIPPET = """
<!-- AI Voice Widget — Telnyx WebRTC -->
<div id="voice-widget-container" style="position:fixed;bottom:24px;right:24px;z-index:9999;">
  <button id="voice-widget-btn" onclick="document.getElementById('voice-widget-modal').style.display='flex'"
    style="background:linear-gradient(135deg,{primary},{accent});color:white;border:none;border-radius:50%;
    width:64px;height:64px;font-size:28px;cursor:pointer;
    box-shadow:0 4px 20px rgba(0,0,0,0.3);transition:all 0.3s ease;"
    onmouseover="this.style.transform='scale(1.1)';this.style.boxShadow='0 6px 24px rgba(0,0,0,0.4)'"
    onmouseout="this.style.transform='scale(1)';this.style.boxShadow='0 4px 20px rgba(0,0,0,0.3)'"
    aria-label="Talk to our AI assistant">
    <svg width="28" height="28" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" style="margin:auto;display:block">
      <path d="M12 1a3 3 0 0 0-3 3v8a3 3 0 0 0 6 0V4a3 3 0 0 0-3-3z"/>
      <path d="M19 10v2a7 7 0 0 1-14 0v-2"/>
      <line x1="12" y1="19" x2="12" y2="23"/>
      <line x1="8" y1="23" x2="16" y2="23"/>
    </svg>
  </button>
  <div style="position:absolute;bottom:72px;right:0;background:white;border-radius:12px;
    padding:8px 14px;font-size:13px;white-space:nowrap;box-shadow:0 2px 12px rgba(0,0,0,0.15);
    color:{primary};font-weight:600;pointer-events:none;">
    Talk to our AI — Try it free
  </div>
</div>

<!-- Voice Widget Modal -->
<div id="voice-widget-modal" style="display:none;position:fixed;inset:0;background:rgba(0,0,0,0.6);
  z-index:10000;align-items:center;justify-content:center;backdrop-filter:blur(4px);">
  <div style="background:white;border-radius:16px;padding:32px;max-width:420px;width:90%;
    box-shadow:0 20px 60px rgba(0,0,0,0.3);text-align:center;position:relative;">
    <button onclick="document.getElementById('voice-widget-modal').style.display='none'"
      style="position:absolute;top:12px;right:12px;background:none;border:none;font-size:24px;
      cursor:pointer;color:#666;line-height:1;">&times;</button>
    <div style="font-size:48px;margin-bottom:16px;">🎙️</div>
    <h3 style="margin:0 0 8px;font-size:20px;color:{primary};">Talk to Our AI Receptionist</h3>
    <p style="margin:0 0 20px;color:#666;font-size:14px;">
      Experience how our AI handles calls for businesses like yours.
      Click below to start a live voice demo.
    </p>
    <a href="https://aiva.agileadapt.com/s/{spore_payload}"
      style="display:inline-block;background:linear-gradient(135deg,{primary},{accent});color:white;
      text-decoration:none;padding:14px 32px;border-radius:8px;font-weight:600;font-size:16px;
      transition:transform 0.2s;"
      onmouseover="this.style.transform='translateY(-2px)'"
      onmouseout="this.style.transform='translateY(0)'">
      Start Voice Demo →
    </a>
    <p style="margin:12px 0 0;color:#999;font-size:12px;">Free demo — no signup required</p>
  </div>
</div>
"""


# ---------------------------------------------------------------------------
# Gemini API key
# ---------------------------------------------------------------------------

def _get_gemini_api_key() -> Optional[str]:
    for key_name in ("GEMINI_API_KEY", "GOOGLE_API_KEY", "GOOGLE_GEMINI_API_KEY"):
        val = os.environ.get(key_name)
        if val:
            return val
    try:
        sys.path.insert(0, "/mnt/e/genesis-system/core")
        from secrets_loader import get_gemini_api_key
        return get_gemini_api_key()
    except Exception:
        pass
    # Try secrets.env directly
    secrets_path = Path("/mnt/e/genesis-system/config/secrets.env")
    if secrets_path.exists():
        for line in secrets_path.read_text().splitlines():
            line = line.strip()
            if line.startswith("GEMINI_API_KEY=") or line.startswith("GOOGLE_API_KEY="):
                return line.split("=", 1)[1].strip().strip('"').strip("'")
    return None


# ---------------------------------------------------------------------------
# Build the Gemini prompt for a domain landing page
# ---------------------------------------------------------------------------

def _build_landing_page_prompt(config: dict) -> str:
    """Build a comprehensive Gemini prompt for generating a landing page."""
    v = config["vertical"]
    p = config["palette"]
    domain = config["domain"]
    city = config.get("city")
    city_key = config.get("city_key")

    # Location-specific content
    if city:
        location_text = f"""
LOCATION TARGETING:
- City: {city_key.replace('_', ' ').title() if city_key else 'Australia'}
- State: {city['state']}
- Service Area: {city['area_desc']}
- Key Suburbs: {city['suburbs']}
- Population: {city['population']}

Include location-specific content:
- Reference the city name in H1, H2, and body text naturally
- Mention specific suburbs in the service area section
- Use "{city_key.replace('_', ' ').title() if city_key else 'Australian'}" in meta title and description
- Include a "Serving [suburbs]" section
"""
    else:
        location_text = """
LOCATION: National Australia
- Target all major Australian cities
- Use "Australian" in positioning
- Reference major cities: Sydney, Melbourne, Brisbane, Perth, Adelaide
"""

    # Build features list
    features_html = "\n".join(f"- {f}" for f in v["features"])
    pain_points_html = "\n".join(f"- {p}" for p in v["pain_points"])
    trust_html = "\n".join(f"- {t}" for t in v["trust_signals"])

    prompt = f"""Generate a complete, standalone HTML landing page for the domain: {domain}

BUSINESS CONTEXT:
This is a landing page for an AI voice agent product targeting {config['vertical_key']} businesses in Australia.
The product is an AI-powered phone receptionist that answers calls 24/7, captures leads, and books appointments.
Brand: AgileAdapt (the service brand) / Sunaiva (the technology platform)

HEADLINE: {v['headline']}
SUBHEADLINE: {v['subheadline']}
CTA: {v['cta']}
PRICE ANCHOR: {v['price_anchor']}

{location_text}

PAIN POINTS TO ADDRESS:
{pain_points_html}

FEATURES TO HIGHLIGHT:
{features_html}

TRUST SIGNALS:
{trust_html}

DESIGN REQUIREMENTS:
- Single standalone HTML file (no external dependencies except Tailwind CDN and Google Fonts)
- Mobile-first responsive design
- Colour scheme:
  - Primary: {p['primary']}
  - Secondary: {p['secondary']}
  - Accent: {p['accent']}
  - Background: {p['bg']}
- Typography: Inter font from Google Fonts
- Australian English spelling throughout (colour, favour, licence, etc.)

SECTIONS (in order):
1. HEADER: Sticky nav with logo text ({domain.split('.')[0].replace('-',' ').title()}), navigation links, and prominent CTA button
2. HERO: Full-width gradient hero with headline, subheadline, CTA button, and subtle animation (CSS only)
3. PAIN POINTS: "Sound Familiar?" section with 4 cards showing the problems
4. HOW IT WORKS: 3-step process (1. We Set Up Your AI → 2. AI Answers Your Calls → 3. You Get More Jobs)
5. FEATURES: Grid of 4 feature cards with icons (use emoji or SVG icons)
6. SOCIAL PROOF: Stats bar (e.g., "500+ businesses trust us | 50,000+ calls handled | 4.9★ rating")
7. PRICING: 3 tiers ($497/mo Starter, $997/mo Professional, $1,497/mo Enterprise) with feature comparison
   - Starter: 500 voice minutes, 1 AI agent, basic analytics, email support
   - Professional: 2,000 minutes, CRM integration, advanced analytics, priority support, white-glove setup
   - Enterprise: 5,000 minutes, 3 AI agents, custom webhooks, API access, dedicated account manager
8. FAQ: 6 common questions with expandable answers (use details/summary HTML)
9. FINAL CTA: Full-width section with "Ready to never miss a call again?" and CTA button
10. FOOTER: Logo, links, copyright, "Powered by Sunaiva AI" small text, Privacy Policy link

SEO REQUIREMENTS:
- Title: "{v['headline']} | {domain}" (max 60 chars)
- Meta description: Include {config['vertical_key']}, location if applicable, and CTA (max 155 chars)
- H1: One per page (the headline)
- Schema markup: LocalBusiness JSON-LD
- Open Graph tags for social sharing
- Canonical URL: https://{domain}

TECHNICAL:
- Tailwind CSS via CDN: <script src="https://cdn.tailwindcss.com"></script>
- Google Fonts Inter: <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800&display=swap" rel="stylesheet">
- Smooth scroll behaviour
- FAQ uses native <details><summary> elements
- All phone numbers as tel: links
- CSS animations for hero (fade-in, slide-up) using @keyframes
- No JavaScript dependencies beyond Tailwind

PRICING DISPLAY:
- Monthly prices in AUD
- Highlight "Professional" as "Most Popular"
- Annual discount hint: "Save 20% with annual billing"
- Each tier has a clear CTA button linking to: https://aiva.agileadapt.com/s/demo

OUTPUT: Return ONLY the complete HTML file starting with <!DOCTYPE html>. No markdown, no code blocks, no explanations."""

    return prompt


# ---------------------------------------------------------------------------
# Call Gemini API
# ---------------------------------------------------------------------------

def _call_gemini(prompt: str, model: str = "gemini-2.5-flash") -> Optional[str]:
    """Call Gemini API to generate HTML."""
    api_key = _get_gemini_api_key()
    if not api_key:
        logger.error("No Gemini API key found")
        return None

    # Try new SDK first
    try:
        import google.genai as genai
        from google.genai import types

        client = genai.Client(api_key=api_key)
        logger.info(f"Calling Gemini ({model}) via google.genai SDK...")

        response = client.models.generate_content(
            model=model,
            contents=prompt,
            config=types.GenerateContentConfig(
                system_instruction="You are a world-class front-end developer specialising in high-conversion landing pages for Australian businesses. You produce complete, standalone HTML files with Tailwind CSS. Your output is always pixel-perfect, mobile-first, and optimised for conversions. Return ONLY HTML — no markdown, no code blocks, no explanations.",
                max_output_tokens=16384,
                temperature=0.4,
            ),
        )

        text = response.text
        if text:
            logger.info(f"Received {len(text)} chars from Gemini")
            return text

    except ImportError:
        logger.info("google.genai not available, trying legacy SDK...")
    except Exception as e:
        logger.warning(f"google.genai failed: {e}, trying legacy SDK...")

    # Fallback: legacy SDK
    try:
        import warnings
        with warnings.catch_warnings():
            warnings.simplefilter("ignore")
            import google.generativeai as genai_legacy

        genai_legacy.configure(api_key=api_key)

        model_obj = genai_legacy.GenerativeModel(
            model_name=model,
            system_instruction="You are a world-class front-end developer specialising in high-conversion landing pages for Australian businesses. Return ONLY complete HTML files.",
        )

        response = model_obj.generate_content(
            prompt,
            generation_config=genai_legacy.GenerationConfig(
                max_output_tokens=16384,
                temperature=0.4,
            ),
        )

        text = response.text
        if text:
            logger.info(f"Received {len(text)} chars (legacy SDK)")
            return text

    except Exception as e:
        logger.error(f"Legacy SDK also failed: {e}")

    return None


# ---------------------------------------------------------------------------
# Post-processing
# ---------------------------------------------------------------------------

def _clean_html(raw: str) -> str:
    """Strip markdown wrappers and ensure clean HTML output."""
    raw = raw.strip()
    if raw.startswith("```html"):
        raw = raw[7:]
    elif raw.startswith("```"):
        raw = raw[3:]
    if raw.endswith("```"):
        raw = raw[:-3]
    raw = raw.strip()

    doctype_idx = raw.lower().find("<!doctype")
    if doctype_idx > 0:
        raw = raw[doctype_idx:]
    elif doctype_idx == -1:
        html_idx = raw.lower().find("<html")
        if html_idx > 0:
            raw = raw[html_idx:]

    return raw


def _inject_voice_widget(html: str, config: dict) -> str:
    """Inject the voice widget into the HTML before </body>."""
    p = config["palette"]
    import base64
    # Create a minimal spore payload for the demo link
    spore_data = json.dumps({"u": f"https://{config['domain']}", "t": 1}, separators=(",", ":"))
    spore_payload = base64.urlsafe_b64encode(spore_data.encode()).decode().rstrip("=")

    widget = VOICE_WIDGET_SNIPPET.format(
        primary=p["primary"],
        accent=p["accent"],
        spore_payload=spore_payload,
    )

    body_close = html.lower().rfind("</body>")
    if body_close != -1:
        html = html[:body_close] + "\n" + widget + "\n" + html[body_close:]
    else:
        html = html + "\n" + widget
    return html


def _inject_analytics(html: str, domain: str) -> str:
    """Inject Plausible analytics tracking before </head>."""
    analytics = f"""
    <!-- Plausible Analytics -->
    <script defer data-domain="{domain}" src="https://plausible.io/js/script.js"></script>
"""
    head_close = html.lower().rfind("</head>")
    if head_close != -1:
        html = html[:head_close] + analytics + html[head_close:]
    return html


# ---------------------------------------------------------------------------
# Fallback template (if Gemini fails)
# ---------------------------------------------------------------------------

def _generate_fallback(config: dict) -> str:
    """Generate a basic but functional landing page if Gemini API fails."""
    v = config["vertical"]
    p = config["palette"]
    domain = config["domain"]
    city = config.get("city")
    city_name = config.get("city_key", "").replace("_", " ").title() if config.get("city_key") else "Australia"

    features_html = "\n".join(
        f'<div class="bg-white rounded-xl p-6 shadow-sm border"><p class="text-lg font-semibold" style="color:{p["primary"]}">{f}</p></div>'
        for f in v["features"]
    )

    return f"""<!DOCTYPE html>
<html lang="en-AU">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>{v['headline']} | {domain}</title>
    <meta name="description" content="{v['subheadline']} Serving {city_name}. {v['price_anchor']}.">
    <meta property="og:title" content="{v['headline']}">
    <meta property="og:description" content="{v['subheadline']}">
    <meta property="og:url" content="https://{domain}">
    <link rel="canonical" href="https://{domain}">
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800&display=swap" rel="stylesheet">
    <style>body {{ font-family: 'Inter', sans-serif; }}</style>
</head>
<body class="bg-gray-50">
    <header class="sticky top-0 z-50 shadow-sm" style="background:{p['primary']}">
        <div class="max-w-6xl mx-auto px-4 py-4 flex justify-between items-center">
            <span class="text-white text-xl font-bold">{domain.split('.')[0].replace('-',' ').title()}</span>
            <a href="https://aiva.agileadapt.com/s/demo" class="text-sm font-semibold px-6 py-2.5 rounded-lg transition" style="background:{p['secondary']};color:{p['primary']}">{v['cta']}</a>
        </div>
    </header>
    <section class="py-24 text-center text-white" style="background:linear-gradient(135deg,{p['primary']},{p['accent']})">
        <div class="max-w-3xl mx-auto px-4">
            <h1 class="text-4xl md:text-5xl font-extrabold mb-4">{v['headline']}</h1>
            <p class="text-xl opacity-90 mb-2">{v['subheadline']}</p>
            {'<p class="text-lg opacity-80 mb-8">Serving ' + city_name + '</p>' if city else '<p class="text-lg opacity-80 mb-8">For Australian businesses</p>'}
            <a href="https://aiva.agileadapt.com/s/demo" class="inline-block text-lg font-bold px-10 py-4 rounded-xl transition hover:opacity-90" style="background:{p['secondary']};color:{p['primary']}">{v['cta']} →</a>
            <p class="mt-4 text-sm opacity-70">{v['price_anchor']}</p>
        </div>
    </section>
    <section class="py-16 bg-white">
        <div class="max-w-5xl mx-auto px-4">
            <h2 class="text-3xl font-bold text-center mb-10" style="color:{p['primary']}">Why Choose Us</h2>
            <div class="grid md:grid-cols-2 gap-6">{features_html}</div>
        </div>
    </section>
    <section class="py-16" style="background:{p['bg']}">
        <div class="max-w-4xl mx-auto px-4 text-center">
            <h2 class="text-3xl font-bold mb-4" style="color:{p['primary']}">Ready to Never Miss a Call Again?</h2>
            <p class="text-lg text-gray-600 mb-8">{v['subheadline']}</p>
            <a href="https://aiva.agileadapt.com/s/demo" class="inline-block text-lg font-bold px-10 py-4 rounded-xl text-white transition hover:opacity-90" style="background:{p['primary']}">{v['cta']} →</a>
        </div>
    </section>
    <footer class="py-8 text-center text-gray-400 text-sm" style="background:{p['primary']}">
        <p class="text-gray-300">&copy; 2026 {domain.split('.')[0].replace('-',' ').title()}. All rights reserved.</p>
        <p class="mt-1 text-gray-500">Powered by <a href="https://sunaiva.ai" class="underline">Sunaiva AI</a></p>
    </footer>
</body>
</html>"""


# ---------------------------------------------------------------------------
# Public API
# ---------------------------------------------------------------------------

def generate_landing_page(
    domain: str,
    model: str = "gemini-2.5-flash",
    use_fallback_on_failure: bool = True,
) -> Optional[str]:
    """
    Generate a complete landing page for a domain from the portfolio.

    Args:
        domain: The domain name (e.g., "tradiechatbots.com.au")
        model: Gemini model to use
        use_fallback_on_failure: If True, return a basic template on API failure

    Returns:
        Complete HTML string ready for deployment.
    """
    config = get_domain_config(domain)
    logger.info(f"Generating landing page for {domain} (vertical={config['vertical_key']}, city={config.get('city_key', 'national')}, tier={config['tier']})")

    # Build prompt
    prompt = _build_landing_page_prompt(config)

    # Call Gemini
    raw_html = _call_gemini(prompt, model=model)

    if raw_html:
        html = _clean_html(raw_html)
    elif use_fallback_on_failure:
        logger.warning(f"Gemini failed for {domain}, using fallback template")
        html = _generate_fallback(config)
    else:
        return None

    # Post-process
    html = _inject_voice_widget(html, config)
    html = _inject_analytics(html, domain)

    logger.info(f"Landing page generated for {domain}: {len(html)} chars")
    return html


# ---------------------------------------------------------------------------
# CLI
# ---------------------------------------------------------------------------

if __name__ == "__main__":
    import argparse
    logging.basicConfig(level=logging.INFO, format="%(levelname)s %(message)s")

    parser = argparse.ArgumentParser(description="Generate a landing page for a Genesis domain")
    parser.add_argument("domain", help="Domain name (e.g., tradiechatbots.com.au)")
    parser.add_argument("--model", default="gemini-2.5-flash", help="Gemini model to use")
    parser.add_argument("--output", help="Output file path (default: output/{domain}/index.html)")
    args = parser.parse_args()

    html = generate_landing_page(args.domain, model=args.model)
    if html:
        output_dir = Path(args.output) if args.output else Path(f"/mnt/e/genesis-system/scripts/gold_pipeline/output/{args.domain}")
        if not args.output:
            output_dir.mkdir(parents=True, exist_ok=True)
            output_path = output_dir / "index.html"
        else:
            output_path = output_dir

        output_path.parent.mkdir(parents=True, exist_ok=True)
        output_path.write_text(html, encoding="utf-8")
        print(f"Landing page saved: {output_path} ({len(html)} chars)")
    else:
        print("Generation failed")
        sys.exit(1)
