#!/usr/bin/env python3
"""
Patch ~/.claude.json to add the cwd field to the dev-hub MCP entry.

claude mcp add-json silently drops the cwd field. Run this script after
any claude mcp add-json call to restore it.

Usage: python3 scripts/patch_mcp_cwd.py
"""
import json
import os
from pathlib import Path

from mcp_server.constants import LEGACY_MCP_SERVER_NAME, MCP_SERVER_NAME
from scripts.mcp_registration import load_claude_json, resolve_mcp_server_name

CLAUDE_JSON = Path.home() / ".claude.json"
STATE_HUB_DIR = Path(__file__).resolve().parent.parent


def main() -> None:
    config = load_claude_json(CLAUDE_JSON)
    if config is None:
        print(f"ERROR: {CLAUDE_JSON} not found. Run 'claude mcp add-json' first.")
        raise SystemExit(1)

    servers = config.setdefault("mcpServers", {})
    server_name = resolve_mcp_server_name(config)
    if server_name is None:
        print(
            f"ERROR: neither '{MCP_SERVER_NAME}' nor '{LEGACY_MCP_SERVER_NAME}' "
            f"found in ~/.claude.json. Run 'claude mcp add-json' first."
        )
        raise SystemExit(1)

    if server_name == LEGACY_MCP_SERVER_NAME:
        print(
            f"NOTE: patching legacy '{LEGACY_MCP_SERVER_NAME}' entry. "
            "Run scripts/migrate_mcp_config.py to rename to dev-hub."
        )

    entry = servers[server_name]
    cwd_str = str(STATE_HUB_DIR)

    if entry.get("cwd") == cwd_str:
        print(f"OK: cwd already set to {cwd_str}")
        return

    entry["cwd"] = cwd_str
    CLAUDE_JSON.write_text(json.dumps(config, indent=2) + "\n")
    print(f"Patched: ~/.claude.json {server_name}.cwd = {cwd_str}")


if __name__ == "__main__":
    main()