"""Confirmation tools for MCP.

SECURITY NOTE: This module only provides status checking tools.
The MCP must NOT have the ability to confirm or reject operations.
Confirmation must happen through the AgendaPro frontend with user authentication.
"""

from typing import Any

from mcp.types import TextContent, Tool

from ..client import Platform2StepClient

CONFIRMATION_TOOLS: list[Tool] = [
    Tool(
        name="get_confirmation_status",
        description="""Check the status of a pending operation.

Possible statuses:
- pending: Waiting for user confirmation
- confirmed: User confirmed, operation executed successfully
- rejected: User rejected the operation
- expired: Operation expired without confirmation
- failed: Error executing against Platform API

Use this to check if the user has confirmed an operation you created.""",
        inputSchema={
            "type": "object",
            "properties": {
                "confirmation_id": {
                    "type": "string",
                    "format": "uuid",
                    "description": "Confirmation ID returned when creating the operation",
                },
            },
            "required": ["confirmation_id"],
        },
    ),
]


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

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

    Returns:
        List of TextContent with the result.
    """
    if name == "get_confirmation_status":
        result = await client.get_confirmation_status(
            confirmation_id=arguments["confirmation_id"],
        )

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

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

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

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

        if result.status == "pending":
            text += f"expires_at: {result.expires_at}\n"
            text += f"confirmable: {result.confirmable}\n"
            if not result.confirmable:
                text += "\nNote: This operation can no longer be confirmed (expired or already processed).\n"

        if result.preview:
            import json

            text += f"\nPreview:\n{json.dumps(result.preview, indent=2)}\n"

        if result.result:
            import json

            text += f"\nResult from Platform API:\n{json.dumps(result.result, indent=2)}\n"

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

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