"""Tool execution services."""

from typing import Any, Protocol, runtime_checkable

from pydantic import BaseModel, Field

# =============================================================================
# TYPES — must be defined before re-exports from submodules
# =============================================================================


class ToolSchema(BaseModel):
    """Schema for a tool, extracted from its Python definition."""

    id: str
    name: str
    description: str
    input_schema: dict[str, Any] = Field(default_factory=dict)
    output_schema: dict[str, Any] = Field(default_factory=dict)
    category: str = "builtin"
    requires_privileged: bool = False


class ToolNotFoundError(Exception):
    """Raised when a requested tool is not found."""

    def __init__(self, tool_name: str):
        self.tool_name = tool_name
        super().__init__(f"Tool not found: {tool_name}")


# =============================================================================
# PROTOCOL - For type-safe registry wrappers
# =============================================================================


@runtime_checkable
class ToolRegistryProtocol(Protocol):
    """Protocol for accessing the tool registry.

    Implemented by ToolRegistry in core.tools and by
    wrappers in pathways.
    """

    def get(self, tool_id: str) -> Any | None:
        """Get a tool handler by ID."""
        ...

    def list_available(self, patterns: list[str]) -> list[str]:
        """List tools matching patterns."""
        ...

    def get_schemas(self, patterns: list[str]) -> list[ToolSchema]:
        """Get schemas for tools matching patterns."""
        ...


# =============================================================================
# RE-EXPORTS (after classes are defined, breaking the circular import)
# =============================================================================

from infrastructure.tools.script_tool_loader import load_tools_from_directory

__all__ = [
    "ToolNotFoundError",
    "ToolRegistryProtocol",
    "ToolSchema",
    "load_tools_from_directory",
]
