"""Tests for StatusEngine and StatusSource."""

import pytest

from brinkhaustools.common.status import StatusEngine, StatusSource


class DummySource(StatusSource):
    def __init__(self, name: str, value: str):
        super().__init__(refresh_time_sec=5)
        self._name = name
        self._value = value

    def get_status(self):
        return {"value": self._value}

    def get_name(self):
        return self._name


def test_register_and_collect():
    engine = StatusEngine()
    src = DummySource("test", "hello")
    engine.register_source(src)
    # Force the elapsed time so it collects
    src._elapsed_since_refresh = 100
    result = engine.collect()
    assert "test" in result
    assert result["test"]["value"] == "hello"


def test_get_last_status_empty():
    engine = StatusEngine()
    assert engine.get_last_status() == {}


def test_no_duplicate_sources():
    engine = StatusEngine()
    src = DummySource("a", "1")
    engine.register_source(src)
    engine.register_source(src)
    assert len(engine._sources) == 1


def test_collection_respects_refresh_time():
    engine = StatusEngine()
    src = DummySource("slow", "data")
    src._refresh_time_sec = 600  # Much larger than collection interval
    engine.register_source(src)
    # First collect increments elapsed by collection_interval (5-60),
    # which is still < 600, so source should be skipped
    engine.collect()
    assert "slow" not in engine.get_last_status()


# -- StatusSource ABC compliance tests -------------------------------------


@pytest.mark.parametrize(
    "cls_factory, expected_refresh",
    [
        (lambda: __import__("brinkhaustools.common.diagnosis", fromlist=["SelfDiagnosisEngine"]).SelfDiagnosisEngine(), 60),
        (lambda: __import__("brinkhaustools.common.fleet.monitor", fromlist=["StatusMonitor"]).StatusMonitor(config_path=None, software_name="test"), 60),
        (lambda: __import__("brinkhaustools.common.heartbeat", fromlist=["HeartbeatEngine"]).HeartbeatEngine(), 60),
        (lambda: __import__("brinkhaustools.common.version", fromlist=["VersionInformation"]).VersionInformation(file_path="/nonexistent"), 3600),
    ],
    ids=["SelfDiagnosisEngine", "StatusMonitor", "HeartbeatEngine", "VersionInformation"],
)
def test_statussource_subclasses_have_refresh_time(cls_factory, expected_refresh):
    instance = cls_factory()
    assert hasattr(instance, "_refresh_time_sec")
    assert instance._refresh_time_sec == expected_refresh
    assert hasattr(instance, "_elapsed_since_refresh")
