import uvicorn import asyncio from datetime import datetime from fastapi import FastAPI, Depends from fastapi.middleware.cors import CORSMiddleware from sqlalchemy.orm import Session from app.api.v1.api import api_router from app.core.config import settings from app.db.session import get_db from app.core.background_tasks import task_manager app = FastAPI( title=settings.PROJECT_NAME, description=settings.PROJECT_DESCRIPTION, version=settings.VERSION, openapi_url="/openapi.json", docs_url="/docs", redoc_url="/redoc", ) # Set up CORS middleware app.add_middleware( CORSMiddleware, allow_origins=settings.BACKEND_CORS_ORIGINS, allow_credentials=True, allow_methods=["*"], allow_headers=["*"], ) # Include API router app.include_router(api_router, prefix=settings.API_V1_STR) # Root endpoint @app.get("/") async def root(): return { "name": settings.PROJECT_NAME, "version": settings.VERSION, "documentation": "/docs", "health": "/health" } # Health check endpoint @app.get("/health", tags=["health"]) async def health_check(db: Session = Depends(get_db)): # Check if database is available try: # Execute a simple query db.execute("SELECT 1") db_status = "connected" except Exception as e: db_status = f"error: {str(e)}" return { "status": "ok", "version": settings.VERSION, "timestamp": datetime.utcnow().isoformat(), "database": db_status, "environment": "production" if not settings.DEBUG else "development", } # Startup event @app.on_event("startup") async def startup_event(): # Start background tasks asyncio.create_task(task_manager.start()) # Shutdown event @app.on_event("shutdown") async def shutdown_event(): # Stop background tasks task_manager.stop() if __name__ == "__main__": uvicorn.run("main:app", host="0.0.0.0", port=8000, reload=True)