import uvicorn
from fastapi import FastAPI, Request
from fastapi.responses import HTMLResponse
import re

app = FastAPI(title="Genesis Reskin Engine")

# Simulated Pomelli DNA Database
POMELLI_DNA = {
    "plumbing": {
        "primary": "#2563eb",
        "secondary": "#eff6ff",
        "font": "'Inter', sans-serif",
        "niche": "Sydney Plumbing",
        "outcome": "Revenue Recovery",
        "benefit": "recovers 22% of missed call revenue",
        "unique": "Gemini 2.5 Flash Native Voice"
    },
    "legal": {
        "primary": "#1e293b",
        "secondary": "#f8fafc",
        "font": "'Playfair Display', serif",
        "niche": "High-Ticket Legal",
        "outcome": "Client Acquisition",
        "benefit": "automates lead qualification with P1 validation",
        "unique": "Immutable Audit Trails (P4)"
    }
}

@app.get("/{niche}")
async def reskin_page(niche: str, request: Request):
    """
    Simulates the Reverse Proxy Reskinning logic.
    Injects Pomelli DNA into the landing page template.
    """
    dna = POMELLI_DNA.get(niche.lower())
    if not dna:
        return HTMLResponse("<h1>Genesis Niche Not Found</h1>")

    # Load the AIO component
    with open("core/web/aio_component.html", "r", encoding="utf-8") as f:
        aio_template = f.read()

    # Dynamic Replacement logic (simulating the 'Reskinning')
    page_content = f"""
    <!DOCTYPE html>
    <html>
    <head>
        <title>{{{{NICHE_NAME}}}} | Powered by Genesis</title>
        <style>
            :root {{
                --brand-primary: {dna['primary']};
                --brand-bg: {dna['secondary']};
            }}
            body {{ font-family: {dna['font']}; }}
            .container {{ max-width: 800px; margin: auto; padding: 50px; }}
        </style>
    </head>
    <body>
        <div class="container">
            <h1>Welcome to {dna['niche']} AI</h1>
            <p>Elite automation designed with premium brand DNA.</p>
            
            <!-- Injected AIO Block -->
            {aio_template}
        </div>
    </body>
    </html>
    """

    # Replace AIO Variables
    placeholders = {
        "{{NICHE_NAME}}": dna['niche'],
        "{{CORE_OUTCOME}}": dna['outcome'],
        "{{BENEFIT_SUMMARY}}": dna['benefit'],
        "{{UNIQUE_VALUE_ADD}}": dna['unique'],
        "{{BUSINESS_NAME}}": "Genesis Elite",
        "{{LOCATION}}": "Sydney / Florida",
        "{{CRM_NAME}}": "TradieM8",
        "{{STAT_1}}": "22% Leaks Plugged",
        "{{STAT_2}}": "Audit-Ready"
    }

    for p, v in placeholders.items():
        page_content = page_content.replace(p, v)

    return HTMLResponse(content=page_content)

if __name__ == "__main__":
    uvicorn.run(app, host="0.0.0.0", port=8080)
