"""Enterprise health checks — liveness, readiness, and deep diagnostics.

Provides Kubernetes-compatible health endpoints and system diagnostics
for enterprise deployments. Stdlib-only.
"""

from __future__ import annotations

import os
import platform
import sys
import time
from collections.abc import Callable
from dataclasses import dataclass
from enum import Enum


class HealthStatus(Enum):
    """Health check result status."""

    HEALTHY = "healthy"
    DEGRADED = "degraded"
    UNHEALTHY = "unhealthy"


@dataclass(frozen=True)
class CheckResult:
    """Result of a single health check."""

    name: str
    status: HealthStatus
    message: str = ""
    latency_ms: float = 0.0

    def to_dict(self) -> dict:
        return {
            "name": self.name,
            "status": self.status.value,
            "message": self.message,
            "latency_ms": round(self.latency_ms, 2),
        }


class HealthChecker:
    """Enterprise health checker with liveness and readiness probes."""

    def __init__(self, version: str = "0.1.0") -> None:
        self._version = version
        self._start_time = time.time()
        self._checks: dict[str, Callable[..., CheckResult | str]] = {}
        self._register_default_checks()

    def _register_default_checks(self) -> None:
        """Register built-in health checks."""
        self._checks["kernel"] = self._check_kernel
        self._checks["dag"] = self._check_dag
        self._checks["audit"] = self._check_audit

    def register_check(self, name: str, check_fn: Callable[..., CheckResult | str]) -> None:
        """Register a custom health check."""
        self._checks[name] = check_fn

    def liveness(self) -> dict:
        """Kubernetes liveness probe — is the process alive?"""
        return {
            "status": "ok",
            "version": self._version,
            "uptime_seconds": round(time.time() - self._start_time, 1),
        }

    def readiness(self) -> dict:
        """Kubernetes readiness probe — can we serve traffic?"""
        results = self.run_checks()
        overall = HealthStatus.HEALTHY

        for r in results:
            if r.status == HealthStatus.UNHEALTHY:
                overall = HealthStatus.UNHEALTHY
                break
            if r.status == HealthStatus.DEGRADED:
                overall = HealthStatus.DEGRADED

        return {
            "status": overall.value,
            "checks": [r.to_dict() for r in results],
            "ready": overall != HealthStatus.UNHEALTHY,
        }

    def deep_check(self) -> dict:
        """Full diagnostic check with system info."""
        readiness = self.readiness()
        return {
            **readiness,
            "system": {
                "python_version": sys.version,
                "platform": platform.platform(),
                "pid": os.getpid(),
                "version": self._version,
                "uptime_seconds": round(time.time() - self._start_time, 1),
            },
        }

    def run_checks(self) -> list[CheckResult]:
        """Run all registered health checks."""
        results: list[CheckResult] = []
        for name, check_fn in sorted(self._checks.items()):
            start = time.monotonic()
            try:
                result = check_fn()
                elapsed = (time.monotonic() - start) * 1000
                if isinstance(result, CheckResult):
                    results.append(result)
                else:
                    results.append(
                        CheckResult(
                            name=name,
                            status=HealthStatus.HEALTHY,
                            message=str(result),
                            latency_ms=elapsed,
                        )
                    )
            except Exception as e:
                elapsed = (time.monotonic() - start) * 1000
                results.append(
                    CheckResult(
                        name=name,
                        status=HealthStatus.UNHEALTHY,
                        message=str(e),
                        latency_ms=elapsed,
                    )
                )
        return results

    def _check_kernel(self) -> CheckResult:
        """Check kernel module import."""
        from orxaq.kernel.types import Entity

        Entity(entity_id="test", name="test")
        return CheckResult(name="kernel", status=HealthStatus.HEALTHY, message="ok")

    def _check_dag(self) -> CheckResult:
        """Check DAG operations."""
        from orxaq.kernel.types import CausalEdge, Entity
        from orxaq.kernel.world_dag import WorldDAG

        dag = WorldDAG()
        dag.add_entity(Entity(entity_id="x", name="x"))
        dag.add_entity(Entity(entity_id="y", name="y"))
        dag.add_edge(CausalEdge(source="x", target="y"))
        assert dag.node_count() == 2
        return CheckResult(name="dag", status=HealthStatus.HEALTHY, message="ok")

    def _check_audit(self) -> CheckResult:
        """Check audit log operations."""
        from orxaq.kernel.audit import AuditLog

        log = AuditLog()
        log.append(action="health_check", actor="system")
        assert log.verify()
        return CheckResult(name="audit", status=HealthStatus.HEALTHY, message="ok")
