"""Unit tests for MCP tool namespace conflict helpers."""

from __future__ import annotations

from anima.core.tool_namespace import detect_tool_conflicts, format_conflict_warnings


def test_detect_tool_conflicts_returns_empty_for_empty_input() -> None:
    """No servers means no conflicts."""
    assert detect_tool_conflicts({}) == {}


def test_detect_tool_conflicts_returns_empty_when_tools_do_not_overlap() -> None:
    """Distinct tool names across servers produce no conflicts."""
    result = detect_tool_conflicts(
        {
            "alpha": ["tool_a", "tool_b"],
            "beta": ["tool_c"],
        }
    )

    assert result == {}


def test_detect_tool_conflicts_collects_only_shared_tool_names() -> None:
    """Only tools that appear in 2+ servers are returned."""
    result = detect_tool_conflicts(
        {
            "beta": ["shared", "beta_only"],
            "alpha": ["shared", "alpha_only"],
            "gamma": ["gamma_only"],
        }
    )

    assert result == {"shared": ["alpha", "beta"]}


def test_format_conflict_warnings_returns_none_for_no_conflicts() -> None:
    """Empty conflict payload yields no warning text."""
    assert format_conflict_warnings({}) is None


def test_format_conflict_warnings_formats_deterministic_multiline_message() -> None:
    """Warning output includes sorted tool sections with server lists."""
    warning = format_conflict_warnings(
        {
            "zeta": ["server_a", "server_b"],
            "alpha": ["server_a", "server_c"],
        }
    )

    assert warning is not None
    assert warning == (
        "Tool name conflicts detected:\n\n"
        "  - 'alpha' defined in: server_a, server_c\n"
        "  - 'zeta' defined in: server_a, server_b"
    )
