"""FastAPI application factory and lifecycle. Startup runs migrations and opens the database engine; shutdown disposes it so no connection or engine resource leaks. The engine, session factory, and config live on ``app.state`` for dependencies to use. The app binds to 127.0.0.1 by default and exposes the versioned ``/api/v1`` surface; US01-02 ships only health. """ from __future__ import annotations from contextlib import asynccontextmanager from fastapi import FastAPI from photo_pipeline.api.routes import health, thumbnails from photo_pipeline.config import Config from photo_pipeline.db import create_db_engine, create_session_factory, run_migrations from photo_pipeline.logging import configure_logging def create_app(config: Config | None = None) -> FastAPI: config = config or Config.from_env() configure_logging(config.log_level, config.log_format) @asynccontextmanager async def lifespan(app: FastAPI): config.database_path.parent.mkdir(parents=True, exist_ok=True) run_migrations(config.database_url) engine = create_db_engine(config.database_url) app.state.config = config app.state.engine = engine app.state.session_factory = create_session_factory(engine) try: yield finally: engine.dispose() app.state.engine = None app = FastAPI(title="Photo Pipeline", version="0.1.0", lifespan=lifespan) app.include_router(health.router, prefix="/api/v1") app.include_router(thumbnails.router, prefix="/api/v1") return app