"""Convert MCP tools into LLM provider tool schemas."""

from __future__ import annotations

import re

from src.plugins.mcp.interfaces import MCPTool
from src.services.ai_providers.permissions import filter_tools_for_agent

_SAFE_TOOL_NAME = re.compile(r"[^a-zA-Z0-9_-]+")


def to_provider_tool_name(tool: MCPTool) -> str:
    """Return a provider-safe unique tool name."""

    raw_name = f"{tool.server_name}__{tool.name}"
    return _SAFE_TOOL_NAME.sub("_", raw_name)[:96]


def anthropic_tool_schema(tool: MCPTool) -> dict:
    """Convert one MCPTool to Anthropic Messages API tool schema."""

    return {
        "name": to_provider_tool_name(tool),
        "description": f"[{tool.server_name}] {tool.description}",
        "input_schema": tool.input_schema or {"type": "object", "properties": {}},
    }


def openai_tool_schema(tool: MCPTool) -> dict:
    """Convert one MCPTool to OpenAI/Ollama-compatible tool schema."""

    return {
        "type": "function",
        "function": {
            "name": to_provider_tool_name(tool),
            "description": f"[{tool.server_name}] {tool.description}",
            "parameters": tool.input_schema or {"type": "object", "properties": {}},
        },
    }


def anthropic_tools_for_agent(tools: list[MCPTool], agent_role: str) -> list[dict]:
    """Return Anthropic tool schemas filtered by agent role."""

    return [anthropic_tool_schema(tool) for tool in filter_tools_for_agent(tools, agent_role)]


def openai_tools_for_agent(tools: list[MCPTool], agent_role: str) -> list[dict]:
    """Return OpenAI/Ollama tool schemas filtered by agent role."""

    return [openai_tool_schema(tool) for tool in filter_tools_for_agent(tools, agent_role)]


def tool_by_provider_name(tools: list[MCPTool], provider_tool_name: str) -> MCPTool | None:
    """Resolve provider-safe tool name back to the original MCPTool."""

    for tool in tools:
        if to_provider_tool_name(tool) == provider_tool_name:
            return tool
    return None
