"""Application factory: router mount, middleware, exception handlers.""" import logging from collections.abc import AsyncIterator from contextlib import asynccontextmanager from fastapi import FastAPI, Request from fastapi.encoders import jsonable_encoder from fastapi.exceptions import RequestValidationError from fastapi.middleware.cors import CORSMiddleware from fastapi.responses import JSONResponse from app.api.v1.router import api_router from app.common.exceptions import AppError from app.config.settings import settings from app.database import all_models # noqa: F401 - registers every mapper from app.pdf.service import pdf_engine_ready logging.basicConfig( level=logging.DEBUG if settings.DEBUG else logging.INFO, format="%(asctime)s %(levelname)s %(name)s %(message)s", ) logger = logging.getLogger(__name__) def _preflight() -> None: """Refuse to start a production instance that would silently misbehave.""" production = settings.ENVIRONMENT.lower() == "production" if not pdf_engine_ready(): if production: raise RuntimeError("WeasyPrint system libraries are required in production") logger.warning("WeasyPrint is unavailable: PDFs will be plain text, not the form layout.") weak_key = settings.SECRET_KEY.startswith("change-me") or len(settings.SECRET_KEY) < 32 if production and weak_key: raise RuntimeError("SECRET_KEY must be a random value of at least 32 characters") @asynccontextmanager async def lifespan(_: FastAPI) -> AsyncIterator[None]: _preflight() yield def create_app() -> FastAPI: app = FastAPI( lifespan=lifespan, title=settings.APP_NAME, version="0.1.0", description=( "Pharmaceutical field-force reporting — MVP. " "Daily Call Reports with AM final approval, GM monitoring, " "locked PDFs and audit trails." ), docs_url="/docs", redoc_url="/redoc", openapi_url="/openapi.json", ) app.add_middleware( CORSMiddleware, allow_origins=settings.CORS_ORIGINS, allow_credentials=True, allow_methods=["*"], allow_headers=["*"], ) # ---- one consistent error envelope ------------------------------- @app.exception_handler(AppError) async def app_error_handler(_: Request, exc: AppError) -> JSONResponse: return JSONResponse(status_code=exc.status_code, content=exc.to_dict()) @app.exception_handler(RequestValidationError) async def validation_handler(_: Request, exc: RequestValidationError) -> JSONResponse: # Pydantic puts the original exception object in `ctx`, which is not JSON # serialisable — strip it, or the error handler itself becomes a 500. errors = [ {k: v for k, v in error.items() if k != "ctx"} | ( {"reason": str(error["ctx"].get("error"))} if isinstance(error.get("ctx"), dict) and "error" in error["ctx"] else {} ) for error in exc.errors() ] return JSONResponse( status_code=422, content=jsonable_encoder( { "error": { "code": "VALIDATION_ERROR", "message": "Request payload failed validation", "details": {"errors": errors}, } } ), ) app.include_router(api_router, prefix=settings.API_V1_PREFIX) @app.get("/health", tags=["meta"]) async def health() -> dict[str, str]: return { "status": "ok", "environment": settings.ENVIRONMENT, "pdf_engine": "weasyprint" if pdf_engine_ready() else "fallback", } return app app = create_app()