"""Host collector: /proc/meminfo parsing + disk reads (never-raise)."""
import os
import tempfile

from watchdog.collectors import host as host_mod


def test_mem_used_pct_from_meminfo():
    content = "MemTotal:       1000 kB\nMemFree:  100 kB\nMemAvailable:  250 kB\n"
    with tempfile.NamedTemporaryFile("w", suffix=".meminfo", delete=False) as f:
        f.write(content)
        path = f.name
    try:
        pct = host_mod.read_mem_used_pct(path)
        # used = (1 - 250/1000) * 100 = 75.0
        assert pct == 75.0
    finally:
        os.unlink(path)


def test_mem_used_pct_missing_file_is_none():
    assert host_mod.read_mem_used_pct("/no/such/meminfo") is None


def test_mem_used_pct_garbage_is_none():
    with tempfile.NamedTemporaryFile("w", delete=False) as f:
        f.write("totally not meminfo\n")
        path = f.name
    try:
        assert host_mod.read_mem_used_pct(path) is None
    finally:
        os.unlink(path)


def test_disk_used_pct_real_path():
    pct = host_mod.read_disk_used_pct("/")
    assert pct is None or (0.0 <= pct <= 100.0)


def test_disk_used_pct_missing_path_is_none():
    assert host_mod.read_disk_used_pct("/no/such/path/xyz") is None


def test_max_disk_used_pct_picks_worst(monkeypatch):
    monkeypatch.setattr(
        host_mod, "read_disk_used_pct",
        lambda p: {"/a": 10.0, "/b": 80.0, "/c": None}.get(p),
    )
    assert host_mod.max_disk_used_pct(["/a", "/b", "/c"]) == ("/b", 80.0)


def test_max_disk_used_pct_all_unreadable(monkeypatch):
    monkeypatch.setattr(host_mod, "read_disk_used_pct", lambda p: None)
    assert host_mod.max_disk_used_pct(["/a", "/b"]) is None
