#!/usr/bin/env python3
"""Rename legacy state-hub MCP registration to dev-hub in ~/.claude.json."""
from __future__ import annotations

import json
import shutil
from datetime import datetime, timezone
from pathlib import Path

from mcp_server.constants import LEGACY_MCP_SERVER_NAME, MCP_SERVER_NAME

CLAUDE_JSON = Path.home() / ".claude.json"


def migrate_config(config: dict) -> tuple[dict, bool]:
    servers = config.setdefault("mcpServers", {})
    if MCP_SERVER_NAME in servers:
        return config, False
    if LEGACY_MCP_SERVER_NAME not in servers:
        return config, False
    servers[MCP_SERVER_NAME] = servers.pop(LEGACY_MCP_SERVER_NAME)
    return config, True


def main() -> None:
    if not CLAUDE_JSON.exists():
        print(f"ERROR: {CLAUDE_JSON} not found.")
        raise SystemExit(1)

    config = json.loads(CLAUDE_JSON.read_text())
    migrated_config, changed = migrate_config(config)
    if not changed:
        if MCP_SERVER_NAME in config.get("mcpServers", {}):
            print(f"OK: '{MCP_SERVER_NAME}' already registered.")
        else:
            print(
                f"Nothing to migrate: neither '{LEGACY_MCP_SERVER_NAME}' nor "
                f"'{MCP_SERVER_NAME}' found in mcpServers."
            )
        return

    stamp = datetime.now(tz=timezone.utc).strftime("%Y%m%dT%H%M%SZ")
    backup = CLAUDE_JSON.with_name(f".claude.json.bak-{stamp}")
    shutil.copy2(CLAUDE_JSON, backup)
    CLAUDE_JSON.write_text(json.dumps(migrated_config, indent=2) + "\n")
    print(f"Backed up: {backup}")
    print(f"Migrated: mcpServers['{LEGACY_MCP_SERVER_NAME}'] → mcpServers['{MCP_SERVER_NAME}']")


if __name__ == "__main__":
    main()