"""Click wrappers: ticket + sprint groups — split from ctl.py."""
from __future__ import annotations

import click

from proxym.cli.tickets import (
    cmd_ticket_list, cmd_ticket_create, cmd_ticket_show, cmd_ticket_update,
    cmd_ticket_assign, cmd_ticket_comment, cmd_ticket_delete,
    cmd_sprint_list, cmd_sprint_create, cmd_sprint_show, cmd_sprint_update,
    cmd_sprint_delete, cmd_board,
)
from proxym.cli._groups._shared import make_args as _make_args, passthrough_arg


# ── Ticket group ─────────────────────────────────────────────

@click.group(name="ticket")
def ticket():
    """Manage tickets (task tracking for multi-tool workflows)."""
    pass


for _name, _handler, _help, _arg in [
    ("show",   cmd_ticket_show,   "Show ticket details.",  "ticket_id"),
    ("delete", cmd_ticket_delete, "Delete a ticket.",      "ticket_id"),
]:
    ticket.add_command(passthrough_arg(_name, _handler, _help, arg_name=_arg))


@ticket.command(name="list")
@click.option("--status", default=None, help="Filter by status (todo, in_progress, done, ...)")
@click.option("--tool", default=None, help="Filter by assigned tool (vscode, aider, claude-code, ...)")
@click.option("--sprint", default=None, help="Filter by sprint ID")
@click.option("--priority", default=None, help="Filter by priority (critical, high, medium, low)")
@click.option("--tag", default=None, help="Filter by tag")
@click.pass_context
def ticket_list(ctx: click.Context, status, tool, sprint, priority, tag):
    """List tickets."""
    args = _make_args(ctx, status=status, tool=tool, sprint=sprint, priority=priority, tag=tag)
    cmd_ticket_list(args)


@ticket.command(name="add")
@click.argument("task")
@click.option("-p", "--project", default=None, help="Project name or ID")
@click.option("-t", "--tool", default=None, help="Assign tool (aider, claude-code, ...)")
@click.option("--priority", default="medium", help="Priority: critical, high, medium, low")
@click.option("--type", "ticket_type", default="task", help="Type: task, bug, feature, refactor, test, docs")
@click.option("--sprint", default=None, help="Sprint ID")
@click.pass_context
def ticket_add(ctx: click.Context, task, project, tool, priority, ticket_type, sprint):
    """Create a ticket (minimalistic). Example: proxym ticket add 'fix the router bug'"""
    from proxym.cli._client import make_client
    args = _make_args(ctx)

    project_id = None
    if project:
        with make_client(args.proxy, args.key) as c:
            r = c.get("/dashboard/projects")
            projects = r.json() if isinstance(r.json(), list) else r.json().get("projects", [])
            for p in projects:
                if p["name"] == project or p["id"] == project:
                    project_id = p["id"]
                    break

    payload = {
        "task": task,
        "project_id": project_id,
        "tool": tool,
        "priority": priority,
        "type": ticket_type,
        "sprint_id": sprint or "",
    }
    with make_client(args.proxy, args.key) as c:
        r = c.post("/dashboard/tickets", json=payload)
        r.raise_for_status()
        t = r.json()

    click.echo(f"  \u2705 {t['id']} {t.get('title', t.get('task', '')[:50])}")


@ticket.command(name="create")
@click.option("--title", required=True, help="Ticket title (legacy — prefer 'ticket add')")
@click.option("--description", default=None, help="Description")
@click.option("--type", "type", default="task", help="Type: task, bug, feature, refactor, test, docs")
@click.option("--priority", default="medium", help="Priority: critical, high, medium, low")
@click.option("--sprint", default=None, help="Sprint ID to assign to")
@click.option("--tags", default=None, help="Comma-separated tags")
@click.option("--files", default=None, help="Comma-separated file paths")
@click.option("--hours", type=float, default=None, help="Estimated hours")
@click.pass_context
def ticket_create(ctx: click.Context, title, description, type, priority, sprint, tags, files, hours):
    """Create a new ticket (legacy — prefer 'ticket add')."""
    args = _make_args(ctx, title=title, description=description, type=type,
                      priority=priority, sprint=sprint, tags=tags, files=files, hours=hours)
    cmd_ticket_create(args)


@ticket.command(name="update")
@click.argument("ticket_id")
@click.option("--title", default=None, help="New title")
@click.option("--status", default=None, help="New status")
@click.option("--priority", default=None, help="New priority")
@click.option("--type", "type", default=None, help="New type")
@click.option("--hours", type=float, default=None, help="Actual hours spent")
@click.pass_context
def ticket_update(ctx: click.Context, ticket_id, title, status, priority, type, hours):
    """Update a ticket."""
    args = _make_args(ctx, ticket_id=ticket_id, title=title, status=status,
                      priority=priority, type=type, hours=hours)
    cmd_ticket_update(args)


@ticket.command(name="assign")
@click.argument("ticket_id")
@click.option("--tool", required=True, help="Tool name (vscode, aider, claude-code, windsurf, cursor)")
@click.option("--mode", default=None, help="Agent mode (code, architect, debug, ask)")
@click.option("--model", default=None, help="Model name or alias")
@click.pass_context
def ticket_assign(ctx: click.Context, ticket_id, tool, mode, model):
    """Assign a tool to work on a ticket."""
    args = _make_args(ctx, ticket_id=ticket_id, tool=tool, mode=mode, model=model)
    cmd_ticket_assign(args)


@ticket.command(name="comment")
@click.argument("ticket_id")
@click.option("--author", default="", help="Author (tool name or user)")
@click.option("--content", required=True, help="Comment text")
@click.pass_context
def ticket_comment(ctx: click.Context, ticket_id, author, content):
    """Add a comment to a ticket."""
    args = _make_args(ctx, ticket_id=ticket_id, author=author, content=content)
    cmd_ticket_comment(args)


@ticket.command(name="board")
@click.option("--sprint", default=None, help="Filter board by sprint ID")
@click.pass_context
def ticket_board(ctx: click.Context, sprint):
    """Show kanban board view."""
    args = _make_args(ctx, sprint=sprint)
    cmd_board(args)


# ── Sprint group ─────────────────────────────────────────────

@click.group(name="sprint")
def sprint():
    """Manage sprints."""
    pass


for _name, _handler, _help, _arg in [
    ("show",   cmd_sprint_show,   "Show sprint details and stats.",  "sprint_id"),
    ("delete", cmd_sprint_delete, "Delete a sprint.",                "sprint_id"),
]:
    sprint.add_command(passthrough_arg(_name, _handler, _help, arg_name=_arg))


@sprint.command(name="list")
@click.option("--status", default=None, help="Filter by status (planning, active, completed, cancelled)")
@click.pass_context
def sprint_list(ctx: click.Context, status):
    """List sprints."""
    args = _make_args(ctx, status=status)
    cmd_sprint_list(args)


@sprint.command(name="create")
@click.option("--name", required=True, help="Sprint name")
@click.option("--goal", default=None, help="Sprint goal")
@click.option("--start", default=None, help="Start date (YYYY-MM-DD)")
@click.option("--end", default=None, help="End date (YYYY-MM-DD)")
@click.pass_context
def sprint_create(ctx: click.Context, name, goal, start, end):
    """Create a new sprint."""
    args = _make_args(ctx, name=name, goal=goal, start=start, end=end)
    cmd_sprint_create(args)


@sprint.command(name="update")
@click.argument("sprint_id")
@click.option("--name", default=None, help="New name")
@click.option("--status", default=None, help="New status")
@click.option("--goal", default=None, help="New goal")
@click.pass_context
def sprint_update(ctx: click.Context, sprint_id, name, status, goal):
    """Update a sprint."""
    args = _make_args(ctx, sprint_id=sprint_id, name=name, status=status, goal=goal)
    cmd_sprint_update(args)


@sprint.command(name="board")
@click.option("--sprint", default=None, help="Filter board by sprint ID")
@click.pass_context
def sprint_board(ctx: click.Context, sprint):
    """Show kanban board view."""
    args = _make_args(ctx, sprint=sprint)
    cmd_board(args)
