"""
Genesis Clone Pipeline — AI Reconstruction Module
==================================================
Uses Gemini Flash to reconstruct a cloned website as clean, modern HTML
with Tailwind CSS, mobile-first design, and Genesis chatbot widget.

Model: google.genai (new SDK) with google-generativeai fallback.
"""

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

logger = logging.getLogger("clone_pipeline.reconstructor")

# ---------------------------------------------------------------------------
# API key resolution
# ---------------------------------------------------------------------------

def _get_gemini_api_key() -> Optional[str]:
    """Resolve Gemini API key from environment or secrets.env."""
    # Check common env var names
    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 genesis secrets loader
    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

    return None


# ---------------------------------------------------------------------------
# Gemini reconstruction prompt
# ---------------------------------------------------------------------------

RECONSTRUCTION_SYSTEM_PROMPT = """You are a world-class web developer specialising in rebuilding
Australian tradie and small business websites. You take existing website content and transform it
into a modern, high-performance, mobile-first HTML page that will rank well on Google and convert
visitors into leads.

Your output must be:
- A single, complete, standalone HTML file
- Mobile-first responsive using Tailwind CSS (CDN)
- Fast loading (no heavy dependencies except Tailwind CDN)
- Professional and trustworthy in appearance
- Optimised for conversions (clear CTAs, phone number prominent)
- Include proper SEO meta tags and Open Graph tags
- Include local business schema markup (JSON-LD)

Always return ONLY the complete HTML file. No explanations. No markdown code blocks.
Just pure HTML starting with <!DOCTYPE html>."""


def _build_reconstruction_prompt(
    content: str,
    business_name: str,
    services: str,
    phone: str,
    location: str = "",
    url: str = "",
    widget_snippet: str = "",
) -> str:
    """Build the Gemini prompt for site reconstruction."""

    # Truncate content to avoid token limits (keep most relevant portion)
    max_content_chars = 12000
    if len(content) > max_content_chars:
        content = content[:max_content_chars] + "\n\n[Content truncated for processing...]"

    prompt = f"""You are rebuilding {business_name}'s website. Here is their current content:

{content}

BUSINESS DETAILS:
- Business Name: {business_name}
- Services: {services if services else 'See content above'}
- Phone: {phone if phone else 'See content above'}
- Location: {location if location else 'See content above'}
- Original URL: {url}

Create a modern, mobile-first HTML page with:

1. DOCTYPE html, head with title, meta description, Open Graph tags, viewport meta
2. Tailwind CSS CDN: <script src="https://cdn.tailwindcss.com"></script>
3. Hero section with:
   - Business name as H1
   - Clear value proposition subtitle
   - Main service offering
   - Prominent phone number as a clickable link (tel: protocol)
   - Strong call-to-action button ("Call Now" or "Get a Free Quote")
4. Services section:
   - Grid of their actual services from the content
   - Icons or emoji to make it scannable
5. Why Choose Us / Trust section:
   - Years in business if mentioned
   - Service area
   - Key differentiators (licensed, insured, etc.)
   - 2-3 trust badges/icons
6. Testimonials section (use 2-3 realistic placeholder testimonials in their industry style)
7. Contact section:
   - Phone number (click to call)
   - Contact form: name, phone, service needed, preferred time, message
   - Service area / location
8. Footer with:
   - Business name
   - Phone
   - Copyright {business_name}
9. Local Business schema JSON-LD in head:
   {{
     "@context": "https://schema.org",
     "@type": "LocalBusiness",
     "name": "{business_name}",
     "telephone": "{phone}",
     "address": {{ "@type": "PostalAddress", "addressRegion": "{location}" }}
   }}
10. Floating "Chat with us" button (bottom right corner) with this EXACT snippet:
{widget_snippet if widget_snippet else '<!-- Genesis chatbot widget will be injected here -->'}

DESIGN REQUIREMENTS:
- Colour scheme: Professional blues/greys for trade services, or match industry colours from content
- Typography: Clean sans-serif (system fonts or Google Fonts Inter)
- Australian spelling and tone (e.g., "colour", "favour", "licence")
- All phone numbers as tel: links for mobile click-to-call
- Sticky header with phone number visible at all times
- Mobile hamburger menu
- Smooth scroll to sections

SEO REQUIREMENTS:
- Title tag: "{business_name} | [Main Service] | [Location]"
- Meta description: 155 chars max, include service + location + phone
- H1: Business name (only one H1)
- H2: Section headings
- Alt text on all images (use placeholder images from https://placehold.co/)

Return ONLY the complete HTML file. No markdown. No code blocks. Start directly with <!DOCTYPE html>."""

    return prompt


# ---------------------------------------------------------------------------
# Gemini API call
# ---------------------------------------------------------------------------

def _call_gemini(prompt: str, model: str = "gemini-2.5-flash") -> Optional[str]:
    """
    Call Gemini API to reconstruct the website.
    Tries new google.genai SDK first, falls back to google.generativeai.
    """
    api_key = _get_gemini_api_key()
    if not api_key:
        logger.error("[Reconstructor] No Gemini API key found. Set GEMINI_API_KEY or GOOGLE_API_KEY.")
        return None

    # --- Try new google.genai SDK (preferred) ---
    try:
        import google.genai as genai
        from google.genai import types

        client = genai.Client(api_key=api_key)

        logger.info(f"[Reconstructor] Calling Gemini ({model}) via google.genai SDK...")

        response = client.models.generate_content(
            model=model,
            contents=prompt,
            config=types.GenerateContentConfig(
                system_instruction=RECONSTRUCTION_SYSTEM_PROMPT,
                max_output_tokens=8192,
                temperature=0.3,
            ),
        )

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

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

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

        genai_legacy.configure(api_key=api_key)

        # Use available flash model
        try:
            model_obj = genai_legacy.GenerativeModel(
                model_name=model,
                system_instruction=RECONSTRUCTION_SYSTEM_PROMPT,
            )
        except Exception:
            model_obj = genai_legacy.GenerativeModel(model_name="gemini-1.5-flash")

        logger.info(f"[Reconstructor] Calling Gemini via legacy SDK...")

        response = model_obj.generate_content(
            prompt,
            generation_config=genai_legacy.GenerationConfig(
                max_output_tokens=8192,
                temperature=0.3,
            ),
        )

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

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

    return None


# ---------------------------------------------------------------------------
# HTML post-processing
# ---------------------------------------------------------------------------

def _clean_html_output(raw: str) -> str:
    """
    Strip any markdown code block wrappers that Gemini sometimes adds.
    Ensures output starts with <!DOCTYPE html>.
    """
    raw = raw.strip()

    # Remove markdown code fences
    if raw.startswith("```html"):
        raw = raw[7:]
    elif raw.startswith("```"):
        raw = raw[3:]

    if raw.endswith("```"):
        raw = raw[:-3]

    raw = raw.strip()

    # If Gemini returned something before <!DOCTYPE, strip it
    doctype_idx = raw.lower().find("<!doctype")
    if doctype_idx > 0:
        raw = raw[doctype_idx:]
    elif doctype_idx == -1:
        # No doctype found — might just be <html>
        html_idx = raw.lower().find("<html")
        if html_idx > 0:
            raw = raw[html_idx:]

    return raw


def _inject_widget(html: str, widget_snippet: str) -> str:
    """
    Inject the chatbot widget snippet before </body> if not already present.
    """
    if not widget_snippet:
        return html

    if "genesis-chat-widget" in html or "GenesisChat" in html:
        # Already injected via prompt
        return html

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

    return html


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

def reconstruct_site(
    content: str,
    business_name: str,
    services: str = "",
    phone: str = "",
    location: str = "",
    url: str = "",
    widget_snippet: str = "",
    model: str = "gemini-2.5-flash",
) -> Optional[str]:
    """
    Reconstruct a business website as clean HTML using Gemini Flash.

    Args:
        content: Extracted markdown/text content from the original site
        business_name: Name of the business
        services: Comma-separated list of services
        phone: Business phone number
        location: City/region
        url: Original URL (for reference)
        widget_snippet: HTML snippet for Genesis chatbot widget
        model: Gemini model to use

    Returns:
        Complete HTML string, or None if reconstruction fails.
    """
    if not content:
        logger.error("[Reconstructor] No content provided for reconstruction")
        return None

    if not business_name:
        business_name = "Your Business"
        logger.warning("[Reconstructor] No business name provided, using placeholder")

    logger.info(f"[Reconstructor] Reconstructing site for: {business_name}")

    # Build prompt
    prompt = _build_reconstruction_prompt(
        content=content,
        business_name=business_name,
        services=services,
        phone=phone,
        location=location,
        url=url,
        widget_snippet=widget_snippet,
    )

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

    if not raw_html:
        logger.error("[Reconstructor] Gemini returned no content")
        return _generate_fallback_html(business_name, services, phone, location, widget_snippet)

    # Clean and inject widget
    html = _clean_html_output(raw_html)
    html = _inject_widget(html, widget_snippet)

    logger.info(f"[Reconstructor] Final HTML: {len(html)} chars")
    return html


def _generate_fallback_html(
    business_name: str,
    services: str,
    phone: str,
    location: str,
    widget_snippet: str = "",
) -> str:
    """
    Generate a minimal but functional HTML page as fallback if Gemini fails.
    """
    logger.info("[Reconstructor] Generating fallback HTML template")
    services_list = [s.strip() for s in services.split(",") if s.strip()] if services else ["Our Services"]
    services_html = "\n".join(
        f'<div class="bg-white rounded-lg p-6 shadow-sm border"><h3 class="font-semibold text-gray-800">{s}</h3></div>'
        for s in services_list[:6]
    )

    return f"""<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>{business_name} | Professional Services | {location}</title>
    <meta name="description" content="{business_name} - Professional {services_list[0] if services_list else 'services'} in {location}. Call {phone} today.">
    <script src="https://cdn.tailwindcss.com"></script>
</head>
<body class="bg-gray-50 font-sans">
    <!-- Header -->
    <header class="bg-blue-900 text-white shadow-lg sticky top-0 z-50">
        <div class="max-w-6xl mx-auto px-4 py-4 flex justify-between items-center">
            <h1 class="text-xl font-bold">{business_name}</h1>
            <a href="tel:{phone}" class="bg-yellow-400 text-blue-900 font-bold px-4 py-2 rounded hover:bg-yellow-300 transition">
                Call {phone}
            </a>
        </div>
    </header>

    <!-- Hero -->
    <section class="bg-gradient-to-br from-blue-900 to-blue-700 text-white py-20">
        <div class="max-w-4xl mx-auto px-4 text-center">
            <h2 class="text-4xl font-bold mb-4">{business_name}</h2>
            <p class="text-xl mb-2">{location}</p>
            <p class="text-lg opacity-90 mb-8">Professional services you can trust</p>
            <a href="tel:{phone}" class="bg-yellow-400 text-blue-900 font-bold text-xl px-8 py-4 rounded-lg hover:bg-yellow-300 transition inline-block">
                Call Now: {phone}
            </a>
        </div>
    </section>

    <!-- Services -->
    <section class="py-16 bg-gray-50">
        <div class="max-w-6xl mx-auto px-4">
            <h2 class="text-3xl font-bold text-center text-gray-800 mb-10">Our Services</h2>
            <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
                {services_html}
            </div>
        </div>
    </section>

    <!-- Contact -->
    <section class="py-16 bg-blue-900 text-white">
        <div class="max-w-2xl mx-auto px-4 text-center">
            <h2 class="text-3xl font-bold mb-6">Get In Touch</h2>
            <p class="text-xl mb-6">Ready to get started? Contact us today.</p>
            <a href="tel:{phone}" class="bg-yellow-400 text-blue-900 font-bold text-2xl px-10 py-5 rounded-lg hover:bg-yellow-300 transition inline-block">
                {phone}
            </a>
        </div>
    </section>

    <!-- Footer -->
    <footer class="bg-gray-800 text-gray-400 py-8 text-center">
        <p>&copy; {business_name}. {location}.</p>
        <p class="mt-1 text-sm">Website enhanced by Genesis AI</p>
    </footer>

    {widget_snippet}
</body>
</html>"""


# ---------------------------------------------------------------------------
# CLI test
# ---------------------------------------------------------------------------

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

    test_content = """
    Bob's Plumbing - Brisbane's trusted plumbers since 2005.
    Services: Emergency plumbing, blocked drains, hot water systems, gas fitting, bathroom renovations.
    Available 24/7 for emergencies.
    Service areas: Brisbane Northside, Southside, Ipswich.
    Call us: 07 3456 7890
    Licensed and insured plumbers.
    """

    html = reconstruct_site(
        content=test_content,
        business_name="Bob's Plumbing",
        services="Emergency Plumbing, Blocked Drains, Hot Water, Gas Fitting",
        phone="07 3456 7890",
        location="Brisbane",
        url="https://example.com",
    )

    if html:
        out = Path("/mnt/e/genesis-system/scripts/clone_pipeline/output/test_reconstruct.html")
        out.parent.mkdir(parents=True, exist_ok=True)
        out.write_text(html)
        print(f"Output saved: {out} ({len(html)} chars)")
    else:
        print("Reconstruction failed")
