"""Tool registry — manages tool registration, lookup, and definition export."""

from __future__ import annotations

from typing import Any

from tsumugi.providers.base import ToolDefinition
from tsumugi.tools.base import BaseTool, ToolSpec


class ToolRegistry:
    """Central registry for all tools."""

    def __init__(self) -> None:
        self._tools: dict[str, BaseTool] = {}

    def register(self, tool: BaseTool) -> None:
        """Register a tool instance."""
        spec = tool.spec()
        self._tools[spec.name] = tool

    def get(self, name: str) -> BaseTool | None:
        """Look up a tool by name."""
        return self._tools.get(name)

    def get_spec(self, name: str) -> ToolSpec | None:
        """Get the spec of a registered tool."""
        tool = self._tools.get(name)
        return tool.spec() if tool else None

    def all_specs(self) -> list[ToolSpec]:
        """Return specs for all registered tools."""
        return [t.spec() for t in self._tools.values()]

    def to_definitions(self) -> list[ToolDefinition]:
        """Export tool definitions for LLM provider consumption."""
        defs = []
        for tool in self._tools.values():
            spec = tool.spec()
            defs.append(
                ToolDefinition(
                    name=spec.name,
                    description=spec.description,
                    parameters=spec.parameters,
                )
            )
        return defs

    @property
    def names(self) -> list[str]:
        return list(self._tools.keys())


def create_default_registry() -> ToolRegistry:
    """Create a registry with all built-in tools."""
    from tsumugi.tools.read_file import ReadFileTool
    from tsumugi.tools.write_file import WriteFileTool
    from tsumugi.tools.edit_file import EditFileTool
    from tsumugi.tools.shell import ShellTool
    from tsumugi.tools.glob_search import GlobSearchTool
    from tsumugi.tools.grep_search import GrepSearchTool
    from tsumugi.tools.list_directory import ListDirectoryTool
    from tsumugi.tools.web_fetch import WebFetchTool

    registry = ToolRegistry()
    registry.register(ReadFileTool())
    registry.register(WriteFileTool())
    registry.register(EditFileTool())
    registry.register(ShellTool())
    registry.register(GlobSearchTool())
    registry.register(GrepSearchTool())
    registry.register(ListDirectoryTool())
    registry.register(WebFetchTool())
    return registry
