# backend/main.py
import os
import re
import io
import zipfile
from fastapi import FastAPI, HTTPException
from fastapi.responses import JSONResponse, StreamingResponse
from pydantic import BaseModel
from openai import OpenAI
from dotenv import load_dotenv

load_dotenv()

OPENROUTER_API_KEY = os.getenv("OPENROUTER_API_KEY")
if not OPENROUTER_API_KEY:
    raise ValueError("Missing OPENROUTER_API_KEY in .env")

YOUR_SITE_URL = os.getenv("FRONTEND_URL", "http://localhost:5173")
YOUR_SITE_NAME = os.getenv("APP_NAME", "SiteGen Agent")

client = OpenAI(
    base_url="https://openrouter.ai/api/v1",
    api_key=OPENROUTER_API_KEY,
)

MODEL = "meta-llama/llama-3.3-70b-instruct:free"

class GenerateRequest(BaseModel):
    prompt: str

def extract_html(text: str) -> str:
    match = re.search(r"```(?:html)?\s*(.*?)\s*```", text, re.DOTALL | re.IGNORECASE)
    if match:
        return match.group(1).strip()
    return text.strip()

def is_valid_html(html: str) -> bool:
    return any(tag in html.lower() for tag in ["<html", "<body", "<div", "<header"])

def ai_generate(prompt: str, max_attempts=3) -> str:
    system_msg = (
        "You are a senior frontend engineer. Generate a complete, self-contained, responsive HTML file "
        "with embedded CSS and JS. No external resources. Include <!DOCTYPE html>. "
        "Return ONLY the code — no explanations, no markdown."
    )
    messages = [{"role": "system", "content": system_msg}, {"role": "user", "content": prompt}]

    for attempt in range(max_attempts):
        try:
            resp = client.chat.completions.create(
                extra_headers={"HTTP-Referer": YOUR_SITE_URL, "X-Title": YOUR_SITE_NAME},
                model=MODEL,
                messages=messages,
                timeout=90,
            )
            raw = resp.choices[0].message.content
            html = extract_html(raw)

            if is_valid_html(html):
                return html

            messages.extend([
                {"role": "assistant", "content": raw},
                {"role": "user", "content": "Fix this. Return ONLY valid full HTML."}
            ])
        except Exception as e:
            if attempt == max_attempts - 1:
                raise HTTPException(500, f"Generation failed: {str(e)}")
    raise HTTPException(500, "Failed after retries")

app = FastAPI()

@app.post("/generate")
async def generate(req: GenerateRequest):
    html = ai_generate(req.prompt)
    return {"html": html}

@app.post("/download")
async def download(req: GenerateRequest):
    html = ai_generate(req.prompt)
    buf = io.BytesIO()
    with zipfile.ZipFile(buf, "w") as zf:
        zf.writestr("index.html", html)
    buf.seek(0)
    return StreamingResponse(
        buf,
        media_type="application/zip",
        headers={"Content-Disposition": "attachment; filename=sitegen_website.zip"}
    )
