"""``albus list`` — list workspace resources."""

from __future__ import annotations

import json
from typing import Annotated

import typer

from albusos.cli import app
from albusos.cli._helpers import load_workspace_or_exit, out

list_app = typer.Typer(
    name="list",
    help="List workspace resources.",
    no_args_is_help=True,
)
app.add_typer(list_app, name="list")


# ---------------------------------------------------------------------------
# Shared options
# ---------------------------------------------------------------------------

_RootOpt = Annotated[str, typer.Option("--root", "-r", help="Workspace root.")]
_JsonOpt = Annotated[bool, typer.Option("--json", "-j", help="Emit JSON.")]


# ---------------------------------------------------------------------------
# Subcommands
# ---------------------------------------------------------------------------


@list_app.command("agents")
def list_agents(root: _RootOpt = ".", json_output: _JsonOpt = False) -> None:
    """List agents discovered in the workspace."""
    ws = load_workspace_or_exit(root)
    _print_ids(sorted(ws.agents), json_output)


@list_app.command("pathways")
def list_pathways(root: _RootOpt = ".", json_output: _JsonOpt = False) -> None:
    """List pathways discovered in the workspace."""
    ws = load_workspace_or_exit(root)
    _print_ids(sorted(ws.pathways), json_output)


@list_app.command("skills")
def list_skills(root: _RootOpt = ".", json_output: _JsonOpt = False) -> None:
    """List skills discovered in the workspace."""
    ws = load_workspace_or_exit(root)
    _print_ids(sorted(ws.skills), json_output)


@list_app.command("tools")
def list_tools_cmd(
    pattern: Annotated[
        str | None,
        typer.Argument(help="Glob pattern to filter tools (e.g. 'web.*')."),
    ] = None,
    root: _RootOpt = ".",
    json_output: _JsonOpt = False,
) -> None:
    """List registered tools (auto-loads workspace first)."""
    load_workspace_or_exit(root)

    import albusos

    tools = albusos.list_tools(pattern)
    if json_output:
        out.print_json(json.dumps(tools, indent=2))
        return
    for t in tools:
        out.print(f"{t['name']:30s}  {t['description']}")
    if not tools:
        out.print("(no tools found)")


# ---------------------------------------------------------------------------
# Helpers
# ---------------------------------------------------------------------------


def _print_ids(ids: list[str], as_json: bool) -> None:
    if as_json:
        out.print_json(json.dumps(ids, indent=2))
        return
    for item in ids:
        out.print(item)
    if not ids:
        out.print("(none)")
