"""Built-in NATIVE tool handler registry.

Maps system tool keys to their async handler functions.
Only tools that benefit from remote execution are registered here
(e.g., db_query, http_request, file_parse, web_crawler).

Architecture reference: Section 12.3 — Tool Execution Architecture on qRemoteX.
"""

from __future__ import annotations

import logging
from typing import Any, Callable, Coroutine

logger = logging.getLogger("qremotex.tools")

# Type alias for a NATIVE tool handler
ToolHandler = Callable[[dict[str, Any], dict[str, Any]], Coroutine[Any, Any, dict[str, Any]]]


class ToolRegistry:
    """Registry of built-in NATIVE tool handlers.

    Each handler is an async function:
        async def handler(tool_params: dict, context: dict) -> dict
    """

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

    def register(self, tool_key: str, handler: ToolHandler) -> None:
        """Register a NATIVE tool handler for the given tool key."""
        self._handlers[tool_key] = handler
        logger.debug("Registered NATIVE handler: %s", tool_key)

    def get(self, tool_key: str) -> ToolHandler | None:
        """Look up a handler by tool key."""
        return self._handlers.get(tool_key)

    def has(self, tool_key: str) -> bool:
        """Check if a handler is registered for the given tool key."""
        return tool_key in self._handlers

    @property
    def registered_keys(self) -> list[str]:
        """Return all registered tool keys."""
        return list(self._handlers.keys())

    def __len__(self) -> int:
        return len(self._handlers)


def build_default_registry() -> ToolRegistry:
    """Create a registry with all built-in system tool handlers.

    Only tools that benefit from remote execution are included.
    Pure-computation tools (calculator, text_transform) are excluded
    because they have no network/file dependency.
    """
    from qremotex.tools.db_query import handle_db_query
    from qremotex.tools.file_parse import handle_file_parse
    from qremotex.tools.http_request import handle_http_request
    from qremotex.tools.web_crawler import handle_web_crawler

    registry = ToolRegistry()
    registry.register("system.db_query", handle_db_query)
    registry.register("system.http_request", handle_http_request)
    registry.register("system.file_parse", handle_file_parse)
    registry.register("system.web_crawler", handle_web_crawler)

    logger.info("Built-in tool registry loaded: %d handlers", len(registry))
    return registry
