"""obol agents - list, get, and score agents."""
from obol.cli._base import get_api, handle_api_error, output, table, score_bar, add_format_arg, CHAR_ACTIVE, CHAR_INACTIVE


@handle_api_error
def cmd_agents(args):
    api = get_api()
    fmt = getattr(args, "format", "text")

    sub = getattr(args, "agents_cmd", None)

    if sub == "get":
        agent = api.get_agent(args.agent_id)
        if fmt == "json":
            output(agent, fmt="json")
        else:
            print(f"Agent #{agent['id']}: {agent['name']}")
            print(f"  Platform:  {agent.get('platform', '-')}")
            print(f"  Model:     {agent.get('model', '-')}")
            print(f"  Framework: {agent.get('framework', '-')}")
            print(f"  Active:    {agent.get('active', False)}")
            if agent.get("trust_score") is not None:
                print(f"  Trust:     {score_bar(agent['trust_score'])}")
                print(f"  Tier:      {agent.get('tier', '-')}")
        return

    if sub == "score":
        score = api.get_score(args.agent_id)
        if fmt == "json":
            output(score, fmt="json")
        else:
            print(f"Trust Score for Agent #{args.agent_id}")
            print(f"  Overall:     {score_bar(score.get('overall', 0))}")
            print(f"  Reliability: {score_bar(score.get('reliability', 0))}")
            print(f"  Consistency: {score_bar(score.get('consistency', 0))}")
            print(f"  Tier:        {score.get('tier', '-')}")
            print(f"  Events:      {score.get('events_total', 0)} total "
                  f"({score.get('events_success', 0)} ok, "
                  f"{score.get('events_failed', 0)} failed)")
            print(f"  Anomalies:   {score.get('anomalies_total', 0)}")
        return

    # Default: list agents
    data = api.list_agents()
    agents = data.get("agents", [])

    if fmt == "json":
        output(data, fmt="json")
        return

    if not agents:
        print("No agents registered. Use the SDK to register one:")
        print('  obol.register("my-agent", model="claude-opus-4-5")')
        return

    rows = []
    for a in agents:
        trust = a.get("trust_score")
        trust_str = f"{trust:.0f}" if trust is not None else "-"
        rows.append([
            a["id"],
            a["name"],
            a.get("platform", "-"),
            a.get("model", "-"),
            trust_str,
            a.get("tier", "-"),
            CHAR_ACTIVE if a.get("active") else CHAR_INACTIVE,
        ])

    table(
        ["ID", "Name", "Platform", "Model", "Trust", "Tier", "Active"],
        rows,
        max_widths={1: 25, 2: 15, 3: 20},
    )


def setup_parser(subparsers):
    """Add agents subparser."""
    parser = subparsers.add_parser("agents", help="Manage agents")
    parser.set_defaults(func=cmd_agents, agents_cmd=None)
    add_format_arg(parser)

    sub = parser.add_subparsers(dest="agents_cmd")

    get_p = sub.add_parser("get", help="Get agent details")
    get_p.add_argument("agent_id", type=int, help="Agent ID")

    score_p = sub.add_parser("score", help="Get agent trust score")
    score_p.add_argument("agent_id", type=int, help="Agent ID")

    sub.add_parser("list", help="List all agents")
