"""
Tool Registry - Central registry for tool classes.

Tools are automatically registered when their module is imported.
The registry maps module paths to tool classes, enabling dynamic loading.
"""

from __future__ import annotations

from typing import TYPE_CHECKING

if TYPE_CHECKING:
    from iq_sdk.tool import BaseTool

# Global registry: maps module path -> tool class
_tool_registry: dict[str, type[BaseTool]] = {}


def register_tool(cls: type[BaseTool], module_path: str) -> None:
    """
    Register a tool class in the global registry.

    Args:
        cls: Tool class to register
        module_path: Full module path (e.g. "tools.my_tool_1.my_tool_1_0")
    """
    _tool_registry[module_path] = cls
    # Also register by just module name for easier lookup
    if "." in module_path:
        _tool_registry[module_path.rsplit(".", 1)[0]] = cls


def get_tool_registry() -> dict[str, type[BaseTool]]:
    """Get the global tool registry."""
    return _tool_registry


def get_tool_class(module_path: str) -> type[BaseTool] | None:
    """
    Get a tool class by its module path.

    Args:
        module_path: Module path to look up

    Returns:
        Tool class or None if not found
    """
    return _tool_registry.get(module_path)


def find_tool_class(partial_path: str) -> type[BaseTool] | None:
    """
    Find a tool class by partial path match.

    Args:
        partial_path: Partial path to match (e.g. "my_tool_1_0")

    Returns:
        First matching tool class or None
    """
    for key, cls in _tool_registry.items():
        if partial_path in key or key.endswith(partial_path):
            return cls
    return None


def clear_tool_registry() -> None:
    """Clear the tool registry (mainly for testing)."""
    _tool_registry.clear()
