"""MCP tool proxy — execute granular MCP tools from the SDK.

Reuses:
    - ``src.plugins.dynamic_registry.DynamicToolRegistry``
"""

from __future__ import annotations

import json
from typing import Any, Dict, List, Optional

from databridge_core.sdk.core.context import SDKContext
from databridge_core.sdk.core.exceptions import NotImplementedStubError, SDKError


class MCPToolProxy:
    """Proxy for executing granular MCP tools from SDK code.

    Useful when an LLM agent needs to call individual MCP tools
    rather than SDK workflows, or for advanced use cases not
    covered by the workflow abstractions.

    Reuses:
        - ``src.plugins.dynamic_registry.DynamicToolRegistry``
        - ``DynamicToolRegistry.search_tools(query)``
        - ``DynamicToolRegistry.get_tools_by_domain(domain)``

    Usage::

        proxy = MCPToolProxy(ctx=ctx)
        result = proxy.execute("profile_data", {"source_path": "data.csv"})
        tools = proxy.search("reconcile")
    """

    def __init__(self, ctx: SDKContext):
        self._ctx = ctx
        self._registry = None

    def _ensure_registry(self) -> None:
        """Lazy-load the DynamicToolRegistry."""
        if self._registry is not None:
            return
        try:
            from src.plugins.dynamic_registry import DynamicToolRegistry

            # In proxy mode, we need access to the tool functions
            # but not the MCP server itself
            self._registry = DynamicToolRegistry(mcp=None, mode="full")
        except ImportError:
            raise SDKError(
                "DynamicToolRegistry not available. "
                "Ensure src/ is on the Python path."
            )

    def execute(
        self, tool_name: str, params: Optional[Dict[str, Any]] = None
    ) -> Dict[str, Any]:
        """Execute an MCP tool by name.

        Reuse: Looks up the tool function in the registry and calls it
        directly, bypassing the MCP transport layer.

        Args:
            tool_name: Name of the MCP tool.
            params: Tool parameters.

        Returns:
            Tool result as a dict.
        """
        # REUSE: DynamicToolRegistry — look up tool function and call it
        # The actual tool functions are registered as mcp.tool() decorated
        # functions. In proxy mode, we import and call them directly.
        raise NotImplementedStubError(
            "MCPToolProxy",
            "execute",
            "Import tool function from src.plugins, call with params, "
            "parse JSON result",
        )

    def search(self, query: str) -> List[Dict[str, str]]:
        """Search available MCP tools.

        Reuse: ``DynamicToolRegistry.search_tools(query)``
        """
        raise NotImplementedStubError(
            "MCPToolProxy",
            "search",
            "src.plugins.dynamic_registry.DynamicToolRegistry.search_tools(query)",
        )

    def list_domains(self) -> List[Dict[str, Any]]:
        """List all tool domains.

        Reuse: ``DynamicToolRegistry.get_all_domains()``
        """
        raise NotImplementedStubError(
            "MCPToolProxy",
            "list_domains",
            "src.plugins.dynamic_registry.DynamicToolRegistry.get_all_domains()",
        )
