"""Booking tools for MCP."""

import json
from typing import Any

from mcp.types import TextContent, Tool

from ..client import Platform2StepClient

BOOKING_TOOLS: list[Tool] = [
    Tool(
        name="list_bookings",
        description="List bookings for a company within a date range.",
        inputSchema={
            "type": "object",
            "properties": {
                "company_id": {
                    "type": "integer",
                    "description": "Company ID",
                },
                "start_date": {
                    "type": "string",
                    "format": "date",
                    "description": "Start date (YYYY-MM-DD)",
                },
                "end_date": {
                    "type": "string",
                    "format": "date",
                    "description": "End date (YYYY-MM-DD)",
                },
                "provider_id": {
                    "type": "integer",
                    "description": "Filter by provider/professional ID (optional)",
                },
                "status": {
                    "type": "string",
                    "enum": ["pending", "confirmed", "cancelled"],
                    "description": "Filter by status (optional)",
                },
                "page": {
                    "type": "integer",
                    "description": "Page number (default 1)",
                },
                "per_page": {
                    "type": "integer",
                    "description": "Results per page (default 25, max 100)",
                },
            },
            "required": ["company_id", "start_date", "end_date"],
        },
    ),
    Tool(
        name="get_booking",
        description="Get details of a specific booking.",
        inputSchema={
            "type": "object",
            "properties": {
                "booking_id": {
                    "type": "integer",
                    "description": "Booking ID",
                },
            },
            "required": ["booking_id"],
        },
    ),
    Tool(
        name="create_booking",
        description="""Create a request to schedule a new booking.

WARNING: This operation does NOT execute immediately.
Returns a confirmation_id that the user must approve in AgendaPro.""",
        inputSchema={
            "type": "object",
            "properties": {
                "service_id": {
                    "type": "integer",
                    "description": "Service ID",
                },
                "provider_id": {
                    "type": "integer",
                    "description": "Provider/professional ID",
                },
                "client_id": {
                    "type": "integer",
                    "description": "Client ID",
                },
                "start": {
                    "type": "string",
                    "format": "date-time",
                    "description": "Start date and time (ISO 8601 format)",
                },
                "company_id": {
                    "type": "integer",
                    "description": "Company ID",
                },
                "notes": {
                    "type": "string",
                    "description": "Additional notes (optional)",
                },
            },
            "required": ["service_id", "provider_id", "client_id", "start", "company_id"],
        },
    ),
    Tool(
        name="cancel_booking",
        description="""Create a request to cancel a booking.

WARNING: Requires human confirmation in AgendaPro.""",
        inputSchema={
            "type": "object",
            "properties": {
                "booking_id": {
                    "type": "integer",
                    "description": "Booking ID to cancel",
                },
            },
            "required": ["booking_id"],
        },
    ),
]


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

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

    Returns:
        List of TextContent with the result.
    """
    if name == "list_bookings":
        result = await client.list_bookings(
            company_id=arguments["company_id"],
            start_date=arguments["start_date"],
            end_date=arguments["end_date"],
            provider_id=arguments.get("provider_id"),
            status=arguments.get("status"),
            page=arguments.get("page", 1),
            per_page=arguments.get("per_page", 25),
        )
        return [TextContent(type="text", text=json.dumps(result, indent=2))]

    elif name == "get_booking":
        result = await client.get_booking(
            booking_id=arguments["booking_id"],
        )
        return [TextContent(type="text", text=json.dumps(result, indent=2))]

    elif name == "create_booking":
        result = await client.create_booking(
            service_id=arguments["service_id"],
            provider_id=arguments["provider_id"],
            client_id=arguments["client_id"],
            start=arguments["start"],
            company_id=arguments["company_id"],
            notes=arguments.get("notes"),
        )
        preview_json = json.dumps(result.preview, indent=2) if result.preview else "{}"
        return [
            TextContent(
                type="text",
                text=f"""Booking request created successfully.

confirmation_id: {result.confirmation_id}
operation: {result.operation}
resource: {result.resource}
expires_at: {result.expires_at}

Preview:
{preview_json}

The user must confirm this booking before {result.expires_at}.
Confirm or reject: {result.get_confirm_url(client.bff_url)}""",
            )
        ]

    elif name == "cancel_booking":
        result = await client.cancel_booking(
            booking_id=arguments["booking_id"],
        )
        return [
            TextContent(
                type="text",
                text=f"""Cancellation request created successfully.

confirmation_id: {result.confirmation_id}
operation: {result.operation}
resource: {result.resource}
resource_id: {result.resource_id}
expires_at: {result.expires_at}

The user must confirm this cancellation before {result.expires_at}.
Confirm or reject: {result.get_confirm_url(client.bff_url)}""",
            )
        ]

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