"""
Demo Site Generator
===================
Given a tradie business profile, generates a complete demo/preview website
using a professional HTML template — no AI required, instant output.

The generated site:
  - Uses the high-quality tradie_template.html base
  - Populates services based on trade type
  - Sets suburb-specific copy
  - Embeds click-to-call and GHL lead-capture form
  - Includes Telnyx AI voice widget
  - Outputs a self-contained HTML file ready to serve statically

Output: E:\genesis-system\Sunaiva\demos\{business_slug}\index.html

Usage:
    python demo_site_generator.py \
        --business-name "Smith Plumbing" \
        --trade plumber \
        --suburb "Parramatta" \
        --phone "0412 345 678"
"""

import argparse
import re
import sys
from pathlib import Path
from datetime import datetime
from typing import Optional

# ---------------------------------------------------------------------------
# Paths
# ---------------------------------------------------------------------------
BASE_DIR = Path(__file__).parent.parent
TEMPLATE_PATH = BASE_DIR / "Sunaiva" / "templates" / "tradie_template.html"
DEMOS_DIR = BASE_DIR / "Sunaiva" / "demos"
DEMOS_DIR.mkdir(parents=True, exist_ok=True)

# Telnyx AI Assistant ID — the live demo assistant
TELNYX_ASSISTANT_ID = "assistant-9c42d3ce-e05a-4e34-8083-c91081917637"

# GHL default lead-capture form
DEFAULT_GHL_FORM_URL = "https://link.receptionistai.com.au/widget/form/demo-lead"

# ---------------------------------------------------------------------------
# Trade-specific content packs
# ---------------------------------------------------------------------------
TRADE_CONTENT = {
    "plumber": {
        "display": "Plumbing",
        "tagline": "Fast, Reliable Plumbing — Available 24/7",
        "hero_headline": "{business_name} — {suburb}'s Trusted Plumbers",
        "hero_sub": "Blocked drains, burst pipes, hot water failures — we respond fast and fix it right the first time.",
        "hero_bg": "https://images.unsplash.com/photo-1581244277943-fe4a9c777189?auto=format&fit=crop&w=1400&q=80",
        "accent_color": "#1a5fa8",
        "cta_text": "Book a Plumber Now",
        "services": [
            {"icon": "droplet", "title": "Blocked Drains", "desc": "High-pressure water jetting and CCTV camera inspection to clear and diagnose blocked drains fast."},
            {"icon": "thermometer", "title": "Hot Water Systems", "desc": "Installation, repair, and replacement of gas, electric, and solar hot water systems."},
            {"icon": "tool", "title": "Leaking Taps & Pipes", "desc": "Stop water waste and prevent damage with our prompt tap repair and pipe relining services."},
            {"icon": "home", "title": "Bathroom Renovations", "desc": "Full bathroom plumbing fit-outs for new builds and renovations, done on time."},
            {"icon": "alert-triangle", "title": "Emergency Plumbing", "desc": "Burst pipes, sewage backups, no hot water — our emergency team arrives within 60 minutes."},
            {"icon": "settings", "title": "Backflow Prevention", "desc": "Annual testing and certification of backflow prevention devices for residential and commercial properties."},
        ],
        "license_label": "Lic. No.",
        "trust_badges": ["Licensed & Insured", "Same-Day Service", "Upfront Pricing", "10-Year Workmanship Guarantee"],
    },
    "electrician": {
        "display": "Electrical",
        "tagline": "Licensed Electricians — Safety First, Every Time",
        "hero_headline": "{business_name} — {suburb}'s Electrical Experts",
        "hero_sub": "From switchboard upgrades to emergency faults, our licensed electricians deliver safe, reliable work on every job.",
        "hero_bg": "https://images.unsplash.com/photo-1621905251189-08b45d6a269e?auto=format&fit=crop&w=1400&q=80",
        "accent_color": "#e07b00",
        "cta_text": "Get a Free Electrical Quote",
        "services": [
            {"icon": "zap", "title": "Switchboard Upgrades", "desc": "Modernise your switchboard with safety switches and circuit breakers to protect your home."},
            {"icon": "sun", "title": "Solar & Battery", "desc": "Certified solar panel installation and battery storage systems to cut your power bill."},
            {"icon": "bulb", "title": "LED Lighting", "desc": "Energy-efficient LED downlight installation, security lighting, and smart lighting systems."},
            {"icon": "power", "title": "Power Points & Data", "desc": "New outlets, USB points, and structured data cabling for home and office."},
            {"icon": "alert-triangle", "title": "Fault Finding", "desc": "Fast diagnosis and repair of electrical faults, tripping breakers, and power outages."},
            {"icon": "tv", "title": "Air Conditioning", "desc": "Split system installation and commissioning by licensed electrical tradespeople."},
        ],
        "license_label": "REC",
        "trust_badges": ["Fully Licensed REC", "Safety Switch Specialist", "Same-Day Fault Response", "Clean & Tidy Guarantee"],
    },
    "builder": {
        "display": "Building & Renovation",
        "tagline": "Quality Builds — On Time, On Budget",
        "hero_headline": "{business_name} — {suburb}'s Trusted Builder",
        "hero_sub": "From extensions and renovations to new builds, we deliver quality craftsmanship backed by a licensed builder.",
        "hero_bg": "https://images.unsplash.com/photo-1504307651254-35680f356dfd?auto=format&fit=crop&w=1400&q=80",
        "accent_color": "#2d6a2d",
        "cta_text": "Request a Free Quote",
        "services": [
            {"icon": "home", "title": "Home Extensions", "desc": "Ground floor and second storey extensions designed to blend seamlessly with your existing home."},
            {"icon": "layers", "title": "Renovations", "desc": "Kitchen, bathroom, and whole-home renovations delivered on time and within budget."},
            {"icon": "grid", "title": "Decks & Patios", "desc": "Timber and composite decking, alfresco areas, and pergolas built to last the Australian climate."},
            {"icon": "archive", "title": "Granny Flats", "desc": "Council-approved granny flat construction to maximise your property's value."},
            {"icon": "tool", "title": "Structural Repairs", "desc": "Foundation repairs, underpinning, and structural rectification work by licensed builders."},
            {"icon": "briefcase", "title": "Commercial Fit-Outs", "desc": "Shop and office fit-outs delivered on tight timelines without disrupting your business."},
        ],
        "license_label": "Builder Lic.",
        "trust_badges": ["Licensed Builder", "Owner-Operated", "Fixed Price Contracts", "10-Year Structural Guarantee"],
    },
    "painter": {
        "display": "Painting",
        "tagline": "Professional Painters — Perfect Finish, Every Time",
        "hero_headline": "{business_name} — {suburb}'s Painting Specialists",
        "hero_sub": "Interior and exterior painting done with precision. We protect your home and leave a finish you'll love.",
        "hero_bg": "https://images.unsplash.com/photo-1562259929-b4e1fd3aef09?auto=format&fit=crop&w=1400&q=80",
        "accent_color": "#7c3aed",
        "cta_text": "Get a Free Painting Quote",
        "services": [
            {"icon": "droplet", "title": "Interior Painting", "desc": "Walls, ceilings, and trims — we prep properly and apply premium paints for a lasting finish."},
            {"icon": "sun", "title": "Exterior Painting", "desc": "Weatherboard, brick, and render painting with premium exterior-grade paints and thorough surface prep."},
            {"icon": "home", "title": "Roof Painting", "desc": "Roof restoration and painting to protect against UV and weather while refreshing your home's look."},
            {"icon": "briefcase", "title": "Commercial Painting", "desc": "Office, retail, and industrial painting completed efficiently with minimal business disruption."},
            {"icon": "settings", "title": "Colour Consultation", "desc": "Free colour advice from our experienced painters to help you choose the right palette."},
            {"icon": "tool", "title": "Render & Texture", "desc": "Acrylic texture coatings, lime renders, and feature wall finishes for modern homes."},
        ],
        "license_label": "Painters Lic.",
        "trust_badges": ["Fully Insured", "Quality Paint Brands Only", "Clean Site Guarantee", "Free Colour Consultation"],
    },
    "hvac": {
        "display": "Air Conditioning & Heating",
        "tagline": "Expert HVAC Installation & Service",
        "hero_headline": "{business_name} — {suburb}'s HVAC Specialists",
        "hero_sub": "Split systems, ducted air conditioning, and heating — installed right and serviced for peak performance.",
        "hero_bg": "https://images.unsplash.com/photo-1585771724684-38269d6639fd?auto=format&fit=crop&w=1400&q=80",
        "accent_color": "#0e7490",
        "cta_text": "Book an AC Service or Quote",
        "services": [
            {"icon": "wind", "title": "Split System Installation", "desc": "Supply and install of leading brands including Daikin, Mitsubishi, and LG — sized right for your room."},
            {"icon": "home", "title": "Ducted Air Conditioning", "desc": "Full ducted system design, installation, and commissioning for whole-home climate control."},
            {"icon": "settings", "title": "AC Servicing & Repair", "desc": "Annual servicing, refrigerant top-ups, and fault diagnosis to keep your system running efficiently."},
            {"icon": "thermometer", "title": "Heating Systems", "desc": "Ducted gas heating, hydronic systems, and reverse-cycle heat pumps installed and serviced."},
            {"icon": "shield", "title": "Commercial HVAC", "desc": "Rooftop units, VRV/VRF systems, and commercial refrigeration for offices and retail."},
            {"icon": "zap", "title": "Smart Controls", "desc": "Wi-Fi thermostat integration and home automation for modern HVAC systems."},
        ],
        "license_label": "ARC Lic.",
        "trust_badges": ["ARC Certified", "All Major Brands", "Same-Day Breakdowns", "Annual Service Plans"],
    },
    "roofer": {
        "display": "Roofing",
        "tagline": "Trusted Roofers — Quality Roofing That Lasts",
        "hero_headline": "{business_name} — {suburb}'s Roofing Experts",
        "hero_sub": "Roof repairs, replacements, and guttering by experienced tradespeople. We work safely at height, every time.",
        "hero_bg": "https://images.unsplash.com/photo-1632823471565-1ecdf5c6da03?auto=format&fit=crop&w=1400&q=80",
        "accent_color": "#b45309",
        "cta_text": "Get a Free Roof Inspection",
        "services": [
            {"icon": "home", "title": "Roof Replacements", "desc": "Full roof replacement in Colorbond, terracotta, or concrete tile — supply and install."},
            {"icon": "tool", "title": "Roof Repairs", "desc": "Broken tiles, cracked flashings, ridge capping — we fix leaks fast before they cause interior damage."},
            {"icon": "droplet", "title": "Gutters & Downpipes", "desc": "Gutter replacement, cleaning, leaf guards, and downpipe installation and repair."},
            {"icon": "sun", "title": "Roof Restoration", "desc": "Pressure wash, repoint, re-bed ridge capping, and apply protective roof membrane coating."},
            {"icon": "shield", "title": "Leak Detection", "desc": "Professional leak diagnosis — we find the source quickly and provide a fixed-price repair quote."},
            {"icon": "settings", "title": "Skylights", "desc": "Velux and custom skylight installation, replacement, and leak repair."},
        ],
        "license_label": "Builder Lic.",
        "trust_badges": ["Height Safety Certified", "Colorbond Specialists", "Insurance Work Welcome", "Free Inspections"],
    },
    "tradie": {
        "display": "Trade Services",
        "tagline": "Professional Trade Services — Quality Workmanship",
        "hero_headline": "{business_name} — {suburb}'s Trusted Tradesperson",
        "hero_sub": "Professional, reliable, and fully insured trade services delivered on time and to the highest standard.",
        "hero_bg": "https://images.unsplash.com/photo-1504307651254-35680f356dfd?auto=format&fit=crop&w=1400&q=80",
        "accent_color": "#1a5fa8",
        "cta_text": "Get a Free Quote",
        "services": [
            {"icon": "tool", "title": "Residential Work", "desc": "Quality trade work for homeowners, done right the first time with minimal disruption."},
            {"icon": "briefcase", "title": "Commercial Projects", "desc": "Reliable service for commercial clients with the capacity to handle large-scale projects."},
            {"icon": "clock", "title": "Prompt Response", "desc": "We respect your time — we show up when we say and keep you informed throughout the job."},
            {"icon": "shield", "title": "Fully Insured", "desc": "All work is covered by public liability insurance for your complete peace of mind."},
        ],
        "license_label": "Lic. No.",
        "trust_badges": ["Fully Licensed", "Fully Insured", "Upfront Pricing", "Quality Guarantee"],
    },
}


def slugify(text: str) -> str:
    text = text.lower().strip()
    text = re.sub(r"[^\w\s-]", "", text)
    text = re.sub(r"[\s_-]+", "-", text)
    text = re.sub(r"^-+|-+$", "", text)
    return text


def build_service_cards(services: list) -> str:
    cards = []
    for svc in services:
        title = svc["title"]
        desc = svc["desc"]
        cards.append(f"""
        <div class="service-card">
          <div class="service-icon">
            <svg xmlns="http://www.w3.org/2000/svg" width="28" height="28" viewBox="0 0 24 24"
                 fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"
                 stroke-linejoin="round"><circle cx="12" cy="12" r="10"/>
              <line x1="12" y1="8" x2="12" y2="16"/>
              <line x1="8" y1="12" x2="16" y2="12"/>
            </svg>
          </div>
          <h3>{title}</h3>
          <p>{desc}</p>
        </div>""")
    return "\n".join(cards)


def build_trust_badges(badges: list, accent: str) -> str:
    items = []
    check_svg = (
        f'<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" '
        f'fill="none" stroke="{accent}" stroke-width="2.5" stroke-linecap="round" '
        f'stroke-linejoin="round"><polyline points="20 6 9 17 4 12"/></svg>'
    )
    for badge in badges:
        items.append(
            f'<span class="trust-badge" style="border-color:{accent}33;color:#333">'
            f'{check_svg} {badge}</span>'
        )
    return "\n  ".join(items)


def generate_demo_site(
    business_name: str,
    trade_type: str,
    suburb: str,
    phone: str,
    email: Optional[str] = None,
    ghl_form_url: Optional[str] = None,
    license_number: Optional[str] = None,
) -> Path:
    trade_key = trade_type.lower().strip()
    content = TRADE_CONTENT.get(trade_key, TRADE_CONTENT["tradie"])
    ghl_url = ghl_form_url or DEFAULT_GHL_FORM_URL
    accent = content["accent_color"]
    year = datetime.now().year
    slug = slugify(f"{business_name}-{suburb}")
    output_dir = DEMOS_DIR / slug
    output_dir.mkdir(parents=True, exist_ok=True)
    output_path = output_dir / "index.html"

    hero_headline = content["hero_headline"].format(business_name=business_name, suburb=suburb)
    hero_sub = content["hero_sub"]
    service_cards_html = build_service_cards(content["services"])
    trust_badges_html = build_trust_badges(content["trust_badges"], accent)
    lic_label = content["license_label"]
    lic_value = license_number or "Available on request"
    email_display = email or f"info@{slugify(business_name)}.com.au"
    phone_clean = re.sub(r"[\s\-\(\)]", "", phone)

    if not TEMPLATE_PATH.exists():
        raise FileNotFoundError(f"Template not found at {TEMPLATE_PATH}. Build tradie_template.html first.")

    html = TEMPLATE_PATH.read_text(encoding="utf-8")

    replacements = {
        "{{BUSINESS_NAME}}": business_name,
        "{{TRADE_DISPLAY}}": content["display"],
        "{{SUBURB}}": suburb,
        "{{TAGLINE}}": content["tagline"],
        "{{HERO_HEADLINE}}": hero_headline,
        "{{HERO_SUB}}": hero_sub,
        "{{HERO_BG}}": content["hero_bg"],
        "{{ACCENT_COLOR}}": accent,
        "{{CTA_TEXT}}": content["cta_text"],
        "{{PHONE}}": phone,
        "{{PHONE_CLEAN}}": phone_clean,
        "{{EMAIL}}": email_display,
        "{{GHL_FORM_URL}}": ghl_url,
        "{{SERVICE_CARDS}}": service_cards_html,
        "{{TRUST_BADGES}}": trust_badges_html,
        "{{LICENSE_LABEL}}": lic_label,
        "{{LICENSE_NUMBER}}": lic_value,
        "{{YEAR}}": str(year),
        "{{TELNYX_ASSISTANT_ID}}": TELNYX_ASSISTANT_ID,
        "{{BUSINESS_SLUG}}": slug,
    }

    for placeholder, value in replacements.items():
        html = html.replace(placeholder, value)

    output_path.write_text(html, encoding="utf-8")
    print(f"[GENERATOR] Demo site created: {output_path}")
    return output_path


def main():
    parser = argparse.ArgumentParser(description="Generate a demo tradie website.")
    parser.add_argument("--business-name", required=True)
    parser.add_argument("--trade", required=True, choices=list(TRADE_CONTENT.keys()))
    parser.add_argument("--suburb", required=True)
    parser.add_argument("--phone", required=True)
    parser.add_argument("--email", default=None)
    parser.add_argument("--ghl-form-url", default=None)
    parser.add_argument("--license", default=None)
    args = parser.parse_args()

    output_path = generate_demo_site(
        business_name=args.business_name,
        trade_type=args.trade,
        suburb=args.suburb,
        phone=args.phone,
        email=args.email,
        ghl_form_url=args.ghl_form_url,
        license_number=args.license,
    )
    print(f"[GENERATOR] Output: {output_path}")


if __name__ == "__main__":
    main()
