"""Table layout checks for monitor CLI rendering.

Spec source: vectl step `ux-polish.fix-monitor-column-widths` requiring
adaptive Rich table columns without fixed width settings.
"""

from __future__ import annotations

import io
import re

from rich.console import Console
from rich.table import Table

from anima.core.schemas import AgentState, AgentStateData
from anima.shell.cli_commands import monitor_serve


def _agent(instance_id: str, state: AgentState) -> AgentStateData:
    return AgentStateData(
        instance_id=instance_id,
        persona_name="demo-model",
        trace_id=f"trace-{instance_id}",
        state=state,
        created_at="2026-03-03T12:00:00Z",
        pid=3210,
    )


def test_monitor_table_columns_do_not_use_fixed_width() -> None:
    source = monitor_serve.__file__
    assert source is not None

    with open(source, "r", encoding="utf-8") as handle:
        text = handle.read()

    assert re.search(r"table\.add_column\([^\n]*width\s*=", text) is None


def test_monitor_table_layout_renders_at_multiple_terminal_widths() -> None:
    table = Table(title="Agents")
    table.add_column("ID", style="cyan")
    table.add_column("State", style="white")
    table.add_column("Model", style="white")
    table.add_column("Created", style="white")
    table.add_column("PID", style="white")
    table.add_column("Tokens", style="white")
    table.add_row(
        "agent-running-0001",
        "running",
        "demo-model",
        "2026-03-03T12:00:00",
        "3210",
        "12345",
    )
    table.add_row(
        "agent-awaiting-0002",
        "awaiting_approval",
        "demo-model",
        "2026-03-03T12:00:00",
        "3210",
        "67890",
    )

    for terminal_width in (72, 120):
        stream = io.StringIO()
        console = Console(file=stream, width=terminal_width, force_terminal=False)
        console.print(table)
        output = stream.getvalue()

        assert "Agents" in output
        assert "running" in output
