"""Booking tools for MCP."""

import json
import re
from typing import Any

from mcp.types import TextContent, Tool

from ..client import Platform2StepClient

# Pattern to match ISO 8601 datetime with Z or offset suffix
_TZ_SUFFIX_RE = re.compile(r"(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2})(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2})$")
_BOOKING_TIME_FIELDS = {"start_time", "end_time"}


def _strip_tz_from_booking(booking: dict) -> dict:
    """Strip timezone suffix from booking time fields.

    Platform API stores naive local times but returns them with a Z suffix.
    Stripping it prevents the LLM from incorrectly converting UTC → local.
    """
    for field in _BOOKING_TIME_FIELDS:
        value = booking.get(field)
        if isinstance(value, str):
            m = _TZ_SUFFIX_RE.match(value)
            if m:
                booking[field] = m.group(1)
    return booking

BOOKING_TOOLS: list[Tool] = [
    Tool(
        name="list_bookings",
        description="List bookings for a company. Times (start_time, end_time) are in the location's local time. At least one entity filter is REQUIRED: location_id, client_id, service_id, or service_provider_id. Call list_locations first if needed.",
        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)",
                },
                "location_id": {
                    "type": "integer",
                    "description": "Filter by location ID",
                },
                "client_id": {
                    "type": "integer",
                    "description": "Filter by client ID",
                },
                "service_id": {
                    "type": "integer",
                    "description": "Filter by service ID",
                },
                "service_provider_id": {
                    "type": "integer",
                    "description": "Filter by provider ID",
                },
                "status_id": {
                    "type": "integer",
                    "enum": [1, 2, 3, 5, 6, 7, 8],
                    "description": "Filter by status: 1=Reservado, 2=Confirmado, 3=Asiste (completed), 5=Cancelado (cancelled), 6=No Asiste, 7=En Espera, 8=Pendiente",
                },
                "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"],
            "additionalProperties": False,
        },
    ),
    Tool(
        name="get_booking",
        description="Get details of a specific booking. Times (start_time, end_time) are in the location's local time.",
        inputSchema={
            "type": "object",
            "properties": {
                "booking_id": {
                    "type": "integer",
                    "description": "Booking ID",
                },
            },
            "required": ["booking_id"],
            "additionalProperties": False,
        },
    ),
    # NOTE: create_booking and cancel_booking tools are disabled until
    # booking mutation routes exist in platform-2steps (currently only [:index, :show]).
]


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"],
            location_id=arguments.get("location_id"),
            client_id=arguments.get("client_id"),
            service_id=arguments.get("service_id"),
            service_provider_id=arguments.get("service_provider_id"),
            status_id=arguments.get("status_id"),
            page=arguments.get("page", 1),
            per_page=arguments.get("per_page", 25),
        )
        # Strip misleading Z suffix — API returns local times with Z
        if isinstance(result, dict) and "data" in result:
            for booking in result["data"]:
                _strip_tz_from_booking(booking)
        return [TextContent(type="text", text=json.dumps(result, indent=2))]

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

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