"""Formal FastAPI entrypoint for the creation-knowledge workbench."""
from __future__ import annotations

import os
from pathlib import Path

from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from fastapi.middleware.gzip import GZipMiddleware
from fastapi.staticfiles import StaticFiles

from app.routes import acquisition, decode, manual_queries, payloads, query_generation, runs

ROOT = Path(__file__).resolve().parent.parent
FRONTEND_DIST = ROOT / "app" / "frontend" / "dist"


def _cors_origins() -> list[str]:
    raw = os.getenv("CK_CORS_ORIGINS", "")
    if raw.strip():
        return [item.strip() for item in raw.split(",") if item.strip()]
    return [
        "http://localhost:5173",
        "http://127.0.0.1:5173",
        "http://localhost:5180",
        "http://127.0.0.1:5180",
    ]


def create_app() -> FastAPI:
    app = FastAPI(title="创作知识发现解构工作台", version="0.6.0")
    app.add_middleware(
        CORSMiddleware,
        allow_origins=_cors_origins(),
        allow_credentials=True,
        allow_methods=["GET", "POST", "PATCH", "OPTIONS"],
        allow_headers=["Authorization", "Content-Type"],
    )
    app.add_middleware(GZipMiddleware, minimum_size=1024)
    app.include_router(acquisition.router)
    app.include_router(decode.router)
    app.include_router(manual_queries.router)
    app.include_router(payloads.router)
    app.include_router(query_generation.router)
    app.include_router(runs.router)

    @app.get("/health")
    def health() -> dict[str, str]:
        return {"status": "ok", "entrypoint": "app.api:app"}

    if FRONTEND_DIST.exists():
        app.mount("/app", StaticFiles(directory=str(FRONTEND_DIST), html=True), name="app")
    return app


app = create_app()
