import logging import os from contextlib import asynccontextmanager from fastapi import FastAPI from fastapi.middleware.cors import CORSMiddleware from fastapi.exceptions import RequestValidationError from starlette.exceptions import HTTPException as StarletteHTTPException from backend.api import ( auth_api, patient_api, session_api, analysis_api, safety_api, notification_api, settings_api, ingestion_api, telemetry_api, ) from backend.routers import cloud_orchestrate, cloud_consult, agent_tools logger = logging.getLogger(__name__) @asynccontextmanager async def lifespan(app: FastAPI): logger.info("Starting medical imaging AI platform API") yield logger.info("Shutting down medical imaging AI platform API") app = FastAPI( title="Medical Imaging & AI Safety Platform", description="Clinical diagnostic imaging platform with AI safety analysis", version="0.1.0", lifespan=lifespan, ) app.add_middleware( CORSMiddleware, allow_origins=os.getenv( "CORS_ORIGINS", "http://localhost:3000,http://localhost:5173,http://localhost:5174,http://localhost:4173", ).split(","), allow_credentials=True, allow_methods=["*"], allow_headers=["*"], ) @app.exception_handler(RequestValidationError) async def validation_exception_handler(request, exc): from fastapi.responses import JSONResponse from data.spec.schemas import ErrorResponse return JSONResponse( status_code=422, content=ErrorResponse(detail=str(exc), code="VALIDATION_ERROR").model_dump(), ) @app.exception_handler(StarletteHTTPException) async def http_exception_handler(request, exc): from fastapi.responses import JSONResponse from data.spec.schemas import ErrorResponse content = ErrorResponse(detail=exc.detail, code="HTTP_ERROR").model_dump() return JSONResponse(status_code=exc.status_code, content=content) @app.exception_handler(NotImplementedError) async def not_implemented_handler(request, exc): from fastapi.responses import JSONResponse from data.spec.schemas import ErrorResponse content = ErrorResponse(detail=str(exc), code="NOT_IMPLEMENTED").model_dump() return JSONResponse(status_code=501, content=content) app.include_router(cloud_orchestrate.router) app.include_router(cloud_consult.router) app.include_router(agent_tools.router) app.include_router(auth_api.router) app.include_router(patient_api.router) app.include_router(session_api.router) app.include_router(analysis_api.router) app.include_router(safety_api.router) app.include_router(notification_api.router) app.include_router(settings_api.router) app.include_router(ingestion_api.router) app.include_router(telemetry_api.router)