"""MCP tools — Ticket and sprint management."""
from __future__ import annotations

from typing import Any

import structlog
from fastapi import APIRouter, Query
from pydantic import BaseModel, Field

from proxym.mcp._helpers import _get_tickets

router = APIRouter()
logger = structlog.get_logger()


# ── Request models ────────────────────────────────────────

class TicketCreateRequest(BaseModel):
    title: str = Field(..., description="Ticket title")
    type: str = Field("task", description="Type: task|bug|feature|refactoring|test")
    priority: str = Field("medium", description="Priority: critical|high|medium|low")
    tags: list[str] = Field(default_factory=list, description="Tags")
    sprint_id: str = Field("", description="Sprint ID")
    description: str = Field("", description="Description")


class TicketAssignRequest(BaseModel):
    ticket_id: str = Field(..., description="Ticket ID")
    tool: str = Field(..., description="Tool: vscode|aider|claude-code|windsurf|cursor")


class SprintCreateRequest(BaseModel):
    name: str = Field(..., description="Sprint name")
    goal: str = Field("", description="Sprint goal")


# ── Endpoints ─────────────────────────────────────────────

@router.post("/tools/ticket_list")
async def tool_ticket_list(
    sprint_id: str | None = Query(None),
    status: str | None = Query(None),
    tool: str | None = Query(None),
) -> dict[str, Any]:
    """List tickets, optionally filtered by sprint, status, or assigned tool."""
    try:
        mgr = _get_tickets()
        from proxym.dashboard.tickets import TicketStatus
        st = TicketStatus(status) if status else None
        tickets = mgr.list_tickets(sprint_id=sprint_id, status=st, tool=tool)
        return {"tickets": [t.summary() for t in tickets]}
    except Exception as exc:
        logger.warning("self_mcp_ticket_list_error", error=str(exc))
        return {"tickets": [], "error": str(exc)}


@router.post("/tools/ticket_create")
async def tool_ticket_create(req: TicketCreateRequest) -> dict[str, Any]:
    """Create a new ticket in the task management system."""
    try:
        mgr = _get_tickets()
        from proxym.dashboard.tickets import Ticket, TicketType, TicketPriority
        ticket = Ticket(
            title=req.title,
            description=req.description,
            type=TicketType(req.type),
            priority=TicketPriority(req.priority),
            tags=req.tags,
            sprint_id=req.sprint_id,
        )
        created = mgr.create_ticket(ticket)
        return {"ticket": created.summary(), "message": f"Created ticket {created.id}"}
    except Exception as exc:
        return {"status": "error", "error": str(exc)}


@router.post("/tools/ticket_assign")
async def tool_ticket_assign(req: TicketAssignRequest) -> dict[str, Any]:
    """Assign a development tool to work on a ticket."""
    try:
        mgr = _get_tickets()
        from proxym.dashboard.tickets import ToolAssignment
        assignment = ToolAssignment(tool=req.tool)
        if mgr.assign_tool(req.ticket_id, assignment):
            ticket = mgr.get_ticket(req.ticket_id)
            return {"ticket": ticket.summary(), "message": f"Assigned {req.tool} to {req.ticket_id}"}
        return {"status": "error", "error": "Ticket not found"}
    except Exception as exc:
        return {"status": "error", "error": str(exc)}


@router.post("/tools/ticket_board")
async def tool_ticket_board(
    sprint_id: str | None = Query(None),
) -> dict[str, Any]:
    """Get kanban board view of tickets grouped by status."""
    try:
        mgr = _get_tickets()
        return mgr.board(sprint_id=sprint_id)
    except Exception as exc:
        return {"status": "error", "error": str(exc)}


@router.post("/tools/sprint_create")
async def tool_sprint_create(req: SprintCreateRequest) -> dict[str, Any]:
    """Create a new sprint."""
    try:
        mgr = _get_tickets()
        from proxym.dashboard.tickets import Sprint
        sprint = Sprint(name=req.name, goal=req.goal)
        created = mgr.create_sprint(sprint)
        return {"sprint": created.summary(), "message": f"Created sprint {created.id}"}
    except Exception as exc:
        return {"status": "error", "error": str(exc)}


# ── Schema fragments ─────────────────────────────────────

TOOL_SCHEMA_TICKETS: list[dict[str, Any]] = [
    {
        "type": "function",
        "function": {
            "name": "ticket_list",
            "description": "List tickets filtered by sprint/status/tool",
            "parameters": {
                "type": "object",
                "properties": {
                    "sprint_id": {"type": "string", "description": "Filter by sprint ID"},
                    "status": {"type": "string", "description": "Filter by status"},
                    "tool": {"type": "string", "description": "Filter by assigned tool"},
                },
                "required": [],
            },
        },
    },
    {
        "type": "function",
        "function": {
            "name": "ticket_create",
            "description": "Create a new task/bug/feature ticket",
            "parameters": {
                "type": "object",
                "properties": {
                    "title": {"type": "string", "description": "Ticket title"},
                    "type": {"type": "string", "enum": ["task", "bug", "feature", "refactoring", "test"], "description": "Ticket type"},
                    "priority": {"type": "string", "enum": ["critical", "high", "medium", "low"], "description": "Priority"},
                    "tags": {"type": "array", "items": {"type": "string"}, "description": "Tags"},
                    "sprint_id": {"type": "string", "description": "Sprint ID"},
                },
                "required": ["title"],
            },
        },
    },
    {
        "type": "function",
        "function": {
            "name": "ticket_assign",
            "description": "Assign a tool (aider/claude-code/vscode/windsurf/cursor) to a ticket",
            "parameters": {
                "type": "object",
                "properties": {
                    "ticket_id": {"type": "string", "description": "Ticket ID"},
                    "tool": {"type": "string", "description": "Tool name"},
                },
                "required": ["ticket_id", "tool"],
            },
        },
    },
    {
        "type": "function",
        "function": {
            "name": "ticket_board",
            "description": "Kanban board view of tickets",
            "parameters": {
                "type": "object",
                "properties": {
                    "sprint_id": {"type": "string", "description": "Filter by sprint ID"},
                },
                "required": [],
            },
        },
    },
    {
        "type": "function",
        "function": {
            "name": "sprint_create",
            "description": "Create a new sprint",
            "parameters": {
                "type": "object",
                "properties": {
                    "name": {"type": "string", "description": "Sprint name"},
                    "goal": {"type": "string", "description": "Sprint goal"},
                },
                "required": ["name"],
            },
        },
    },
]
