"""cortex/api/routes/admin/health.py — Health check endpoints."""

from __future__ import annotations

from typing import Any

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

from cortex.api.deps import PREFIX, get_plugin


def _register(router: APIRouter, verify_api_key):
    """Register health routes on the given router."""

    @router.get(
        f"{PREFIX}/health",
        summary="System health",
        tags=["system"],
        operation_id="get_health",
    )
    async def get_health(
        detail: bool = False,
        plugin: Any = Depends(get_plugin),
    ):
        """Return health status for all Cortex modules.

        Without ``?detail=true``, returns the legacy structure
        (``ok``, ``storage``, ``modules``, ``errors``, ``timestamp``) with an added
        ``status`` field for forward-compatibility.

        With ``?detail=true``, also returns full HealthChecker output including
        storage stats, error rates, memory usage, and uptime.
        """
        from cortex.api.health import HealthChecker

        # Legacy plugin.health() for backward-compatible fields
        report = await plugin.health()

        # HealthChecker for richer status string + optional detail
        health_report = await HealthChecker.check(plugin, detail=detail)

        # ok reflects actual availability: True when healthy or degraded,
        # False only when truly unhealthy.
        effective_ok = health_report.status in ("healthy", "degraded")
        is_degraded = health_report.status == "degraded"

        # Extract disk usage for top-level exposure (CI-friendly)
        disk_check = health_report.checks.get("disk", {})
        disk_pct = disk_check.get("usage_pct", None)

        # Extract retrieval hydration for top-level exposure (#1583)
        hydration_check = health_report.checks.get("retrieval_hydration", {})

        base = {
            "ok": effective_ok,
            "degraded": is_degraded,
            "status": health_report.status,
            "version": health_report.version,
            "storage": report.storage,
            "modules": report.modules,
            "errors": report.errors,
            "timestamp": report.timestamp,
            "disk_usage_pct": disk_pct,
            "retrieval_hydration": hydration_check,
        }

        if detail:
            base.update({
                "checks": health_report.checks,
                "uptime_seconds": health_report.uptime_seconds,
                "version": health_report.version,
                "detail": health_report.detail,
            })

        return JSONResponse(content=base)

    @router.get(
        f"{PREFIX}/health/ready",
        summary="Readiness probe (Fly.io / k8s)",
        tags=["system"],
        operation_id="get_health_ready",
    )
    async def get_health_ready(
        plugin: Any = Depends(get_plugin),
    ):
        """Readiness probe endpoint.

        Returns 200 only when plugin is fully initialized AND storage is connected.
        Returns 503 during startup or if storage is disconnected.
        """
        from cortex.api.health import HealthChecker

        health_report = await HealthChecker.check(plugin)

        storage_check = health_report.checks.get("storage", {})
        storage_status = (
            storage_check.get("status", "unknown")
            if isinstance(storage_check, dict) else "ok"
        )

        if storage_status == "unhealthy" or health_report.status == "unhealthy":
            return JSONResponse(
                status_code=503,
                content={
                    "ready": False,
                    "reason": "storage unavailable or plugin unhealthy",
                    "status": health_report.status,
                },
            )

        return JSONResponse(content={"ready": True, "status": health_report.status})
