"""Tests for 4-tier health level system (HEALTHY/DEGRADED/WARNING/CRITICAL)."""

from __future__ import annotations


class TestHealthLevelDetermination:
    """Verify the 4-tier health level logic in __main__._main()."""

    def _run_with_results(self, results: dict) -> dict:
        """Simulate _main() health level computation without Telegram."""
        from heartbeat.config import CRITICAL_KEYS, DEGRADED_KEYS, WARNING_KEYS

        def _failed(keys: frozenset) -> list:
            return sorted(k for k in keys if results.get(k) is False)

        critical = _failed(CRITICAL_KEYS)
        warning = _failed(WARNING_KEYS)
        degraded = _failed(DEGRADED_KEYS)

        if critical:
            level = "critical"
        elif warning:
            level = "warning"
        elif degraded:
            level = "degraded"
        else:
            level = "healthy"

        healthy = level in ("healthy", "degraded")
        return {"level": level, "healthy": healthy, "critical": critical, "warning": warning, "degraded": degraded}

    def test_all_pass_is_healthy(self):
        """All gates True -> HEALTHY."""
        results = {k: True for k in [
            "clickhouse", "sidecar", "kintsugi", "disk",
            "stathera_overlaps", "stathera_gaps", "circuit_breaker_healthy",
            "kintsugi_stuck", "kintsugi_failures", "kintsugi_memory",
            "cross_midnight", "version_drift", "seeder_ok",
            "kintsugi_telemetry", "yesterday_completion",
        ]}
        r = self._run_with_results(results)
        assert r["level"] == "healthy"
        assert r["healthy"] is True

    def test_missing_keys_is_healthy(self):
        """Missing keys (None) -> HEALTHY (not False)."""
        r = self._run_with_results({})
        assert r["level"] == "healthy"
        assert r["healthy"] is True

    def test_degraded_only_is_degraded(self):
        """Only DEGRADED keys fail -> DEGRADED (still 'healthy' for backward compat)."""
        results = {"kintsugi_telemetry": False, "yesterday_completion": False}
        r = self._run_with_results(results)
        assert r["level"] == "degraded"
        assert r["healthy"] is True  # degraded is still "healthy" for message lifecycle

    def test_warning_key_is_warning(self):
        """WARNING key fails -> WARNING (not healthy)."""
        results = {"kintsugi_failures": False}
        r = self._run_with_results(results)
        assert r["level"] == "warning"
        assert r["healthy"] is False

    def test_critical_key_is_critical(self):
        """CRITICAL key fails -> CRITICAL."""
        results = {"clickhouse": False}
        r = self._run_with_results(results)
        assert r["level"] == "critical"
        assert r["healthy"] is False

    def test_critical_overrides_warning(self):
        """Both critical + warning failures -> CRITICAL (highest wins)."""
        results = {"clickhouse": False, "kintsugi_failures": False}
        r = self._run_with_results(results)
        assert r["level"] == "critical"
        assert "clickhouse" in r["critical"]

    def test_warning_overrides_degraded(self):
        """Warning + degraded failures -> WARNING."""
        results = {"seeder_ok": False, "kintsugi_telemetry": False}
        r = self._run_with_results(results)
        assert r["level"] == "warning"

    def test_kintsugi_1_failure_stathera_clean_is_warning_not_critical(self):
        """THE FALSE ALARM CASE: kintsugi_failures=False but stathera clean -> WARNING, not CRITICAL.

        This was the original bug: a single transient kintsugi failure during deploy
        triggered UNHEALTHY (now CRITICAL) even though Stathera showed zero gaps.
        With the 4-tier system, this correctly produces WARNING instead.
        """
        results = {
            "clickhouse": True,
            "sidecar": True,
            "kintsugi": True,
            "stathera_overlaps": True,
            "stathera_gaps": True,
            "circuit_breaker_healthy": True,
            "disk": True,
            # WARNING tier:
            "kintsugi_failures": False,  # <-- the transient failure
            "kintsugi_stuck": True,
            "version_drift": True,
            "seeder_ok": True,
        }
        r = self._run_with_results(results)
        assert r["level"] == "warning"  # NOT critical!
        assert r["healthy"] is False  # triggers persistent message
        assert "kintsugi_failures" in r["warning"]

    def test_stathera_gaps_growing_is_critical(self):
        """Stathera gaps = False (growing, not healing) -> CRITICAL."""
        results = {"stathera_gaps": False}
        r = self._run_with_results(results)
        assert r["level"] == "critical"

    def test_stathera_today_gaps_is_critical(self):
        """stathera_today_gaps=False -> CRITICAL (not WARNING)."""
        results = {"stathera_today_gaps": False}
        r = self._run_with_results(results)
        assert r["level"] == "critical"
        assert "stathera_today_gaps" in r["critical"]

    def test_stathera_today_overlaps_is_critical(self):
        """stathera_today_overlaps=False -> CRITICAL."""
        results = {"stathera_today_overlaps": False}
        r = self._run_with_results(results)
        assert r["level"] == "critical"
        assert "stathera_today_overlaps" in r["critical"]

    def test_circuit_breaker_open_is_critical(self):
        """Circuit breaker open -> CRITICAL."""
        results = {"circuit_breaker_healthy": False}
        r = self._run_with_results(results)
        assert r["level"] == "critical"


class TestFormatterHeaders:
    """Verify the formatter produces correct header for each tier."""

    def test_healthy_header(self):
        from heartbeat.formatter import format_message
        results = {"_health_level": "healthy"}
        msg = format_message(results, True)
        assert "Heartbeat OK" in msg
        assert "\U0001f49a" in msg  # green heart

    def test_degraded_header(self):
        from heartbeat.formatter import format_message
        results = {"_health_level": "degraded", "kintsugi_telemetry": False}
        msg = format_message(results, True)
        assert "DEGRADED" in msg
        assert "\U0001f7e1" in msg  # yellow circle

    def test_warning_header(self):
        from heartbeat.formatter import format_message
        results = {"_health_level": "warning", "kintsugi_failures": False}
        msg = format_message(results, False)
        assert "WARNING" in msg
        assert "\U0001f7e0" in msg  # orange circle

    def test_critical_header(self):
        from heartbeat.formatter import format_message
        results = {"_health_level": "critical", "clickhouse": False}
        msg = format_message(results, False)
        assert "CRITICAL" in msg
        assert "\U0001f534" in msg  # red circle


class TestTierAssignment:
    """Verify every HEALTH_GATE_KEY is assigned to exactly one tier."""

    def test_all_keys_assigned(self):
        from heartbeat.config import (
            CRITICAL_KEYS,
            DEGRADED_KEYS,
            HEALTH_GATE_KEYS,
            WARNING_KEYS,
        )
        assigned = CRITICAL_KEYS | WARNING_KEYS | DEGRADED_KEYS
        assert assigned == HEALTH_GATE_KEYS, f"Missing: {HEALTH_GATE_KEYS - assigned}"

    def test_no_overlap(self):
        from heartbeat.config import CRITICAL_KEYS, DEGRADED_KEYS, WARNING_KEYS
        assert not (CRITICAL_KEYS & WARNING_KEYS), "critical/warning overlap"
        assert not (CRITICAL_KEYS & DEGRADED_KEYS), "critical/degraded overlap"
        assert not (WARNING_KEYS & DEGRADED_KEYS), "warning/degraded overlap"

    def test_critical_keys_are_data_integrity(self):
        """CRITICAL tier should only contain data-integrity gates."""
        from heartbeat.config import CRITICAL_KEYS
        expected = {
            "clickhouse", "sidecar", "kintsugi", "disk",
            "stathera_overlaps", "stathera_gaps",
            "stathera_today_gaps", "stathera_today_overlaps",  # #295 P0-3
            "circuit_breaker_healthy",
        }
        assert expected == CRITICAL_KEYS

    def test_warning_keys_are_operational(self):
        """WARNING tier should contain operational gates."""
        from heartbeat.config import WARNING_KEYS
        expected = {"kintsugi_stuck", "kintsugi_failures", "kintsugi_memory", "cross_midnight", "version_drift", "seeder_ok", "ratelimit_ok"}
        assert expected == WARNING_KEYS
