"""SOAGILA MCP Tool handlers — Central registration.

MCP SDK requires a single list_tools and a single call_tool handler.
Each tool module exports get_definition() -> Tool and handle(args) -> list[TextContent].
This module collects them all and registers with the MCP Server.
"""

import logging
import time
from mcp.server import Server
from mcp.types import Tool, TextContent

from soagila.tools import remember, recall, receipt, status, annihilate, prime, inspect_tool, config_tool, backup, enterprise, crossagent, inherit, snapshot, restore

logger = logging.getLogger(__name__)

# All tool modules — each has get_definition() and handle()
_TOOL_MODULES = [
    remember,
    recall,
    receipt,
    status,
    annihilate,
    prime,
    inspect_tool,
    config_tool,
    backup,
    enterprise,
    crossagent,
    inherit,
    snapshot,
    restore,
]

# Build lookup: tool_name -> module
_TOOL_MAP: dict[str, object] = {}


def register_all_tools(app: Server) -> None:
    """Register all SOAGILA tools with a single list_tools + call_tool handler."""

    # Build the tool map
    for module in _TOOL_MODULES:
        defn = module.get_definition()
        _TOOL_MAP[defn.name] = module
        logger.debug(f"Registered tool: {defn.name}")

    @app.list_tools()
    async def handle_list_tools() -> list[Tool]:
        return [mod.get_definition() for mod in _TOOL_MODULES]

    @app.call_tool()
    async def handle_call_tool(name: str, arguments: dict) -> list[TextContent]:
        module = _TOOL_MAP.get(name)
        if module is None:
            return [TextContent(type="text", text=f'{{"error": "Unknown tool: {name}"}}')]
        start = time.monotonic()
        try:
            result = await module.handle(arguments)
            # Telemetry: track successful tool call
            try:
                from soagila.core.telemetry.collector import track
                elapsed = round((time.monotonic() - start) * 1000, 1)
                track("tool_called", "tool_usage", {
                    "tool": name, "duration_ms": elapsed, "status": "success",
                })
            except Exception:
                pass
            return result
        except Exception as e:
            # Telemetry: track failed tool call
            try:
                from soagila.core.telemetry.collector import track
                elapsed = round((time.monotonic() - start) * 1000, 1)
                track("tool_called", "tool_usage", {
                    "tool": name, "duration_ms": elapsed, "status": "error",
                })
                track("error", "error", {"tool": name, "error_type": type(e).__name__})
            except Exception:
                pass
            logger.error(f"Tool {name} error: {e}", exc_info=True)
            return [TextContent(type="text", text=f'{{"error": "Tool execution failed: {str(e)}"}}')]

    logger.info(f"Registered {len(_TOOL_MAP)} MCP tools: {list(_TOOL_MAP.keys())}")
