"""Tests for the ASCII monitor — renderer + collectors, no live stack required."""
from __future__ import annotations

from nexusos_cli.monitor import _bar, _fmt_bytes, _recent_tools, render_frame


def test_bar_bounds():
    assert _bar(0, 10, unicode=False) == "-" * 10
    assert _bar(1, 10, unicode=False) == "#" * 10
    assert _bar(0.5, 10, unicode=False).count("#") == 5


def test_fmt_bytes():
    assert _fmt_bytes(None) == "—"
    assert _fmt_bytes(512) == "512B"
    assert _fmt_bytes(2048).endswith("K")


def test_render_frame_contains_sections():
    snap = {
        "ts": "2026-08-20T12:00:00-05:00",
        "version": "0.0.0",
        "services": {
            "backend": {"running": True, "pid": 11, "url": "http://127.0.0.1:8000"},
            "memory": {"running": False, "pid": None, "url": "http://127.0.0.1:8001"},
            "frontend": {"running": False, "pid": None, "url": "http://127.0.0.1:5173"},
            "provider": {
                "provider": "ollama",
                "url": "http://127.0.0.1:11434",
                "reachable": True,
            },
        },
        "api": {
            "online": True,
            "version": "0.0.0",
            "ollama": "running",
            "memories": 3,
            "conversations": 2,
            "playbooks": 1,
            "models": 4,
            "action_tool_policy": "ask",
        },
        "host": {"cpu_pct": 12.5, "mem_used": 1_000_000_000, "mem_total": 8_000_000_000, "mem_pct": 12.5},
        "procs": {"cpu_pct": 1.0, "rss": 50_000_000, "pids": [11]},
        "toolchains": [
            {"lang": "python", "ready": True, "tool": "/usr/bin/python", "summary": "python"},
            {"lang": "rust", "ready": False, "tool": None, "summary": "rust"},
        ],
        "recent_tools": ["run_snippet", "render_preview"],
        "paths": {},
    }
    frame = render_frame(snap, width=72, unicode=False)
    assert "SERVICES" in frame
    assert "RESOURCES" in frame
    assert "DATA / TOOLS" in frame
    assert "RUN TOOLCHAINS" in frame
    assert "backend" in frame and "UP" in frame
    assert "memory" in frame and "DOWN" in frame
    assert "run_snippet" in frame
    assert "ready    python" in frame
    assert "missing  rust" in frame
    # Fixed-width box: every content line same length.
    lengths = {len(line) for line in frame.splitlines()}
    assert len(lengths) == 1


def test_recent_tools_parses_status_sentinels(tmp_path):
    log = tmp_path / "chat.log"
    log.write_text(
        "noise\n__status__tools\n__status__run_snippet\n"
        'payload {"name": "render_preview"}\n__status__remember\n',
        encoding="utf-8",
    )
    found = _recent_tools(log, limit=5)
    assert "run_snippet" in found
    assert "remember" in found
    assert "render_preview" in found
    assert "tools" not in found
