""" FastAPI application entry point for Delphi Database. This module initializes the FastAPI application, sets up database connections, and provides the main application instance. """ import os import logging from contextlib import asynccontextmanager from fastapi import FastAPI, Depends, Request from fastapi.middleware.sessions import SessionMiddleware from fastapi.middleware.cors import CORSMiddleware from fastapi.staticfiles import StaticFiles from fastapi.templating import Jinja2Templates from sqlalchemy.orm import Session from dotenv import load_dotenv from .database import create_tables, get_db, get_database_url from .models import User # Load environment variables load_dotenv() # Get SECRET_KEY from environment variables SECRET_KEY = os.getenv("SECRET_KEY") if not SECRET_KEY: raise ValueError("SECRET_KEY environment variable must be set") # Configure logging logging.basicConfig(level=logging.INFO) logger = logging.getLogger(__name__) # Configure Jinja2 templates templates = Jinja2Templates(directory="app/templates") @asynccontextmanager async def lifespan(app: FastAPI): """ Lifespan context manager for FastAPI application. Handles startup and shutdown events: - Creates database tables on startup - Logs database connection info """ # Startup logger.info("Starting Delphi Database application...") # Create database tables create_tables() logger.info("Database tables created/verified") # Log database connection info db_url = get_database_url() logger.info(f"Database connected: {db_url}") yield # Shutdown logger.info("Shutting down Delphi Database application...") # Create FastAPI application with lifespan management app = FastAPI( title="Delphi Database", description="Legal case management database application", version="1.0.0", lifespan=lifespan ) # Add CORS middleware for cross-origin requests app.add_middleware( CORSMiddleware, allow_origins=["*"], # In production, specify allowed origins allow_credentials=True, allow_methods=["*"], allow_headers=["*"], ) # Add SessionMiddleware for session management app.add_middleware(SessionMiddleware, secret_key=SECRET_KEY) # Mount static files directory app.mount("/static", StaticFiles(directory="static"), name="static") @app.get("/") async def root(): """ Root endpoint - health check. """ return {"message": "Delphi Database API is running"} @app.get("/health") async def health_check(db: Session = Depends(get_db)): """ Health check endpoint that verifies database connectivity. """ try: # Test database connection by querying user count user_count = db.query(User).count() return { "status": "healthy", "database": "connected", "users": user_count } except Exception as e: logger.error(f"Health check failed: {e}") return { "status": "unhealthy", "database": "error", "error": str(e) }