import pytest

from src.plugins.mcp.interfaces import MCPTool, MCPToolProvider, MCPToolResult
from src.services.mcp_tool_registry import MCPToolRegistry


def test_mcp_tool_result_accepts_legacy_data_alias() -> None:
    result = MCPToolResult(success=True, data={"ok": True})

    assert result.execution_id.startswith("mcp-")
    assert result.output == {"ok": True}
    assert result.to_dict()["output"] == {"ok": True}


def test_mcp_tool_result_keeps_explicit_output_over_data_alias() -> None:
    result = MCPToolResult(
        success=True,
        execution_id="exec-1",
        output={"new": True},
        data={"legacy": True},
    )

    assert result.execution_id == "exec-1"
    assert result.output == {"new": True}


def test_mcp_tool_result_allows_failure_without_execution_id() -> None:
    result = MCPToolResult(success=False, error="blocked")

    assert result.execution_id.startswith("mcp-")
    assert result.error == "blocked"


def test_mcp_tool_allows_legacy_missing_server_name() -> None:
    tool = MCPTool(name="legacy_tool", description="legacy", input_schema={})

    assert tool.server_name == ""


@pytest.mark.asyncio
async def test_mcp_registry_stamps_missing_server_name_from_provider() -> None:
    class LegacyProvider(MCPToolProvider):
        @property
        def name(self) -> str:
            return "legacy_provider"

        async def list_tools(self) -> list[MCPTool]:
            return [MCPTool(name="legacy_tool", description="legacy", input_schema={})]

        async def execute(self, tool_name: str, parameters: dict) -> MCPToolResult:
            return MCPToolResult(success=True, output={"tool": tool_name, "parameters": parameters})

    registry = MCPToolRegistry()

    count = await registry.register_provider(LegacyProvider())

    assert count == 1
    registered = registry.get_all_tools()[0]
    assert registered.tool.server_name == "legacy_provider"
