"""Health check endpoint for WealthWise API. This module provides a comprehensive health check endpoint that verifies: - Application is running - Database connectivity - Overall system status """ from fastapi import APIRouter, Depends, HTTPException, status from sqlalchemy import text from sqlmodel.ext.asyncio.session import AsyncSession from app.api.deps import SessionDep from app.core.config import get_settings from app.core.db import check_db_connection router = APIRouter() settings = get_settings() @router.get( "/health", summary="Health check endpoint", description="Performs comprehensive health checks including database connectivity.", response_description="Health status with version and database state", tags=["Health"], ) async def health_check(session: AsyncSession = SessionDep) -> dict: """Check application and database health. This endpoint performs an actual database query (SELECT 1) to verify that the database connection is working properly. It returns a detailed health status including: - Overall application status - Database connectivity state - Application version Returns: dict: Health status object with the following structure: { "status": "healthy" | "degraded", "database": "connected" | "disconnected", "version": "1.0.0", "timestamp": "2024-01-01T00:00:00Z" } Raises: HTTPException: 503 if database is unreachable """ health_status = { "status": "healthy", "database": "connected", "version": settings.VERSION, } try: # Perform actual database query to verify connectivity result = await session.execute(text("SELECT 1")) db_response = result.scalar() if db_response != 1: raise Exception("Unexpected database response") except Exception as e: health_status.update({ "status": "degraded", "database": "disconnected", "error": str(e), }) raise HTTPException( status_code=status.HTTP_503_SERVICE_UNAVAILABLE, detail=health_status, ) return health_status @router.get( "/health/ready", summary="Readiness probe", description="Kubernetes-style readiness probe endpoint.", tags=["Health"], ) async def readiness_probe() -> dict: """Kubernetes readiness probe. Returns 200 if the application is ready to receive traffic. Used by container orchestrators to determine when to route traffic. Returns: dict: Simple status object """ return {"ready": True} @router.get( "/health/live", summary="Liveness probe", description="Kubernetes-style liveness probe endpoint.", tags=["Health"], ) async def liveness_probe() -> dict: """Kubernetes liveness probe. Returns 200 if the application is alive and should not be restarted. Used by container orchestrators to detect deadlocks or stuck processes. Returns: dict: Simple status object """ return {"alive": True}