"""Batch tools for MCP."""

import json
from typing import Any

from mcp.types import TextContent, Tool

from ..client import Platform2StepClient

BATCH_TOOLS: list[Tool] = [
    Tool(
        name="create_batch",
        description="""Create a batch of operations. This is the ONLY way to make changes (create, update, delete) to categories, services, and providers. Works for single operations or multiple (up to 50). Returns a batch_id and confirmation URL. The user must confirm in the browser before operations execute.""",
        inputSchema={
            "type": "object",
            "properties": {
                "company_id": {
                    "type": "integer",
                    "description": "Company ID",
                },
                "description": {
                    "type": "string",
                    "description": "Description of the batch for the user",
                },
                "operations": {
                    "type": "array",
                    "maxItems": 50,
                    "description": "List of operations to execute",
                    "items": {
                        "type": "object",
                        "properties": {
                            "operation": {
                                "type": "string",
                                "enum": ["create", "update", "delete"],
                                "description": "Operation type",
                            },
                            "resource": {
                                "type": "string",
                                "enum": ["category", "service", "booking", "provider"],
                                "description": "Resource type",
                            },
                            "resource_id": {
                                "type": "integer",
                                "description": "Resource ID (required for update/delete)",
                            },
                            "payload": {
                                "type": "object",
                                "description": (
                                    "REQUIRED for create/update. Omit for delete. "
                                    "For update: include ONLY the fields you want to change. "
                                    "For create: include all required fields."
                                ),
                                "properties": {
                                    "name": {"type": "string", "description": "Resource name (required for create category/service)"},
                                    "order": {"type": "integer", "description": "Display order (category)"},
                                    "service_category_id": {"type": "integer", "description": "Category ID (required for create service)"},
                                    "duration": {"type": "integer", "description": "Duration in minutes (service)"},
                                    "price": {"type": "integer", "description": "Price in cents (service)"},
                                    "active": {"type": "boolean", "description": "Active status (service)"},
                                    "description": {"type": "string", "description": "Description (service)"},
                                    "service_id": {"type": "integer", "description": "Service ID (required for create booking)"},
                                    "provider_id": {"type": "integer", "description": "Provider ID (required for create booking)"},
                                    "client_id": {"type": "integer", "description": "Client ID (required for create booking)"},
                                    "start_time": {"type": "string", "description": "Start datetime ISO 8601 (required for create booking)"},
                                    "notes": {"type": "string", "description": "Notes (booking)"},
                                    "location_id": {"type": "integer", "description": "Location ID (required for create booking and provider operations)"},
                                    "public_name": {"type": "string", "description": "Public name (provider)"},
                                    "online_booking": {"type": "boolean", "description": "Online booking enabled (provider)"},
                                    "company_id": {"type": "integer", "description": "Company ID (required for create)"},
                                },
                            },
                        },
                        "required": ["operation", "resource"],
                    },
                },
            },
            "required": ["operations", "company_id"],
        },
    ),
    Tool(
        name="get_batch_status",
        description="""Get the status of a batch of operations.

Possible statuses:
- pending: Waiting for user confirmation
- confirmed: All operations executed successfully
- rejected: User rejected the batch
- expired: Batch expired without confirmation
- partial: Some operations failed during execution""",
        inputSchema={
            "type": "object",
            "properties": {
                "batch_id": {
                    "type": "string",
                    "format": "uuid",
                    "description": "Batch ID (UUID)",
                },
            },
            "required": ["batch_id"],
        },
    ),
]


async def handle_batch_tool(
    name: str,
    arguments: dict[str, Any],
    client: Platform2StepClient,
) -> list[TextContent]:
    """Handle batch tool calls.

    Args:
        name: Tool name.
        arguments: Tool arguments.
        client: Platform2Step HTTP client.

    Returns:
        List of TextContent with the result.
    """
    if name == "create_batch":
        result = await client.create_batch(
            operations=arguments["operations"],
            company_id=arguments["company_id"],
            description=arguments.get("description"),
        )

        operations_preview = ""
        if result.operations:
            for op in result.operations:
                operations_preview += (
                    f"  {op.get('position', '?')}. {op.get('operation')} "
                    f"{op.get('resource')}"
                )
                if op.get("resource_id"):
                    operations_preview += f" (ID: {op['resource_id']})"
                operations_preview += "\n"

        return [
            TextContent(
                type="text",
                text=f"""Batch created successfully.

batch_id: {result.batch_id}
status: {result.status}
operations_count: {result.operations_count}
expires_at: {result.expires_at}
{f"description: {result.description}" if result.description else ""}

Operations:
{operations_preview if operations_preview else "(see operations in AgendaPro)"}

The user must confirm this batch in AgendaPro to execute all operations.
Confirm or reject all {result.operations_count} operations: {result.get_confirm_url(client.bff_url)}""",
            )
        ]

    elif name == "get_batch_status":
        result = await client.get_batch_status(
            batch_id=arguments["batch_id"],
        )

        status_emoji = {
            "pending": "[PENDING]",
            "confirmed": "[CONFIRMED]",
            "rejected": "[REJECTED]",
            "expired": "[EXPIRED]",
            "partial": "[PARTIAL]",
        }
        emoji = status_emoji.get(result.status, "[?]")

        operations_info = ""
        if result.operations:
            for op in result.operations:
                op_status = op.get("status", "pending")
                operations_info += (
                    f"  {op.get('position', '?')}. [{op_status.upper()}] "
                    f"{op.get('operation')} {op.get('resource')}"
                )
                if op.get("resource_id"):
                    operations_info += f" (ID: {op['resource_id']})"
                operations_info += "\n"

        text = f"""{emoji} Batch Status: {result.status}

batch_id: {result.batch_id}
operations_count: {result.operations_count}
executed_count: {result.executed_count}
failed_count: {result.failed_count}
confirmable: {result.confirmable}
expires_at: {result.expires_at}
"""

        if result.description:
            text += f"description: {result.description}\n"

        if operations_info:
            text += f"\nOperations:\n{operations_info}"

        return [TextContent(type="text", text=text)]

    raise ValueError(f"Unknown batch tool: {name}")
