import logging from fastapi import FastAPI from fastapi.middleware.cors import CORSMiddleware from fastapi.responses import JSONResponse from app.api.v1.api import api_router from app.core.config import settings from app.db.init_db import ensure_db_dir_exists, init_db logging.basicConfig(level=logging.INFO) logger = logging.getLogger(__name__) # Create FastAPI app app = FastAPI( title=settings.PROJECT_NAME, openapi_url="/openapi.json", ) # Configure CORS if settings.BACKEND_CORS_ORIGINS: app.add_middleware( CORSMiddleware, allow_origins=[str(origin) for origin in settings.BACKEND_CORS_ORIGINS], allow_credentials=True, allow_methods=["*"], allow_headers=["*"], ) # Include API router app.include_router(api_router, prefix=settings.API_V1_STR) # Startup event to initialize database @app.on_event("startup") async def startup_db_client(): try: logger.info("Ensuring database directory exists") ensure_db_dir_exists() logger.info("Database directory check completed") except Exception as e: logger.error(f"Failed to initialize database directory: {str(e)}") # We don't want to crash the app if this fails, just log the error # Health check endpoint @app.get("/health", response_model=None) async def health_check(): """ Health check endpoint to verify the API is running. """ # Check database directory try: db_dir_exists = settings.DB_DIR.exists() except Exception: db_dir_exists = False health_status = { "status": "healthy", "api": "ok", "db_directory": "ok" if db_dir_exists else "missing", } if not db_dir_exists: health_status["status"] = "degraded" return JSONResponse(content=health_status) if __name__ == "__main__": import uvicorn uvicorn.run(app, host="0.0.0.0", port=8000)