"""Provider (service professional) tools for MCP."""

import json
from typing import Any

from mcp.types import TextContent, Tool

from ..client import Platform2StepClient

PROVIDER_TOOLS: list[Tool] = [
    Tool(
        name="list_providers",
        description="List service professionals (providers) for a company. Returns providers with their IDs, names, locations, and availability.",
        inputSchema={
            "type": "object",
            "properties": {
                "company_id": {
                    "type": "integer",
                    "description": "Company ID to list providers for",
                },
                "location_ids": {
                    "type": "array",
                    "items": {"type": "integer"},
                    "description": "Filter by location IDs (optional)",
                },
                "active": {
                    "type": "boolean",
                    "description": "Filter by active status (optional)",
                },
                "public_name": {
                    "type": "string",
                    "description": "Filter by public name (optional)",
                },
                "service_ids": {
                    "type": "array",
                    "items": {"type": "integer"},
                    "description": "Filter by service IDs (optional)",
                },
                "page": {
                    "type": "integer",
                    "description": "Page number (default 1)",
                },
                "per_page": {
                    "type": "integer",
                    "description": "Results per page (default 25, max 100)",
                },
            },
            "required": ["company_id"],
        },
    ),
    Tool(
        name="get_provider",
        description="Get details of a specific service professional (provider).",
        inputSchema={
            "type": "object",
            "properties": {
                "provider_id": {
                    "type": "integer",
                    "description": "Provider ID",
                },
            },
            "required": ["provider_id"],
        },
    ),
    Tool(
        name="create_provider",
        description="""Create a request to add a new service professional (provider).

WARNING: This operation does NOT execute immediately.
Returns a confirmation_id that the user must approve in AgendaPro
before it expires (5-15 minutes).

The user will see a preview and can:
- Confirm: The provider will be created
- Reject: The operation is discarded""",
        inputSchema={
            "type": "object",
            "properties": {
                "company_id": {
                    "type": "integer",
                    "description": "Company ID to create the provider in",
                },
                "location_id": {
                    "type": "integer",
                    "description": "Location ID where the provider works",
                },
                "public_name": {
                    "type": "string",
                    "description": "Provider's public display name",
                    "minLength": 1,
                    "maxLength": 255,
                },
                "online_booking": {
                    "type": "boolean",
                    "description": "Whether provider accepts online bookings (optional)",
                },
                "times": {
                    "type": "array",
                    "description": "Availability schedule as list of day objects with day, start, end (optional)",
                    "items": {
                        "type": "object",
                        "properties": {
                            "day": {"type": "string"},
                            "start": {"type": "string"},
                            "end": {"type": "string"},
                        },
                    },
                },
            },
            "required": ["company_id", "location_id", "public_name"],
        },
    ),
    Tool(
        name="update_provider",
        description="""Create a request to update an existing service professional (provider).

WARNING: Requires human confirmation in AgendaPro.""",
        inputSchema={
            "type": "object",
            "properties": {
                "provider_id": {
                    "type": "integer",
                    "description": "Provider ID to update",
                },
                "public_name": {
                    "type": "string",
                    "description": "New public name (optional)",
                },
                "online_booking": {
                    "type": "boolean",
                    "description": "New online booking setting (optional)",
                },
                "times": {
                    "type": "array",
                    "description": "New availability schedule (optional)",
                    "items": {
                        "type": "object",
                        "properties": {
                            "day": {"type": "string"},
                            "start": {"type": "string"},
                            "end": {"type": "string"},
                        },
                    },
                },
            },
            "required": ["provider_id"],
        },
    ),
    Tool(
        name="deactivate_provider",
        description="""Create a request to deactivate a service professional (provider).

WARNING: Requires human confirmation.
WARNING: This action sets the provider as inactive. The provider will no longer
appear in booking interfaces or accept new appointments.""",
        inputSchema={
            "type": "object",
            "properties": {
                "provider_id": {
                    "type": "integer",
                    "description": "Provider ID to deactivate",
                },
            },
            "required": ["provider_id"],
        },
    ),
]


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

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

    Returns:
        List of TextContent with the result.
    """
    if name == "list_providers":
        result = await client.list_providers(
            company_id=arguments["company_id"],
            location_ids=arguments.get("location_ids"),
            active=arguments.get("active"),
            public_name=arguments.get("public_name"),
            service_ids=arguments.get("service_ids"),
            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_provider":
        result = await client.get_provider(
            provider_id=arguments["provider_id"],
        )
        return [TextContent(type="text", text=json.dumps(result, indent=2))]

    elif name == "create_provider":
        result = await client.create_provider(
            company_id=arguments["company_id"],
            location_id=arguments["location_id"],
            public_name=arguments["public_name"],
            online_booking=arguments.get("online_booking"),
            times=arguments.get("times"),
        )
        preview_json = json.dumps(result.preview, indent=2) if result.preview else "{}"
        return [
            TextContent(
                type="text",
                text=f"""Pending operation 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 operation before {result.expires_at}.
Confirm or reject: {result.get_confirm_url(client.bff_url)}""",
            )
        ]

    elif name == "update_provider":
        result = await client.update_provider(
            provider_id=arguments["provider_id"],
            public_name=arguments.get("public_name"),
            online_booking=arguments.get("online_booking"),
            times=arguments.get("times"),
        )
        preview_json = json.dumps(result.preview, indent=2) if result.preview else "{}"
        return [
            TextContent(
                type="text",
                text=f"""Update request created successfully.

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

Preview of changes:
{preview_json}

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

    elif name == "deactivate_provider":
        result = await client.deactivate_provider(
            provider_id=arguments["provider_id"],
        )
        return [
            TextContent(
                type="text",
                text=f"""Deactivation request created successfully.

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

WARNING: This will deactivate the provider. They will no longer appear in
booking interfaces or accept new appointments.
The user must confirm before the operation expires.
Confirm or reject: {result.get_confirm_url(client.bff_url)}""",
            )
        ]

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