"""Unit tests for timmy.vassal.house_health."""

from __future__ import annotations

import pytest

from timmy.vassal.house_health import (
    DiskUsage,
    MemoryUsage,
    OllamaHealth,
    SystemSnapshot,
    _probe_disk,
)

# ---------------------------------------------------------------------------
# Data model tests
# ---------------------------------------------------------------------------


def test_system_snapshot_healthy_when_no_warnings():
    snap = SystemSnapshot()
    assert snap.healthy is True


def test_system_snapshot_unhealthy_with_warnings():
    snap = SystemSnapshot(warnings=["disk 90% full"])
    assert snap.healthy is False


def test_disk_usage_defaults():
    d = DiskUsage()
    assert d.percent_used == 0.0
    assert d.path == "/"


def test_memory_usage_defaults():
    m = MemoryUsage()
    assert m.percent_used == 0.0


def test_ollama_health_defaults():
    o = OllamaHealth()
    assert o.reachable is False
    assert o.loaded_models == []


# ---------------------------------------------------------------------------
# _probe_disk — runs against real filesystem
# ---------------------------------------------------------------------------


def test_probe_disk_root():
    result = _probe_disk("/")
    assert result.total_gb > 0
    assert 0.0 <= result.percent_used <= 100.0
    assert result.free_gb >= 0


def test_probe_disk_bad_path():
    result = _probe_disk("/nonexistent_path_xyz")
    # Should not raise — returns zeroed DiskUsage
    assert result.percent_used == 0.0


# ---------------------------------------------------------------------------
# get_system_snapshot — async
# ---------------------------------------------------------------------------


@pytest.mark.asyncio
async def test_get_system_snapshot_returns_snapshot():
    from timmy.vassal.house_health import get_system_snapshot

    snap = await get_system_snapshot()
    assert isinstance(snap, SystemSnapshot)
    # Disk is always probed
    assert snap.disk.total_gb >= 0
    # Ollama is likely unreachable in test env — that's fine
    assert isinstance(snap.ollama, OllamaHealth)


@pytest.mark.asyncio
async def test_get_system_snapshot_disk_warning(monkeypatch):
    """When disk is above threshold, a warning is generated."""
    import timmy.vassal.house_health as hh

    # Patch _probe_disk to return high usage
    def _full_disk(path: str) -> DiskUsage:
        return DiskUsage(
            path=path,
            total_gb=100.0,
            used_gb=90.0,
            free_gb=10.0,
            percent_used=90.0,
        )

    monkeypatch.setattr(hh, "_probe_disk", _full_disk)

    snap = await hh.get_system_snapshot()
    assert any("disk" in w.lower() or "Disk" in w for w in snap.warnings)


# ---------------------------------------------------------------------------
# cleanup_stale_files — temp dir test
# ---------------------------------------------------------------------------


@pytest.mark.asyncio
async def test_cleanup_stale_files_missing_dir():
    """Should not raise when the target dir doesn't exist."""
    from timmy.vassal.house_health import cleanup_stale_files

    result = await cleanup_stale_files(temp_dirs=["/tmp/timmy_test_xyz_nonexistent"])
    assert result["deleted_count"] == 0
    assert result["errors"] == []
