from contextlib import asynccontextmanager from pathlib import Path from fastapi import FastAPI from fastapi.responses import FileResponse, JSONResponse from fastapi.staticfiles import StaticFiles from backend.app.db.connection import QueryError, close_pool, open_pool from backend.app.api.routes import readings, receipts, health, chat, reports FRONTEND = Path(__file__).resolve().parents[2] / "frontend" STATUS = { "P0400": 400, "P0403": 403, "P0404": 404, "P0409": 409, } @asynccontextmanager async def lifespan(_: FastAPI): await open_pool() yield await close_pool() def create_app() -> FastAPI: app = FastAPI( title="dark-tariff", lifespan=lifespan, docs_url=None, redoc_url=None, openapi_url=None, max_body_size=65536, ) for router in (readings.router, receipts.router, health.router, chat.router, reports.router): app.include_router(router) @app.exception_handler(QueryError) async def query_error(_, exc: QueryError): status = STATUS.get(exc.sqlstate, 500) return JSONResponse( {"detail": exc.message if status != 500 else "The service could not process the request."}, status_code=status, ) app.mount("/static", StaticFiles(directory=FRONTEND), name="static") @app.middleware("http") async def revalidate_static(request, call_next): response = await call_next(request) if request.url.path.startswith("/static/"): response.headers["Cache-Control"] = "no-cache" if request.url.path.startswith("/api/") and request.method == "POST": response.headers["Cache-Control"] = "no-store" return response @app.get("/", include_in_schema=False) async def index(): return FileResponse(FRONTEND / "public" / "index.html") return app