"""albus list -- Resource discovery commands."""

from __future__ import annotations

import asyncio

import aiohttp

from core.pathways.nodes.registry import NodeTypeRegistry
from core.tools import get_tool_registry
from server.transport.cli._models import ListArgs, PathwayArgs
from server.transport.cli.pathway import _pathway_list
from stdlib.bootstrap import load_stdlib


def cmd_list(args: ListArgs) -> int:
    """List resources."""
    if args.resource == "tools":
        return _list_tools(args)
    if args.resource == "pathways":
        pw_args = PathwayArgs(action="list", host=args.host, port=args.port)
        return _pathway_list(pw_args)
    if args.resource == "skills":
        return _list_skills(args)
    if args.resource == "agents":
        return _list_agents(args)
    if args.resource == "node-types":
        return _list_node_types()
    print(f"Unknown resource: {args.resource}")
    return 2


def _list_tools(args: ListArgs) -> int:
    """List registered tools."""
    load_stdlib()

    registry = get_tool_registry()
    category = (args.category or "").strip()

    tools = sorted(registry.names())
    if category:
        tools = [t for t in tools if t.startswith(f"{category}.")]

    namespaces: dict[str, list[str]] = {}
    for tool in tools:
        ns = tool.split(".")[0] if "." in tool else "_"
        namespaces.setdefault(ns, []).append(tool)

    print(f"Tools ({len(tools)}):")
    for ns in sorted(namespaces.keys()):
        print(f"\n  {ns}:")
        for tool in namespaces[ns]:
            print(f"    {tool}")

    return 0


def _list_skills(args: ListArgs) -> int:
    """List available skills."""

    async def _list() -> int:
        url = f"http://{args.host}:{args.port}/api/v1/skills"
        try:
            async with aiohttp.ClientSession() as session, session.get(url) as resp:
                data = await resp.json()
                skills = data.get("skills", [])
                print(f"Skills ({len(skills)}):")
                for s in skills:
                    print(f"  {s.get('id')}: {s.get('description', '')[:60]}")
                return 0
        except Exception as e:
            print(f"Error: {e}")
            return 1

    return asyncio.run(_list())


def _list_agents(args: ListArgs) -> int:
    """List registered agents."""

    async def _list() -> int:
        url = f"http://{args.host}:{args.port}/api/v1/agents"
        try:
            async with aiohttp.ClientSession() as session, session.get(url) as resp:
                data = await resp.json()
                agents = data.get("agents", [])
                print(f"Agents ({len(agents)}):")
                for a in agents:
                    print(f"  {a.get('id')}: {a.get('name', '')}")
                return 0
        except Exception as e:
            print(f"Error: {e}")
            return 1

    return asyncio.run(_list())


def _list_node_types() -> int:
    """List pathway node types."""
    specs = NodeTypeRegistry.list_all()

    print(f"Node Types ({len(specs)}):")
    for spec in specs:
        print(f"  {spec.name}: {spec.description}")

    return 0
