"""Pure-logic tests for The Bridge perf module (no sudo, hardware-tolerant).

    cd tools/bridge && python3 -m pytest tests/ -q
"""
import sys
from pathlib import Path

sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
import perf as P


def test_temp_state_thresholds():
    assert P.temp_state(None) == "unknown"
    assert P.temp_state(40) == "cool"
    assert P.temp_state(54) == "cool"
    assert P.temp_state(60) == "warm"
    assert P.temp_state(75) == "hot"
    assert P.temp_state(90) == "critical"


def test_modes_shape():
    assert set(P.MODES) == {"silent", "cool", "standard", "extreme", "normal"}
    assert P.MODES["extreme"][1] == "--extreme"
    assert P.MODES["normal"][1] == "--stop"
    assert P.MODES["silent"][1] == "--silent"


def test_detect_mode_silent_vs_cool(monkeypatch):
    # silent and cool share powersave + a capped clock; EPP disambiguates.
    def fake_reads(gov, epp, maxp):
        monkeypatch.setattr(P, "_read", lambda p, d=None:
                            {"scaling_governor": gov,
                             "energy_performance_preference": epp}.get(p.split("/")[-1], d))
        monkeypatch.setattr(P, "_read_int", lambda p, d=None:
                            maxp if p.endswith("max_perf_pct") else (0 if p.endswith("min_perf_pct") else d))
    fake_reads("powersave", "power", 55)
    assert P.detect_mode() == "silent"
    fake_reads("powersave", "balance_performance", 85)
    assert P.detect_mode() == "cool"


def test_set_mode_rejects_unknown():
    ok, msg = P.set_mode("turbo")
    assert ok is False and "unknown mode" in msg


def test_set_mode_guards_missing_script(monkeypatch):
    monkeypatch.setattr(P, "script_available", lambda: False)
    ok, msg = P.set_mode("cool")
    assert ok is False and "not deployed" in msg


def test_snapshot_shape():
    s = P.snapshot()
    for k in ("mode", "package_c", "temp_state", "cores_c", "fans_rpm",
              "freq_max_mhz", "throttle_delta", "script_available", "modes"):
        assert k in s
    assert s["mode"] in P.MODES
    assert isinstance(s["cores_c"], list)
    assert isinstance(s["script_available"], bool)


def test_detect_mode_returns_known():
    assert P.detect_mode() in P.MODES
