"""Service tools for MCP."""

import json
from typing import Any

from mcp.types import TextContent, Tool

from ..client import Platform2StepClient

SERVICE_TOOLS: list[Tool] = [
    Tool(
        name="list_services",
        description="List services for a company, optionally filtered by category.",
        inputSchema={
            "type": "object",
            "properties": {
                "company_id": {
                    "type": "integer",
                    "description": "Company ID",
                },
                "category_id": {
                    "type": "integer",
                    "description": "Filter by category ID (optional)",
                },
                "active": {
                    "type": "boolean",
                    "description": "Filter by active/inactive 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"],
        },
    ),
    Tool(
        name="get_service",
        description="Get details of a specific service.",
        inputSchema={
            "type": "object",
            "properties": {
                "service_id": {
                    "type": "integer",
                    "description": "Service ID",
                },
            },
            "required": ["service_id"],
        },
    ),
    Tool(
        name="create_service",
        description="""Create a request to add a new service.

WARNING: This operation does NOT execute immediately.
Returns a confirmation_id that the user must approve in AgendaPro.""",
        inputSchema={
            "type": "object",
            "properties": {
                "name": {
                    "type": "string",
                    "description": "Service name",
                },
                "service_category_id": {
                    "type": "integer",
                    "description": "Category ID for the service",
                },
                "duration": {
                    "type": "integer",
                    "description": "Duration in minutes",
                },
                "company_id": {
                    "type": "integer",
                    "description": "Company ID",
                },
                "price": {
                    "type": "number",
                    "description": "Service price (optional)",
                },
                "active": {
                    "type": "boolean",
                    "description": "Whether the service is active (default true)",
                },
                "description": {
                    "type": "string",
                    "description": "Service description (optional)",
                },
            },
            "required": ["name", "service_category_id", "duration", "company_id"],
        },
    ),
    Tool(
        name="update_service",
        description="""Create a request to update an existing service.

WARNING: Requires human confirmation in AgendaPro.""",
        inputSchema={
            "type": "object",
            "properties": {
                "service_id": {
                    "type": "integer",
                    "description": "Service ID to update",
                },
                "name": {
                    "type": "string",
                    "description": "New name (optional)",
                },
                "duration": {
                    "type": "integer",
                    "description": "New duration in minutes (optional)",
                },
                "price": {
                    "type": "number",
                    "description": "New price (optional)",
                },
                "active": {
                    "type": "boolean",
                    "description": "New active status (optional)",
                },
                "description": {
                    "type": "string",
                    "description": "New description (optional)",
                },
            },
            "required": ["service_id"],
        },
    ),
    Tool(
        name="delete_service",
        description="""Create a request to delete a service.

WARNING: Requires human confirmation.
WARNING: This action is IRREVERSIBLE.""",
        inputSchema={
            "type": "object",
            "properties": {
                "service_id": {
                    "type": "integer",
                    "description": "Service ID to delete",
                },
            },
            "required": ["service_id"],
        },
    ),
]


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

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

    Returns:
        List of TextContent with the result.
    """
    if name == "list_services":
        result = await client.list_services(
            company_id=arguments["company_id"],
            category_id=arguments.get("category_id"),
            active=arguments.get("active"),
            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_service":
        result = await client.get_service(
            service_id=arguments["service_id"],
        )
        return [TextContent(type="text", text=json.dumps(result, indent=2))]

    elif name == "create_service":
        result = await client.create_service(
            name=arguments["name"],
            service_category_id=arguments["service_category_id"],
            duration=arguments["duration"],
            company_id=arguments["company_id"],
            price=arguments.get("price"),
            active=arguments.get("active", True),
            description=arguments.get("description"),
        )
        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_service":
        result = await client.update_service(
            service_id=arguments["service_id"],
            name=arguments.get("name"),
            duration=arguments.get("duration"),
            price=arguments.get("price"),
            active=arguments.get("active"),
            description=arguments.get("description"),
        )
        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 == "delete_service":
        result = await client.delete_service(
            service_id=arguments["service_id"],
        )
        return [
            TextContent(
                type="text",
                text=f"""Deletion 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 action is IRREVERSIBLE.
The user must confirm before the operation expires.
Confirm or reject: {result.get_confirm_url(client.bff_url)}""",
            )
        ]

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