"""Command utilities for listing items."""

from proxym.cli._client import make_client, print_json_if_yaml, print_table


def cmd_list_items(args, endpoint: str, item_name: str, columns: list[str], widths: list[int], empty_message: str):
    """Generic command to list items from an API endpoint."""
    with make_client() as c:
        r = c.get(endpoint)
        data = r.json()

    items = data.get(item_name, [])
    if print_json_if_yaml(args, data):
        return

    print(f"\n  {item_name.title()} ({len(items)})\n")
    if not items:
        print(f"  {empty_message}\n")
        return

    print_table(items, columns, widths)
    print()


def cmd_sessions_list(args):
    """List active agent sessions."""
    cmd_list_items(
        args,
        "/v1/sessions",
        "sessions",
        ["id", "project_id", "age_seconds", "idle_seconds", "history_length"],
        [20, 25, 12, 12, 14],
        "No active sessions."
    )


def cmd_mcp_servers(args):
    """List registered MCP servers."""
    cmd_list_items(
        args,
        "/v1/mcp/servers",
        "servers",
        ["name", "url", "transport", "enabled", "priority"],
        [20, 40, 10, 8, 8],
        "No MCP servers registered."
    )
