"""Unit tests for health monitor."""

import unittest
import time
from std_msgs.msg import String


class TestHealthMonitor(unittest.TestCase):
    """Test cases for health monitor node."""

    def test_heartbeat_parsing(self):
        """Test parsing of heartbeat messages."""
        # Test message format: "node_name:data"
        test_cases = [
            ("rover_driver:alive", "rover_driver"),
            ("slam_node:map_ready", "slam_node"),
            ("nav2_bringup:planning", "nav2_bringup"),
        ]

        for heartbeat, expected_node in test_cases:
            parts = heartbeat.split(":", 1)
            node_name = parts[0].strip()
            self.assertEqual(node_name, expected_node)

    def test_timeout_detection(self):
        """Test detection of stale heartbeats."""
        heartbeat_timeout = 5.0
        current_time = time.time()

        # Fresh heartbeat
        time_since_heartbeat = current_time - (current_time - 1.0)
        self.assertLess(time_since_heartbeat, heartbeat_timeout)

        # Stale heartbeat
        stale_time = current_time - 10.0
        time_since_heartbeat = current_time - stale_time
        self.assertGreater(time_since_heartbeat, heartbeat_timeout)

    def test_health_status_generation(self):
        """Test generation of health status JSON."""
        import json

        health_data = {
            "timestamp": "2025-03-05T10:00:00",
            "uptime_s": 3600,
            "nodes": {
                "rover_driver": {
                    "status": "UP",
                    "time_since_heartbeat_s": 0.5,
                    "heartbeat_count": 100,
                    "restart_count": 0,
                    "expected": True,
                },
                "slam_node": {
                    "status": "DOWN",
                    "time_since_heartbeat_s": 6.0,
                    "heartbeat_count": 50,
                    "restart_count": 1,
                    "expected": True,
                },
            },
            "critical_down": ["slam_node"],
            "system_healthy": False,
        }

        # Should be serializable to JSON
        json_str = json.dumps(health_data)
        parsed = json.loads(json_str)

        self.assertEqual(parsed["system_healthy"], False)
        self.assertIn("slam_node", parsed["critical_down"])
        self.assertEqual(parsed["nodes"]["rover_driver"]["status"], "UP")


if __name__ == "__main__":
    unittest.main()
