from contextlib import asynccontextmanager
from pathlib import Path

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

from .core.config import get_settings
from .routers import auth, dataset, inference, platform, predictions, statistics, web

settings = get_settings()


@asynccontextmanager
async def lifespan(app: FastAPI):
    # Pre-load ML models on startup to avoid cold-start latency
    from .routers.inference import _load_models
    _load_models()
    yield


app = FastAPI(
    title="OpenData II — Panel Interno",
    description=(
        "API interna para administradores: estadísticas descriptivas, "
        "dashboards ML/NLP, inferencia de modelos en tiempo real y "
        "acceso completo a la base de datos de la plataforma de usuarios."
    ),
    version="1.0.0",
    lifespan=lifespan,
    docs_url="/docs",
    redoc_url="/redoc",
)

app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

app.mount("/static", StaticFiles(directory=Path(__file__).parent / "static"), name="static")

# Web panel (HTML — cookie auth) — must be included BEFORE JSON API routers
# so that GET "/" is handled by the web router, not the JSON root.
app.include_router(web.router)

# JSON API routers
app.include_router(auth.router)
app.include_router(statistics.router)
app.include_router(predictions.router)
app.include_router(inference.router)
app.include_router(dataset.router)
app.include_router(platform.router)


@app.get("/health", tags=["Root"], summary="Estado del servicio")
def health():
    return {"status": "ok"}


@app.get("/api", tags=["Root"], summary="Información de la API JSON")
def api_info():
    return {
        "service": "OpenData II — Internal API",
        "version": "1.0.0",
        "docs": "/docs",
        "redoc": "/redoc",
        "panel": "/panel",
    }
