from pathlib import Path
import uuid

from fastapi import FastAPI, HTTPException, Request
from fastapi.responses import HTMLResponse
from fastapi.staticfiles import StaticFiles
from fastapi.templating import Jinja2Templates
from pydantic import BaseModel, Field

from src.dashboard_service import build_dashboard_payload, load_analyzed_reviews
from src.graph import feedback_graph

BASE_DIR = Path(__file__).resolve().parent
RESULTS_FILE = BASE_DIR / "outputs" / "analyzed_reviews.jsonl"

app = FastAPI(
    title="Customer Feedback Intelligence",
    version="1.0.0",
    description="Parallel multi-agent customer feedback analytics dashboard.",
)

app.mount("/static", StaticFiles(directory=BASE_DIR / "static"), name="static")
templates = Jinja2Templates(directory=BASE_DIR / "templates")


class LiveFeedbackRequest(BaseModel):
    feedback: str = Field(min_length=5, max_length=5000)


@app.get("/", response_class=HTMLResponse)
def dashboard(request: Request):
    return templates.TemplateResponse(request=request, name="index.html", context={})


@app.get("/api/dashboard")
def dashboard_data():
    return build_dashboard_payload(load_analyzed_reviews(RESULTS_FILE))


@app.post("/api/analyze")
def analyze_feedback(payload: LiveFeedbackRequest):
    customer_id = f"LIVE-{uuid.uuid4().hex[:6].upper()}"
    try:
        result = feedback_graph.invoke(
            {"customer_id": customer_id, "feedback": payload.feedback},
            config={"max_concurrency": 4},
        )
    except Exception as exc:
        raise HTTPException(status_code=500, detail=f"Analysis failed: {exc}") from exc
    return result["final_analysis"].model_dump()


@app.get("/health")
def health():
    return {"status": "ok"}
