"""Tests for dev-hub MCP registration helpers and config migration."""
from __future__ import annotations

import json

import mcp_server.server as server
from mcp_server.constants import LEGACY_MCP_SERVER_NAME, MCP_SERVER_NAME
from scripts.mcp_registration import (
    mcp_server_registered,
    resolve_mcp_server_name,
)
from scripts.migrate_mcp_config import migrate_config


def test_mcp_server_name_is_dev_hub() -> None:
    assert server.mcp.name == MCP_SERVER_NAME


def test_mcp_server_registered_accepts_dev_hub() -> None:
    config = {"mcpServers": {MCP_SERVER_NAME: {"type": "sse"}}}
    assert mcp_server_registered(config) is True


def test_mcp_server_registered_accepts_legacy_state_hub() -> None:
    config = {"mcpServers": {LEGACY_MCP_SERVER_NAME: {"type": "sse"}}}
    assert mcp_server_registered(config) is True


def test_resolve_mcp_server_name_prefers_dev_hub() -> None:
    config = {
        "mcpServers": {
            MCP_SERVER_NAME: {"type": "sse"},
            LEGACY_MCP_SERVER_NAME: {"type": "sse"},
        }
    }
    assert resolve_mcp_server_name(config) == MCP_SERVER_NAME


def test_migrate_config_renames_legacy_entry() -> None:
    legacy_entry = {"type": "sse", "url": "http://127.0.0.1:8001/sse"}
    config = {"mcpServers": {LEGACY_MCP_SERVER_NAME: legacy_entry}}
    migrated, changed = migrate_config(config)
    assert changed is True
    assert LEGACY_MCP_SERVER_NAME not in migrated["mcpServers"]
    assert migrated["mcpServers"][MCP_SERVER_NAME] == legacy_entry


def test_migrate_config_noop_when_dev_hub_present() -> None:
    config = {"mcpServers": {MCP_SERVER_NAME: {"type": "sse"}}}
    migrated, changed = migrate_config(config)
    assert changed is False
    assert migrated is config


def test_migrate_config_noop_when_neither_present() -> None:
    config = {"mcpServers": {"ops-bridge": {"type": "sse"}}}
    migrated, changed = migrate_config(config)
    assert changed is False
    assert migrated is config


def test_migrate_config_preserves_other_servers(tmp_path) -> None:
    claude_json = tmp_path / ".claude.json"
    config = {
        "mcpServers": {
            LEGACY_MCP_SERVER_NAME: {"type": "sse"},
            "ops-bridge": {"type": "sse", "url": "http://127.0.0.1:8002/sse"},
        }
    }
    claude_json.write_text(json.dumps(config))
    migrated, changed = migrate_config(json.loads(claude_json.read_text()))
    assert changed is True
    assert "ops-bridge" in migrated["mcpServers"]
    assert migrated["mcpServers"]["ops-bridge"]["url"] == "http://127.0.0.1:8002/sse"