"""E2E: HealthChecker against real node state."""

import pytest

from citadel_operator.k3s.health import HealthChecker, HealthState

pytestmark = pytest.mark.usefixtures("cluster_reachable")


class TestHealthAssessment:
    """Verify HealthChecker produces correct reports from live node data."""

    def test_running_node_reports_healthy(self, node_manager, health_checker, node_name):
        info = node_manager.get_node(node_name)
        report = health_checker.check(info)

        # A running k3d node should be HEALTHY (or WARNING if old enough)
        assert report.state in (HealthState.HEALTHY, HealthState.WARNING)
        assert report.node_name == node_name

    def test_node_conditions_match_reality(self, node_manager, health_checker, node_name):
        info = node_manager.get_node(node_name)
        report = health_checker.check(info)

        # Find the Ready condition in the report
        ready_conds = [c for c in report.conditions if c.condition_type == "Ready"]
        assert len(ready_conds) == 1
        assert ready_conds[0].healthy is True
        assert ready_conds[0].status == "True"

        # Pressure conditions should all be healthy on a running k3d node
        pressure_conds = [
            c for c in report.conditions if c.condition_type in {
                "DiskPressure", "MemoryPressure", "PIDPressure"
            }
        ]
        for cond in pressure_conds:
            assert cond.healthy is True, f"{cond.condition_type} should be healthy"

    def test_age_is_positive_and_reasonable(self, node_manager, node_name):
        info = node_manager.get_node(node_name)

        # Node should have been created some time ago
        assert info.age_hours > 0, "Node age should be positive"
        # Sanity: less than 1 year old
        assert info.age_hours < 8760, "Node age seems unreasonably large"

    def test_tiny_max_age_triggers_age_exceeded(self, node_manager, node_name):
        """A HealthChecker with max_age=0.001 hours (~4 seconds) should flag any real node."""
        checker = HealthChecker(max_age_hours=0.001)
        info = node_manager.get_node(node_name)
        report = checker.check(info)

        assert report.age_exceeded is True
        assert report.needs_termination is True

    def test_check_all_returns_report_for_every_node(self, node_manager, health_checker):
        nodes = node_manager.list_nodes()
        reports = health_checker.check_all(nodes)

        assert len(reports) == len(nodes)
        report_names = {r.node_name for r in reports}
        node_names = {n.name for n in nodes}
        assert report_names == node_names
