"""MCP tool for retrieving cached Arcade tool schemas."""

from enum import Enum
from typing import Annotated, Any

from arcade_tdk import ToolContext, tool

from cadecoder.core.logging import log
from cadecoder.execution.tool_schema_cache import ToolSchemaCache


class ToolSchemaAction(str, Enum):
    """Action for the ToolSchema tool."""

    LIST = "list"
    GET = "get"


def _get_cache() -> ToolSchemaCache:
    """Get or create the shared ToolSchemaCache instance."""
    return ToolSchemaCache()


@tool(
    name="ToolSchema",
    desc=(
        "Browse and inspect cached Arcade tool schemas. "
        "action='list': list all tools selected via Arcade_SelectTools for a thread. "
        "action='get': get full parameter schema for a specific tool."
    ),
)
def tool_schema_tool(
    context: ToolContext,
    thread_id: Annotated[str, "The thread ID to query."],
    action: Annotated[
        ToolSchemaAction, "list (browse tools) or get (full schema)."
    ] = ToolSchemaAction.LIST,
    tool_name: Annotated[str, "Tool name (required for action=get, e.g. 'Google_ReadEmail')."] = "",
) -> Annotated[dict[str, Any], "Tool schema information."]:
    """Browse or inspect cached Arcade tool schemas."""
    cache = _get_cache()

    if action == ToolSchemaAction.LIST:
        tools = cache.list_tools(thread_id)
        return {
            "tools": tools,
            "total": len(tools),
            "message": (
                f"{len(tools)} tools cached for this thread."
                if tools
                else "No tools cached for this thread. Use Arcade_SelectTools first."
            ),
        }

    elif action == ToolSchemaAction.GET:
        if not tool_name:
            return {
                "error": "tool_name is required for action='get'.",
                "hint": "Use action='list' to see available tool names.",
            }

        schema = cache.get_tool_schema(thread_id, tool_name)

        if schema is None:
            log.warning(f"Tool schema not found: {tool_name} in thread {thread_id}")
            return {
                "error": f"Tool '{tool_name}' not found in cache for this thread.",
                "hint": "Use action='list' to see available cached tools, "
                "or call Arcade_SelectTools to discover and cache new tools.",
            }

        return {
            "name": schema.name,
            "description": schema.description,
            "parameters": schema.parameters,
            "query_id": schema.query_id,
            "cached_at": schema.cached_at,
        }

    else:
        return {"error": f"Unknown action: {action}"}
