"""
Health check endpoints.

Two distinct checks, both standard practice in production:
- /health/live  — "is the process alive at all". Used by systemd/Docker
  to decide whether to restart the process. Must be cheap and never
  depend on external services (DB/Redis) — if Postgres is briefly down,
  the process itself is still alive and should NOT be restarted for that.
- /health/ready — "is this instance able to actually serve requests".
  Used by Nginx/load balancer to decide whether to route traffic here.
  Checks DB and Redis connectivity and model load status.
"""

from fastapi import APIRouter

from app.core.config import get_settings
from app.db.session import check_db_connection
from app.models_loader.registry import model_registry
from app.services.cache_service import cache_service
from app.services.reference_data import reference_data

router = APIRouter()
settings = get_settings()


@router.get("/health/live")
async def liveness() -> dict:
    return {"status": "alive", "version": settings.APP_VERSION}


@router.get("/health/ready")
async def readiness() -> dict:
    db_ok = await check_db_connection()
    redis_ok = await cache_service.health_check()
    models_ok = model_registry.is_ready
    reference_ok = reference_data._loaded  # internal flag, acceptable for a health probe

    all_ok = db_ok and models_ok and reference_ok
    # Redis is deliberately NOT in the all_ok gate — the system degrades
    # gracefully without cache (see cache_service.py), so a Redis outage
    # should not pull this instance out of the load balancer rotation.

    return {
        "status": "ready" if all_ok else "not_ready",
        "checks": {
            "database": "ok" if db_ok else "failed",
            "redis_cache": "ok" if redis_ok else "degraded",
            "models_loaded": "ok" if models_ok else "failed",
            "reference_data_loaded": "ok" if reference_ok else "failed",
        },
        "loaded_models": model_registry.loaded_model_keys if models_ok else [],
    }
