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

from __future__ import annotations

import click

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

# ── 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"),
    ("analyze", cmd_ticket_analyze, "Analyze if a ticket was completed correctly (shows job result, files, errors).", "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.option("--project", default=None, help="Filter by project name or ID")
@click.pass_context
def ticket_list(ctx: click.Context, status, tool, sprint, priority, tag, project):
    """List tickets."""
    from proxym.cli._client import make_client
    args = _make_args(ctx)
    params = {}
    if status:
        params["status"] = status
    if tool:
        params["tool"] = tool
    if sprint:
        params["sprint_id"] = sprint
    if priority:
        params["priority"] = priority
    if tag:
        params["tag"] = tag
    if project:
        # Resolve project name → all matching IDs
        matching_ids = []
        with make_client(args.proxy, args.key) as pc:
            pr = pc.get("/dashboard/projects")
            projects_data = pr.json() if isinstance(pr.json(), list) else pr.json().get("projects", [])
            for p in projects_data:
                if p.get("name") == project or p.get("id") == project:
                    matching_ids.append(p["id"])
        # Pass comma-separated IDs for multi-match
        params["project_id"] = ",".join(matching_ids) if matching_ids else project
    with make_client(args.proxy, args.key) as c:
        r = c.get("/dashboard/tickets", params=params)
        data = r.json()
    if print_json_if_yaml(args, data):
        return
    tickets = data.get("tickets", [])
    click.echo(f"\n  Tickets ({len(tickets)})\n")
    if not tickets:
        click.echo("  No tickets found.\n")
        return
    for t in tickets:
        status_icon = {"todo": "○", "in_progress": "◐", "done": "●", "blocked": "⊘"}.get(
            t.get("status", ""), "?"
        )
        prio = t.get("priority", "?")[:1].upper()
        task = t.get("task", t.get("title", "Untitled"))[:40]
        click.echo(f"  {status_icon} {t['id']:<12s} [{prio}] {task}")


@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_data = r.json() if isinstance(r.json(), list) else r.json().get("projects", [])
            best_match = None
            for p in projects_data:
                if p.get("name") == project or p.get("id") == project:
                    if best_match is None or p.get("created_at", 0) > best_match.get("created_at", 0):
                        best_match = p
            if best_match:
                project_id = best_match["id"]

    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')."""
    click.echo(click.style("  ⚠ Warning: 'ticket create' is deprecated. Use 'ticket add' instead.", fg="yellow"))
    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)


@ticket.command(name="dedup")
@click.option("--execute", is_flag=True, help="Actually remove duplicates (default: dry run)")
@click.pass_context
def ticket_dedup(ctx: click.Context, execute: bool):
    """Find and remove duplicate tickets (dry run by default)."""
    args = _make_args(ctx, dry_run=not execute)
    cmd_ticket_dedup(args)


@ticket.command(name="export")
@click.option("--format", "fmt", default="markdown", type=click.Choice(["markdown", "json"]), help="Export format")
@click.option("--status", default=None, help="Filter by status")
@click.option("--project", default=None, help="Filter by project name or ID")
@click.option("--output", "-o", default=None, help="Output file (default: stdout)")
@click.pass_context
def ticket_export(ctx: click.Context, fmt: str, status: str | None, project: str | None, output: str | None):
    """Export tickets to markdown or JSON."""
    from proxym.cli._client import make_client
    args = _make_args(ctx)
    c = make_client(args.proxy, args.key)

    params = {"format": fmt}
    if status:
        params["status"] = status
    if project:
        params["project_name"] = project

    r = c.get("/dashboard/tickets/export", params=params)
    data = r.json()

    if fmt == "markdown":
        content = data.get("content", "")
    else:
        import json
        content = json.dumps(data, indent=2)

    if output:
        with open(output, 'w') as f:
            f.write(content)
        click.echo(f"  Exported to {output}")
    else:
        click.echo(content)


# ── 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)
