"""CLI commands for ticket & sprint management.

Usage:
  proxym ticket list [--status STATUS] [--tool TOOL] [--sprint SPRINT_ID]
  proxym ticket create --title "..." [--type bug] [--priority high] [--sprint SPR-...]
  proxym ticket show TICKET_ID
  proxym ticket update TICKET_ID --status done
  proxym ticket assign TICKET_ID --tool aider [--mode code] [--model claude-sonnet-4-6]
  proxym ticket comment TICKET_ID --author aider --content "Fixed the bug"
  proxym ticket delete TICKET_ID
  proxym sprint list [--status active]
  proxym sprint create --name "Sprint 1" [--goal "..."] [--start 2026-03-23] [--end 2026-04-06]
  proxym sprint show SPRINT_ID
  proxym sprint update SPRINT_ID --status active
  proxym sprint delete SPRINT_ID
  proxym sprint board [--sprint SPRINT_ID]
"""

from __future__ import annotations

from proxym.cli._client import make_client, print_json, print_table


def cmd_ticket_list(args):
    """List tickets with optional filters."""
    params = {}
    if getattr(args, "status", None):
        params["status"] = args.status
    if getattr(args, "tool", None):
        params["tool"] = args.tool
    if getattr(args, "sprint", None):
        params["sprint_id"] = args.sprint
    if getattr(args, "priority", None):
        params["priority"] = args.priority
    if getattr(args, "tag", None):
        params["tag"] = args.tag

    with make_client() as c:
        r = c.get("/dashboard/tickets", params=params)
        data = r.json()

    tickets = data.get("tickets", [])
    if getattr(args, "format", "table") == "yaml":
        print_json(data)
        return

    print(f"\n  Tickets ({len(tickets)})\n")
    if not tickets:
        print("  No tickets found.\n")
        return

    print_table(
        tickets,
        ["id", "title", "status", "priority", "type", "assigned_tool"],
        [12, 35, 14, 10, 10, 20],
    )
    print()


def cmd_ticket_create(args):
    """Create a new ticket."""
    payload = {"title": args.title}
    if getattr(args, "description", None):
        payload["description"] = args.description
    if getattr(args, "type", None):
        payload["type"] = args.type
    if getattr(args, "priority", None):
        payload["priority"] = args.priority
    if getattr(args, "sprint", None):
        payload["sprint_id"] = args.sprint
    if getattr(args, "tags", None):
        payload["tags"] = [t.strip() for t in args.tags.split(",") if t.strip()]
    if getattr(args, "files", None):
        payload["files"] = [f.strip() for f in args.files.split(",") if f.strip()]
    if getattr(args, "hours", None):
        payload["estimated_hours"] = args.hours

    with make_client() as c:
        r = c.post("/dashboard/tickets", json=payload)
        data = r.json()

    print(f"  ✓ Created ticket {data['id']}: {data['title']}")
    print(f"    Status: {data['status']}  Priority: {data['priority']}  Type: {data['type']}")


def cmd_ticket_show(args):
    """Show ticket details."""
    with make_client() as c:
        r = c.get(f"/dashboard/tickets/{args.ticket_id}")
        if r.status_code == 404:
            print(f"  Ticket {args.ticket_id} not found.")
            return
        data = r.json()

    print(f"\n  {data['id']}  {data['title']}")
    print(f"  Status: {data['status']}  Priority: {data['priority']}  Type: {data['type']}")
    if data.get("description"):
        print(f"  Description: {data['description']}")
    if data.get("sprint_id"):
        print(f"  Sprint: {data['sprint_id']}")
    if data.get("assigned_tool"):
        t = data["assigned_tool"]
        print(f"  Tool: {t['tool']}" + (f" ({t['agent_mode']})" if t.get("agent_mode") else ""))
    if data.get("tags"):
        print(f"  Tags: {', '.join(data['tags'])}")
    if data.get("files"):
        print(f"  Files: {', '.join(data['files'])}")
    if data.get("comments"):
        print(f"\n  Comments ({len(data['comments'])}):")
        for c in data["comments"]:
            print(f"    [{c.get('author', '?')}] {c['content']}")
    print()


def cmd_ticket_update(args):
    """Update a ticket."""
    payload = {}
    if getattr(args, "title", None):
        payload["title"] = args.title
    if getattr(args, "status", None):
        payload["status"] = args.status
    if getattr(args, "priority", None):
        payload["priority"] = args.priority
    if getattr(args, "type", None):
        payload["type"] = args.type
    if getattr(args, "hours", None):
        payload["actual_hours"] = args.hours

    if not payload:
        print("  No updates specified.")
        return

    with make_client() as c:
        r = c.put(f"/dashboard/tickets/{args.ticket_id}", json=payload)
        if r.status_code == 404:
            print(f"  Ticket {args.ticket_id} not found.")
            return
        data = r.json()

    print(f"  ✓ Updated {data['id']}: status={data['status']} priority={data['priority']}")


def cmd_ticket_assign(args):
    """Assign a tool to a ticket."""
    payload = {"tool": args.tool}
    if getattr(args, "mode", None):
        payload["agent_mode"] = args.mode
    if getattr(args, "model", None):
        payload["model"] = args.model

    with make_client() as c:
        r = c.post(f"/dashboard/tickets/{args.ticket_id}/assign", json=payload)
        if r.status_code == 404:
            print(f"  Ticket {args.ticket_id} not found.")
            return
        data = r.json()

    ticket = data.get("ticket", {})
    print(f"  ✓ Assigned {args.tool} to {args.ticket_id} (status: {ticket.get('status')})")


def cmd_ticket_comment(args):
    """Add a comment to a ticket."""
    payload = {"content": args.content}
    if getattr(args, "author", None):
        payload["author"] = args.author

    with make_client() as c:
        r = c.post(f"/dashboard/tickets/{args.ticket_id}/comment", json=payload)
        if r.status_code == 404:
            print(f"  Ticket {args.ticket_id} not found.")
            return

    print(f"  ✓ Comment added to {args.ticket_id}")


def cmd_ticket_delete(args):
    """Delete a ticket."""
    with make_client() as c:
        r = c.delete(f"/dashboard/tickets/{args.ticket_id}")
        if r.status_code == 404:
            print(f"  Ticket {args.ticket_id} not found.")
            return

    print(f"  ✓ Deleted {args.ticket_id}")


def cmd_sprint_list(args):
    """List sprints."""
    params = {}
    if getattr(args, "status", None):
        params["status"] = args.status

    with make_client() as c:
        r = c.get("/dashboard/sprints", params=params)
        data = r.json()

    sprints = data.get("sprints", [])
    if getattr(args, "format", "table") == "yaml":
        print_json(data)
        return

    print(f"\n  Sprints ({len(sprints)})\n")
    if not sprints:
        print("  No sprints found.\n")
        return

    print_table(
        sprints,
        ["id", "name", "status", "tickets_total", "tickets_done", "progress_pct"],
        [12, 30, 12, 8, 8, 10],
    )
    print()


def cmd_sprint_create(args):
    """Create a new sprint."""
    payload = {"name": args.name}
    if getattr(args, "goal", None):
        payload["goal"] = args.goal
    if getattr(args, "start", None):
        payload["start_date"] = args.start
    if getattr(args, "end", None):
        payload["end_date"] = args.end

    with make_client() as c:
        r = c.post("/dashboard/sprints", json=payload)
        data = r.json()

    print(f"  ✓ Created sprint {data['id']}: {data['name']}")


def cmd_sprint_show(args):
    """Show sprint details."""
    with make_client() as c:
        r = c.get(f"/dashboard/sprints/{args.sprint_id}")
        if r.status_code == 404:
            print(f"  Sprint {args.sprint_id} not found.")
            return
        data = r.json()

    print(f"\n  {data['id']}  {data['name']}")
    print(f"  Status: {data['status']}  Progress: {data['progress_pct']}%")
    if data.get("goal"):
        print(f"  Goal: {data['goal']}")
    if data.get("start_date"):
        print(f"  Period: {data['start_date']} → {data.get('end_date', '...')}")
    print(f"  Tickets: {data['tickets_total']} total, {data['tickets_done']} done, {data['tickets_in_progress']} in progress")

    stats = data.get("stats", {})
    if stats.get("by_tool"):
        print(f"  Tools: {', '.join(f'{k}:{v}' for k, v in stats['by_tool'].items())}")
    print()


def cmd_sprint_update(args):
    """Update a sprint."""
    payload = {}
    if getattr(args, "name", None):
        payload["name"] = args.name
    if getattr(args, "status", None):
        payload["status"] = args.status
    if getattr(args, "goal", None):
        payload["goal"] = args.goal

    if not payload:
        print("  No updates specified.")
        return

    with make_client() as c:
        r = c.put(f"/dashboard/sprints/{args.sprint_id}", json=payload)
        if r.status_code == 404:
            print(f"  Sprint {args.sprint_id} not found.")
            return
        data = r.json()

    print(f"  ✓ Updated {data['id']}: status={data['status']}")


def cmd_sprint_delete(args):
    """Delete a sprint."""
    with make_client() as c:
        r = c.delete(f"/dashboard/sprints/{args.sprint_id}")
        if r.status_code == 404:
            print(f"  Sprint {args.sprint_id} not found.")
            return

    print(f"  ✓ Deleted {args.sprint_id}")


def cmd_board(args):
    """Show kanban board."""
    params = {}
    if getattr(args, "sprint", None):
        params["sprint_id"] = args.sprint

    with make_client() as c:
        r = c.get("/dashboard/tickets/board/view", params=params)
        board = r.json()

    statuses = ["backlog", "todo", "in_progress", "in_review", "done", "cancelled"]
    print("\n  Kanban Board\n")
    for status in statuses:
        tickets = board.get(status, [])
        if not tickets:
            continue
        print(f"  [{status.upper().replace('_', ' ')}] ({len(tickets)})")
        for t in tickets:
            tool = f" @{t['assigned_tool']['tool']}" if t.get("assigned_tool") else ""
            print(f"    {t['id']}  {t['title'][:40]}{tool}")
        print()
