from contextlib import asynccontextmanager from typing import AsyncGenerator from fastapi import FastAPI from fastapi.middleware.cors import CORSMiddleware from sqlalchemy.ext.asyncio import AsyncEngine, create_async_engine from app.config import settings from app.api.v1.router import api_v1_router from app.ws.handler import ws_router engine: AsyncEngine | None = None @asynccontextmanager async def lifespan(app: FastAPI) -> AsyncGenerator[None, None]: """Manage application lifespan: set up and tear down DB engine.""" global engine engine = create_async_engine( settings.DATABASE_URL, echo=False, pool_size=20, max_overflow=10, pool_pre_ping=True, ) yield if engine is not None: await engine.dispose() engine = None def create_app() -> FastAPI: """Application factory.""" application = FastAPI( title="Amazon AI Transcreation Platform", description="Backend API for AI-powered marketing transcreation", version="1.0.0", lifespan=lifespan, ) # CORS middleware (permissive for development) application.add_middleware( CORSMiddleware, allow_origins=["*"], allow_credentials=True, allow_methods=["*"], allow_headers=["*"], ) # API routes application.include_router(api_v1_router) # WebSocket routes application.include_router(ws_router) @application.get("/health", tags=["health"]) async def health_check() -> dict: return {"status": "healthy", "version": "1.0.0"} return application app = create_app()