import importlib
import inspect
import pkgutil
import sys
from pathlib import Path
from typing import Callable, Dict, List, Tuple, Any

from mcp.server import Server
from mcp.types import Tool, TextContent

class MCPServerPluginLoader:
    """Dynamically loads MCP tools and handlers from plugins."""
    def __init__(self, plugins_dir: Path):
        self.plugins_dir = plugins_dir
        self.tools: List[Tool] = []
        self.handlers: Dict[str, Callable] = {}

    def load_plugins(self) -> Tuple[List[Tool], Dict[str, Callable]]:
        """Scans the plugins directory and loads any module exposing TOOLS and HANDLERS."""
        if not self.plugins_dir.exists():
            return [], {}
        
        # Add the parent directory to sys.path so we can import dynamically
        parent_dir = str(self.plugins_dir.parent.absolute())
        if parent_dir not in sys.path:
            sys.path.insert(0, parent_dir)
            
        package_name = f"{self.plugins_dir.parent.name}.{self.plugins_dir.name}"
        
        for _, module_name, is_pkg in pkgutil.iter_modules([str(self.plugins_dir)]):
            if is_pkg:
                continue
            full_module_name = f"{package_name}.{module_name}"
            try:
                mod = importlib.import_module(full_module_name)
                
                # Extract TOOLS if present
                if hasattr(mod, "TOOLS") and isinstance(mod.TOOLS, list):
                    for tool in mod.TOOLS:
                        self.tools.append(tool)
                        # If the tool dict contains a "handler" key, register it
                        if isinstance(tool, dict) and "handler" in tool:
                            name = tool.get("name", "")
                            if name:
                                self.handlers[name] = tool["handler"]

                # Extract HANDLERS if present (explicit handler dict takes precedence)
                if hasattr(mod, "HANDLERS") and isinstance(mod.HANDLERS, dict):
                    self.handlers.update(mod.HANDLERS)
            except Exception as e:
                import logging
                logging.getLogger(__name__).error(f"Failed to load plugin {module_name}: {e}")
                
        return self.tools, self.handlers
