import sys import os from pathlib import Path # Add project root to Python path for imports in alembic migrations project_root = Path(__file__).parent.absolute() sys.path.insert(0, str(project_root)) from fastapi import FastAPI, Request from fastapi.middleware.cors import CORSMiddleware from fastapi.responses import JSONResponse from app.api.routers import api_router from app.core.config import settings from app.db import init_db # Initialize the database on startup try: init_db.init_db() except Exception as e: print(f"Error initializing database: {e}") # Continue with app startup even if DB init fails, to allow debugging app = FastAPI(title=settings.PROJECT_NAME) # Set all CORS enabled origins - Allow all origins app.add_middleware( CORSMiddleware, allow_origins=["*"], allow_credentials=True, allow_methods=["*"], allow_headers=["*"], ) # Add exception handlers for better error reporting @app.exception_handler(Exception) async def validation_exception_handler(request: Request, exc: Exception): return JSONResponse( status_code=500, content={"detail": f"Internal Server Error: {str(exc)}"}, ) app.include_router(api_router) @app.get("/health", tags=["health"]) def health_check(): """ Health check endpoint to verify the application is running correctly """ return {"status": "ok"} @app.get("/db-test", tags=["health"]) def test_db_connection(): """ Test database connection and table creation """ from sqlalchemy import text from app.db.session import engine try: with engine.connect() as conn: # Try to select from the task table to verify it exists result = conn.execute(text("SELECT COUNT(*) FROM task")).scalar() return { "status": "ok", "connection": "successful", "task_count": result } except Exception as e: return { "status": "error", "connection": "failed", "error": str(e) }