from dataclasses import dataclass

from aitop.ui.components.memory_panel import MemoryPanel


@dataclass
class _MemoryStats:
    total: float
    used: float
    percent: float
    swap_total: float
    swap_used: float
    swap_percent: float


class _RecordingDisplay:
    width = 120

    def __init__(self) -> None:
        self.calls: list[tuple[int, int, str, int]] = []

    def safe_addstr(self, y: int, x: int, text: str, attr: int = 0) -> None:
        self.calls.append((y, x, text, attr))

    def create_bar(self, _value: float, width: int) -> tuple[str, int]:
        return ("#" * min(max(width, 0), 5), 0)


def test_memory_panel_hides_zero_detail_entries(monkeypatch) -> None:
    display = _RecordingDisplay()
    panel = MemoryPanel(display)
    memory_stats = _MemoryStats(
        total=8 * 1024**3,
        used=2 * 1024**3,
        percent=25.0,
        swap_total=0.0,
        swap_used=0.0,
        swap_percent=0.0,
    )

    monkeypatch.setattr(
        "aitop.ui.components.memory_panel.curses.color_pair", lambda _i: 0
    )
    monkeypatch.setattr("aitop.ui.components.memory_panel.curses.A_BOLD", 0)

    panel.render(
        memory_stats=memory_stats,
        memory_types={"cached": 0.0, "buffers": 1024**3},
        start_y=0,
        indent=0,
    )

    rendered_lines = [entry[2] for entry in display.calls]
    assert any("Buffers" in line for line in rendered_lines)
    assert all("Cached" not in line for line in rendered_lines)


def test_memory_panel_warns_on_high_swap_and_ram() -> None:
    panel = MemoryPanel(_RecordingDisplay())
    memory_stats = _MemoryStats(
        total=16 * 1024**3,
        used=15 * 1024**3,
        percent=93.0,
        swap_total=2 * 1024**3,
        swap_used=1.9 * 1024**3,
        swap_percent=95.0,
    )

    warning = panel.create_warning_message(threshold=90.0, memory_stats=memory_stats)

    assert "High RAM usage" in warning
    assert "High swap usage" in warning
