"""Click wrappers: tools group — tool registry + job queue CLI."""
from __future__ import annotations

import click

from proxym.cli._groups._shared import (
    make_args as _make_args,
    api_json_cmd,
    api_json_arg_cmd,
)
from proxym.cli._client import print_json_if_yaml


@click.group(name="tools")
def tools():
    """Manage AI development tools and job queue."""
    pass


@tools.command(name="list")
@click.option("--category", default=None, help="Filter: ide, agent_cli, browser")
@click.option("--available", is_flag=True, help="Only show tools with an available host or docker-backed instance")
@click.pass_context
def tools_list(ctx: click.Context, category: str | None, available: bool):
    """List registered tools."""
    from proxym.cli._client import make_client
    args = _make_args(ctx)
    c = make_client(args.proxy, args.key)
    params = {}
    if category:
        params["category"] = category
    if available:
        params["available_only"] = "true"
    r = c.get("/dashboard/tools/", params=params)
    data = r.json()
    if print_json_if_yaml(args, data):
        return
    for t in data.get("tools", []):
        icon = "\033[32m\u2713\033[0m" if t.get("available") else "\033[31m\u2717\033[0m"
        click.echo(f"  {icon}  {t['name']:<15s}  {t.get('category', ''):<10s}  {t.get('description', '')}")


@tools.command(name="dispatch")
@click.option("--ticket", required=True, help="Ticket ID")
@click.option("--tool", required=True, help="Tool name (aider, claude-code, ...)")
@click.option("--mode", default="", help="Agent mode (code, architect, debug, ask)")
@click.option("--model", default="", help="Model alias or full name")
@click.option("--project-dir", default="", help="Project directory")
@click.pass_context
def tools_dispatch(ctx: click.Context, ticket: str, tool: str, mode: str, model: str, project_dir: str):
    """Dispatch a tool to work on a ticket."""
    from proxym.cli._client import make_client, print_json
    args = _make_args(ctx)
    c = make_client(args.proxy, args.key)
    r = c.post("/dashboard/tools/dispatch", json={
        "ticket_id": ticket, "tool": tool, "mode": mode, "model": model, "project_dir": project_dir,
    })
    print_json(r.json())


@tools.command(name="queue")
@click.pass_context
def tools_queue(ctx: click.Context):
    """Show job queue status."""
    from proxym.cli._client import make_client
    args = _make_args(ctx)
    c = make_client(args.proxy, args.key)
    r = c.get("/dashboard/tools/queue")
    data = r.json()
    if print_json_if_yaml(args, data):
        return
    click.echo(f"  Queue: {data.get('queue_size', 0)} pending  |  Total: {data.get('total_jobs', 0)}")
    click.echo(f"  Executor: {'running' if data.get('running') else 'stopped'}")
    for s, count in data.get("by_status", {}).items():
        click.echo(f"    {s}: {count}")


@tools.command(name="jobs")
@click.option("--status", default=None, help="Filter: queued, running, done, failed, cancelled")
@click.option("--limit", default=20, type=int, help="Max jobs to show")
@click.pass_context
def tools_jobs(ctx: click.Context, status: str | None, limit: int):
    """List jobs."""
    from proxym.cli._client import make_client
    args = _make_args(ctx)
    c = make_client(args.proxy, args.key)
    params = {"limit": limit}
    if status:
        params["status"] = status
    r = c.get("/dashboard/tools/queue/jobs", params=params)
    data = r.json()
    if print_json_if_yaml(args, data):
        return
    for j in data.get("jobs", []):
        st = j.get("status", "?")
        click.echo(f"  {j['id']}  {j.get('ticket_id', ''):<12s}  {j.get('tool', ''):<14s}  {st}")


@tools.command(name="set-model")
@click.argument("tool_name")
@click.argument("model")
@click.pass_context
def tools_set_model(ctx: click.Context, tool_name: str, model: str):
    """Set the default LLM model for a tool.

    \b
    Examples:
      proxym tools set-model aider balanced
      proxym tools set-model claude-code premium
      proxym tools set-model roo-code openrouter/anthropic/claude-sonnet-4.6
    """
    from proxym.cli._client import make_client, print_json
    args = _make_args(ctx)
    c = make_client(args.proxy, args.key)
    r = c.put(f"/dashboard/tools/{tool_name}", json={"default_model": model})
    if r.status_code == 404:
        click.echo(f"  Tool '{tool_name}' not found.")
        return
    data = r.json()
    click.echo(f"  ✓ {tool_name} → default_model = {data.get('default_model', model)}")


# ── Simple API passthrough commands ──────────────────────────

for _name, _method, _path_tpl, _help in [
    ("show",   "get",  "/dashboard/tools/{tool_name}",              "Show details for a specific tool."),
    ("job",    "get",  "/dashboard/tools/queue/jobs/{job_id}",      "Show details for a specific job."),
    ("cancel", "post", "/dashboard/tools/queue/jobs/{job_id}/cancel", "Cancel a queued job."),
    ("retry",  "post", "/dashboard/tools/queue/jobs/{job_id}/retry",  "Retry a failed or cancelled job."),
    ("repair", "post", "/dashboard/tools/queue/jobs/{job_id}/repair", "Run diagnosis for a failed job and print suggestions."),
]:
    _arg = "tool_name" if "tool_name" in _path_tpl else "job_id"
    tools.add_command(api_json_arg_cmd(_name, _method, _path_tpl, _help, arg_name=_arg))

for _name, _method, _path, _help in [
    ("start", "post", "/dashboard/tools/queue/start", "Start the background executor."),
    ("stop",  "post", "/dashboard/tools/queue/stop",  "Stop the background executor."),
]:
    tools.add_command(api_json_cmd(_name, _method, _path, _help))
