"""Tests for SelfDiagnosisEngine."""

import time

from brinkhaustools.common.diagnosis import SelfDiagnosisEngine


def _make_engine():
    e = SelfDiagnosisEngine()
    e.reset_for_testing()
    return e


def test_notify_and_get():
    e = _make_engine()
    e.notify(100, "Test error", critical=True)
    msgs = e.get_messages()
    assert len(msgs) == 1
    assert msgs[0].code == 100
    assert msgs[0].critical is True


def test_no_duplicates():
    e = _make_engine()
    e.notify(100, "First")
    e.notify(100, "Second")
    assert len(e.get_messages()) == 1
    assert e.get_messages()[0].message == "First"


def test_clear():
    e = _make_engine()
    e.notify(100, "Error")
    e.clear(100)
    assert len(e.get_messages()) == 0


def test_clear_nonexistent():
    e = _make_engine()
    e.clear(999)  # Should not raise


def test_timeout():
    e = _make_engine()
    e.notify(100, "Temporary", timeout_sec=0.1)
    assert len(e.get_messages()) == 1
    time.sleep(0.2)
    assert len(e.get_messages()) == 0


def test_get_status_format():
    e = _make_engine()
    e.notify(100, "Warning", critical=False, information=True)
    status = e.get_status()
    assert status["Source name"] == "RunTimeTests"
    assert status["System Status"] is True  # no critical
    assert len(status["messages"]) == 1
    msg = status["messages"][0]
    assert msg["code"] == 100
    assert msg["messageForUI"] == "Warning"
    assert msg["information"] is True


def test_critical_sets_system_status_false():
    e = _make_engine()
    e.notify(100, "Critical!", critical=True)
    status = e.get_status()
    assert status["System Status"] is False


def test_get_name():
    e = _make_engine()
    assert e.get_name() == "RunTimeTests"
