import json

import click

from strawhub.client import StrawHubClient
from strawhub.display import print_list_table, print_error, console
from strawhub.errors import StrawHubError


@click.command("list")
@click.option(
    "--kind",
    type=click.Choice(["skills", "roles", "agents", "memories", "integrations", "all"]),
    default="all",
)
@click.option("--limit", type=int, default=50, help="Max results (1-200)")
@click.option(
    "--sort",
    type=click.Choice(["updated", "downloads", "stars"]),
    default="updated",
)
@click.option("--json", "as_json", is_flag=True, default=False, help="Output as JSON")
def list_cmd(kind, limit, sort, as_json):
    """List skills, roles, agents, memories, and/or integrations."""
    with StrawHubClient() as client:
        try:
            result = {}
            if kind in ("skills", "all"):
                data = client.list_skills(limit=limit, sort=sort)
                if as_json:
                    result["skills"] = data.get("items", [])
                else:
                    items = data.get("items", [])
                    if items:
                        print_list_table(items, "skill")
                    elif kind == "skills":
                        console.print("No skills found.")

            if kind in ("roles", "all"):
                data = client.list_roles(limit=limit, sort=sort)
                if as_json:
                    result["roles"] = data.get("items", [])
                else:
                    items = data.get("items", [])
                    if items:
                        print_list_table(items, "role")
                    elif kind == "roles":
                        console.print("No roles found.")

            if kind in ("agents", "all"):
                data = client.list_agents(limit=limit, sort=sort)
                if as_json:
                    result["agents"] = data.get("items", [])
                else:
                    items = data.get("items", [])
                    if items:
                        print_list_table(items, "agent")
                    elif kind == "agents":
                        console.print("No agents found.")

            if kind in ("memories", "all"):
                data = client.list_memories(limit=limit, sort=sort)
                if as_json:
                    result["memories"] = data.get("items", [])
                else:
                    items = data.get("items", [])
                    if items:
                        print_list_table(items, "memory")
                    elif kind == "memories":
                        console.print("No memories found.")

            if kind in ("integrations", "all"):
                data = client.list_integrations(limit=limit, sort=sort)
                if as_json:
                    result["integrations"] = data.get("items", [])
                else:
                    items = data.get("items", [])
                    if items:
                        print_list_table(items, "integration")
                    elif kind == "integrations":
                        console.print("No integrations found.")

            if as_json:
                console.print_json(json.dumps(result))
        except StrawHubError as e:
            print_error(str(e))
            raise SystemExit(1)
