"""Tests for enterprise health checks and configuration."""

from __future__ import annotations

from unittest.mock import patch

from orxaq.enterprise.config import EnterpriseConfig
from orxaq.enterprise.health import CheckResult, HealthChecker, HealthStatus

# ── HealthStatus ─────────────────────────────────────────────


class TestHealthStatus:
    def test_values(self):
        assert HealthStatus.HEALTHY.value == "healthy"
        assert HealthStatus.DEGRADED.value == "degraded"
        assert HealthStatus.UNHEALTHY.value == "unhealthy"


# ── CheckResult ──────────────────────────────────────────────


class TestCheckResult:
    def test_creation(self):
        r = CheckResult(name="test", status=HealthStatus.HEALTHY)
        assert r.name == "test"
        assert r.message == ""

    def test_to_dict(self):
        r = CheckResult(
            name="dag",
            status=HealthStatus.HEALTHY,
            message="ok",
            latency_ms=1.234,
        )
        d = r.to_dict()
        assert d["name"] == "dag"
        assert d["status"] == "healthy"
        assert d["latency_ms"] == 1.23


# ── HealthChecker ────────────────────────────────────────────


class TestHealthChecker:
    def test_liveness(self):
        hc = HealthChecker()
        result = hc.liveness()
        assert result["status"] == "ok"
        assert "version" in result
        assert result["uptime_seconds"] >= 0

    def test_readiness(self):
        hc = HealthChecker()
        result = hc.readiness()
        assert result["ready"] is True
        assert result["status"] == "healthy"
        assert len(result["checks"]) >= 3

    def test_deep_check(self):
        hc = HealthChecker()
        result = hc.deep_check()
        assert "system" in result
        assert "python_version" in result["system"]
        assert "platform" in result["system"]
        assert result["ready"] is True

    def test_run_checks(self):
        hc = HealthChecker()
        results = hc.run_checks()
        assert len(results) >= 3
        for r in results:
            assert isinstance(r, CheckResult)
            assert r.status == HealthStatus.HEALTHY

    def test_custom_check(self):
        hc = HealthChecker()

        def my_check():
            return CheckResult(name="custom", status=HealthStatus.HEALTHY, message="works")

        hc.register_check("custom", my_check)
        results = hc.run_checks()
        names = [r.name for r in results]
        assert "custom" in names

    def test_failing_check(self):
        hc = HealthChecker()

        def bad_check():
            msg = "broken"
            raise RuntimeError(msg)

        hc.register_check("bad", bad_check)
        result = hc.readiness()
        assert result["status"] == "unhealthy"
        assert result["ready"] is False

    def test_degraded_check(self):
        hc = HealthChecker()

        def slow_check():
            return CheckResult(name="slow", status=HealthStatus.DEGRADED, message="slow")

        hc.register_check("slow", slow_check)
        result = hc.readiness()
        assert result["status"] in ("degraded", "healthy")

    def test_check_kernel(self):
        hc = HealthChecker()
        r = hc._check_kernel()
        assert r.status == HealthStatus.HEALTHY

    def test_check_dag(self):
        hc = HealthChecker()
        r = hc._check_dag()
        assert r.status == HealthStatus.HEALTHY

    def test_check_audit(self):
        hc = HealthChecker()
        r = hc._check_audit()
        assert r.status == HealthStatus.HEALTHY

    def test_version(self):
        hc = HealthChecker(version="2.0.0")
        result = hc.liveness()
        assert result["version"] == "2.0.0"

    def test_string_return_check(self):
        hc = HealthChecker()

        def str_check():
            return "all good"

        hc.register_check("str_check", str_check)
        results = hc.run_checks()
        found = [r for r in results if r.name == "str_check"]
        assert len(found) == 1
        assert found[0].status == HealthStatus.HEALTHY


# ── EnterpriseConfig ─────────────────────────────────────────


class TestEnterpriseConfig:
    def test_defaults(self):
        config = EnterpriseConfig()
        assert config.port == 8741
        assert config.host == "0.0.0.0"
        assert config.workers == 1
        assert config.auth_enabled is False

    def test_from_env(self):
        env = {
            "ORXAQ_PORT": "9000",
            "ORXAQ_HOST": "127.0.0.1",
            "ORXAQ_WORKERS": "4",
            "ORXAQ_AUTH_ENABLED": "true",
            "ORXAQ_LOG_LEVEL": "DEBUG",
        }
        with patch.dict("os.environ", env, clear=True):
            config = EnterpriseConfig.from_env()
        assert config.port == 9000
        assert config.host == "127.0.0.1"
        assert config.workers == 4
        assert config.auth_enabled is True
        assert config.log_level == "DEBUG"

    def test_from_env_defaults(self):
        with patch.dict("os.environ", {}, clear=True):
            config = EnterpriseConfig.from_env()
        assert config.port == 8741
        assert config.auth_enabled is False

    def test_to_dict(self):
        config = EnterpriseConfig()
        d = config.to_dict()
        assert d["port"] == 8741
        assert d["host"] == "0.0.0.0"
        assert "cors_origins" in d
        assert "plugin_dir" in d

    def test_frozen(self):
        config = EnterpriseConfig()
        try:
            config.port = 9999  # type: ignore[misc]
            assert False, "should be frozen"
        except AttributeError:
            pass
