"""
FastAPI Server for Historical-2d Studio Review Dashboard.
Listens on port 1516 across all interfaces (0.0.0.0) for Tailscale access.
"""

import os
from pathlib import Path
from fastapi import FastAPI, HTTPException, Request
from fastapi.responses import HTMLResponse, JSONResponse, FileResponse
from fastapi.staticfiles import StaticFiles
from fastapi.middleware.cors import CORSMiddleware
from pydantic import BaseModel
from typing import Optional

from src.web_review.data_service import (
    get_system_status,
    get_intro_scenes,
    get_episodes_list,
    get_ep01_detail,
    get_document,
    get_feedback_list,
    save_feedback
)

BASE_DIR = Path(__file__).resolve().parent.parent.parent
STATIC_DIR = Path(__file__).resolve().parent / "static"
OUTPUT_DIR = BASE_DIR / "output"
EPISODES_DIR = BASE_DIR / "episodes"
ASSETS_DIR = BASE_DIR / "assets"
DATA_DIR = BASE_DIR / "data"

app = FastAPI(
    title="Historical-2d Studio Review Dashboard",
    description="Interactive Executive Review System for Seven Nguyen over Tailscale",
    version="2026.1"
)

# Enable CORS for cross-device mobile access
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# Mount media directories
STATIC_DIR.mkdir(parents=True, exist_ok=True)
app.mount("/static", StaticFiles(directory=str(STATIC_DIR)), name="static")

if OUTPUT_DIR.exists():
    app.mount("/output", StaticFiles(directory=str(OUTPUT_DIR)), name="output_direct")
    app.mount("/media/output", StaticFiles(directory=str(OUTPUT_DIR)), name="output_media")
if EPISODES_DIR.exists():
    app.mount("/media/episodes", StaticFiles(directory=str(EPISODES_DIR)), name="episodes_media")
if ASSETS_DIR.exists():
    app.mount("/assets", StaticFiles(directory=str(ASSETS_DIR)), name="assets_direct")
    app.mount("/media/assets", StaticFiles(directory=str(ASSETS_DIR)), name="assets_media")

NODE_MODULES_DIR = BASE_DIR / "node_modules"
if NODE_MODULES_DIR.exists():
    app.mount("/node_modules", StaticFiles(directory=str(NODE_MODULES_DIR)), name="node_modules")

WEBGL_DIR = BASE_DIR / "src" / "webgl_engine"
if WEBGL_DIR.exists():
    app.mount("/src/webgl_engine", StaticFiles(directory=str(WEBGL_DIR)), name="webgl_engine")


class FeedbackPayload(BaseModel):
    author: Optional[str] = "Seven Nguyen"
    verdict: str  # APPROVED, REVISE, DIRECTIVE
    category: str  # video, map, script, roadmap, general
    comment: str
    timestamp: Optional[str] = None


@app.get("/", response_class=HTMLResponse)
@app.head("/", response_class=HTMLResponse)
async def serve_index():
    index_file = STATIC_DIR / "index.html"
    if not index_file.exists():
        return HTMLResponse("<h1>Historical-2d Review Dashboard</h1><p>Static index.html is being prepared...</p>")
    with open(index_file, "r", encoding="utf-8") as f:
        return HTMLResponse(content=f.read())


@app.get("/warroom", response_class=HTMLResponse)
async def serve_warroom():
    warroom_file = BASE_DIR / "src" / "webgl_engine" / "index.html"
    if not warroom_file.exists():
        raise HTTPException(status_code=404, detail="War Room file not found")
    with open(warroom_file, "r", encoding="utf-8") as f:
        return HTMLResponse(content=f.read())


@app.get("/api/status")
async def api_status():
    return JSONResponse(get_system_status())


@app.get("/api/scenes")
async def api_scenes():
    return JSONResponse(get_intro_scenes())


@app.get("/api/episodes")
async def api_episodes():
    return JSONResponse(get_episodes_list())


@app.get("/api/ep01")
async def api_ep01():
    return JSONResponse(get_ep01_detail())


@app.get("/api/docs/{doc_id}")
async def api_doc(doc_id: str):
    doc = get_document(doc_id)
    return JSONResponse(doc)


@app.get("/api/feedback")
async def api_get_feedback():
    return JSONResponse(get_feedback_list())


@app.post("/api/feedback")
async def api_post_feedback(payload: FeedbackPayload):
    import datetime
    now_str = datetime.datetime.now().astimezone().strftime("%Y-%m-%d %H:%M:%S %z")
    record = {
        "author": payload.author or "Seven Nguyen",
        "verdict": payload.verdict,
        "category": payload.category,
        "comment": payload.comment,
        "timestamp": payload.timestamp or now_str
    }
    result = save_feedback(record)
    return JSONResponse(result)


if __name__ == "__main__":
    import uvicorn
    uvicorn.run("src.web_review.server:app", host="0.0.0.0", port=1516, reload=False)
