"""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_gpu_manager_mode_parse_and_cache(monkeypatch):
    import types
    calls = {"n": 0}

    def fake_run(cmd, **kw):
        calls["n"] += 1
        return types.SimpleNamespace(returncode=0, stdout="hybrid\n", stderr="")

    monkeypatch.setattr(P.subprocess, "run", fake_run)
    P._GPU_MODE_CACHE.update(val=None, ts=0.0, done=False)
    assert P.gpu_manager_mode() == "hybrid"
    assert P.gpu_manager_mode() == "hybrid"   # served from cache
    assert calls["n"] == 1                     # only one subprocess spawn


def test_gpu_manager_mode_absent(monkeypatch):
    def boom(cmd, **kw):
        raise FileNotFoundError("envycontrol")

    monkeypatch.setattr(P.subprocess, "run", boom)
    P._GPU_MODE_CACHE.update(val=None, ts=0.0, done=False)
    assert P.gpu_manager_mode() is None        # feature just no-ops


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",
              "dgpu", "gpu_manager", "thermald"):
        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
