"""Health check endpoints."""

from fastapi import APIRouter, Request
from fastapi.responses import JSONResponse

router = APIRouter()


@router.get("/health")
async def health_check() -> dict[str, str]:
    """Basic health check endpoint.

    Returns healthy if the service is running.
    Does not check dependencies (use /ready for that).
    """
    return {"status": "healthy"}


@router.get("/ready", response_model=None)
async def readiness_check(request: Request):
    """Readiness check - verify dependencies are available.

    Checks:
    - Database connection is working

    Returns 503 if any dependency is unavailable.
    """
    checks: dict[str, str] = {}

    # Check database connection
    try:
        db = getattr(request.app.state, "db", None)
        if db is None:
            checks["database"] = "not configured"
        else:
            # Try a simple query - works for both real pool and mock
            if hasattr(db, "fetch_one"):
                await db.fetch_one("SELECT 1")
            elif hasattr(db, "execute"):
                await db.execute("SELECT 1")
            # Show if using real or mock DB
            db_type = type(db).__name__
            checks["database"] = f"ok ({db_type})"
    except Exception as e:
        checks["database"] = f"error: {e}"
        return JSONResponse(
            status_code=503,
            content={"status": "not ready", "checks": checks},
        )

    return {"status": "ready", "checks": checks}
