import importlib
import inspect
import pkgutil
from pathlib import Path
from typing import Dict, Optional, Type

from core.tool import ToolBase


# Registry that maps tool names to their classes
_tool_registry: Dict[str, Type[ToolBase]] = {}


def _iter_tool_classes():
    package_dir = Path(__file__).parent
    for module_info in pkgutil.walk_packages([str(package_dir)], prefix="tools."):
        if module_info.name.endswith(".registry") or module_info.name.endswith(".contract_tools"):
            continue
        module = importlib.import_module(module_info.name)
        for _, obj in inspect.getmembers(module, inspect.isclass):
            if getattr(obj, "_is_tool", False) and issubclass(obj, ToolBase):
                yield obj


def build_registry(force_refresh: bool = False) -> Dict[str, Type[ToolBase]]:
    if _tool_registry and not force_refresh:
        return _tool_registry

    _tool_registry.clear()
    for cls in _iter_tool_classes():
        _tool_registry[cls._name] = cls
    return _tool_registry


def get_tool(name: str) -> Optional[Type[ToolBase]]:
    return _tool_registry.get(name)


def available_tools() -> Dict[str, str]:
    return {name: cls._description for name, cls in _tool_registry.items()}


# Build registry on import
build_registry()

if __name__ == "__main__":
    for tool_name, tool_desc in available_tools().items():
        print(f"Tool: {tool_name}, Description: {tool_desc}")