"""FastAPI application entry point."""

import asyncio

import structlog
from fastapi import FastAPI, Request
from fastapi.responses import FileResponse, Response
from fastapi.staticfiles import StaticFiles

from navi.api.routes import agents, health, messages, sessions
from navi.api.websocket import router as ws_router
from navi.config import settings

structlog.configure(
    wrapper_class=structlog.make_filtering_bound_logger(
        getattr(__import__("logging"), settings.log_level)
    ),
)

app = FastAPI(
    title="Navi",
    description="Modular agent system — REST API and WebSocket",
    version="0.1.0",
)

app.include_router(health.router)
app.include_router(agents.router)
app.include_router(sessions.router)
app.include_router(messages.router)
app.include_router(ws_router)

app.mount("/static", StaticFiles(directory="client"), name="static")


@app.on_event("startup")
async def _start_session_file_cleanup() -> None:
    from navi.api.deps import get_session_store
    from navi.session_files import cleanup_loop
    asyncio.create_task(cleanup_loop(get_session_store()))


@app.middleware("http")
async def no_cache_static(request: Request, call_next) -> Response:
    response = await call_next(request)
    if request.url.path.startswith("/static/"):
        response.headers["Cache-Control"] = "no-store"
    return response


@app.get("/", include_in_schema=False)
async def index() -> FileResponse:
    return FileResponse("client/index.html", headers={"Cache-Control": "no-store"})


@app.get("/debug", include_in_schema=False)
async def debug() -> FileResponse:
    return FileResponse("client/debug.html", headers={"Cache-Control": "no-store"})
