import uvicorn
from fastapi import FastAPI, Request
from fastapi.responses import HTMLResponse
import re
import os
from core.architect.web_architect_skill import WebArchitectSkill
from core.architect.site_factory import SiteFactory

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)
    
@app.get("/architect/{niche}")
async def serve_architected_page(niche: str):
    """
    Serves the high-fidelity site generated by the Genesis Web Architect.
    """
    file_path = f"dist/web/{niche.lower()}_index.html"
    if not os.path.exists(file_path):
        return HTMLResponse(f"<h1>Architected Site for {niche} not found</h1><p>Run /architect/build/{niche} first.</p>")
    
    with open(file_path, "r", encoding="utf-8") as f:
        content = f.read()
    return HTMLResponse(content=content)

@app.post("/architect/build/{niche}")
async def build_architected_page(niche: str, prompt: str = "Build a landing page"):
    """
    Triggers the Web Architect flow: Manifest -> Factory -> Build.
    """
    architect = WebArchitectSkill()
    factory = SiteFactory()
    
    # In a real scenario, the prompt would be enriched with niche data
    manifest = architect.generate_manifest(f"{prompt} targeting {niche}")
    manifest_path = architect.save_manifest(manifest)
    
    output_path = factory.build_site(manifest_path)
    
    return {"status": "success", "output_path": output_path, "niche": niche}

if __name__ == "__main__":
    uvicorn.run(app, host="0.0.0.0", port=8080)
