from __future__ import annotations

from fastapi import APIRouter
from sqlalchemy import text

from app.core.config import get_settings
from app.db.session import get_engine

router = APIRouter(prefix="/health")


@router.get("")
def health_check() -> dict[str, object]:
    settings = get_settings()
    database_ok = False
    database_error = None

    if settings.setup_completed:
        try:
            with get_engine().connect() as connection:
                connection.execute(text("SELECT 1"))
            database_ok = True
        except Exception as exc:  # pragma: no cover - runtime connectivity branch
            database_error = str(exc)

    return {
        "status": "ok" if database_ok else "degraded",
        "database": {
            "configured": settings.setup_completed,
            "ok": database_ok,
            "error": database_error,
        },
        "redis": {"configured": bool(settings.redis_url), "enabled": bool(settings.redis_url)},
    }
