"""MCP Connector Tools for AiCippy Agents."""

from __future__ import annotations

import logging
from typing import Any

from aicippy.connectors.registry import ConnectorRegistry

logger = logging.getLogger(__name__)

class UnknownMCPToolError(ValueError):
    """Exception raised when MCP tool name format is invalid."""

    def __init__(self, name: str) -> None:
        """Initialize exception with invalid tool name."""
        super().__init__(f"Unknown MCP tool format: {name}")

class MCPTools:
    """Provides tool definitions for MCP Connectors."""

    def __init__(self, registry: ConnectorRegistry | None = None) -> None:
        """Initialize MCP tools provider.

        Args:
            registry: Optional connector registry instance. Will initialize defaults if None.

        """
        self._registry = registry or ConnectorRegistry.initialize_default_connectors()

    def get_tool_definitions(self) -> list[dict[str, Any]]:
        """Get definitions for all available MCP tools."""
        connectors = self._registry.get_available()
        definitions = []

        for conn in connectors:
            # We expose a generic 'execute' tool for each available connector
            definitions.append(
                {
                    "name": f"mcp_{conn.name}_execute",
                    "description": f"Execute a command using the {conn.name} MCP connector. {conn.description}",
                    "parameters": {
                        "type": "object",
                        "properties": {
                            "command": {
                                "type": "string",
                                "description": f"The full command to execute (e.g. for {conn.name} connector)",
                            },
                        },
                        "required": ["command"],
                    },
                },
            )

        return definitions

    async def call_tool(self, name: str, arguments: dict[str, object]) -> str:
        """Call an MCP connector tool."""
        if not name.startswith("mcp_") or not name.endswith("_execute"):
            raise UnknownMCPToolError(name)

        connector_name = name[4:-8]  # Extract name between 'mcp_' and '_execute'
        connector = self._registry.get(connector_name)

        if not connector:
            return f"Error: MCP connector '{connector_name}' is not registered or not available."

        if not connector.is_available:
            return f"Error: MCP connector '{connector_name}' is currently unavailable."

        command = str(arguments.get("command", ""))
        if not command:
            return "Error: No command provided."

        try:
            result = await connector.execute(command)
        except Exception as e:
            logger.error("mcp_tool_execution_failed", exc_info=True)
            return f"Error executing command: {e!s}"
        else:
            if result.success:
                return f"Success:\n{result.output}"
            return f"Execution Failed:\n{result.error}"
