#!/usr/bin/env python3
"""Register frozen executable with Claude / Codex / Cursor MCP (no source tree)."""

from __future__ import annotations

import json
import platform
import re
import shutil
import subprocess
from pathlib import Path

SERVER_NAME = "bsd-watermark"
PORT = "8765"


def log(msg: str) -> None:
    print(msg, flush=True)


def mcp_entry_exe(exe: Path) -> dict:
    return {
        "command": str(exe.absolute()),
        "args": ["--mcp"],
        "env": {"BSD_WM_PORT": PORT},
    }


def merge_json_mcp(path: Path, entry: dict) -> None:
    data: dict = {}
    if path.exists():
        try:
            data = json.loads(path.read_text(encoding="utf-8"))
            if not isinstance(data, dict):
                data = {}
        except Exception:
            bak = path.with_suffix(path.suffix + ".bak")
            shutil.copy2(path, bak)
            data = {}
    servers = data.get("mcpServers")
    if not isinstance(servers, dict):
        servers = {}
    servers[SERVER_NAME] = entry
    data["mcpServers"] = servers
    path.parent.mkdir(parents=True, exist_ok=True)
    path.write_text(json.dumps(data, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")


def install_for_executable(exe: Path) -> None:
    exe = exe.absolute()
    entry = mcp_entry_exe(exe)
    log("")
    log("BSD Watermark Studio — MCP 자동 연결")
    log(f"실행 파일: {exe}")
    log("")

    # Claude CLI
    claude = shutil.which("claude")
    if claude:
        payload = {
            "type": "stdio",
            "command": entry["command"],
            "args": entry["args"],
            "env": entry["env"],
        }
        subprocess.run([claude, "mcp", "remove", "-s", "user", SERVER_NAME], capture_output=True)
        r = subprocess.run(
            [claude, "mcp", "add-json", "-s", "user", SERVER_NAME, json.dumps(payload)],
            capture_output=True,
            text=True,
        )
        if r.returncode == 0:
            log("✓ Claude Code 연결 완료")
        else:
            log("! Claude Code 연결 실패 — 앱 재설치 후 다시 「MCP 연결」실행")
    else:
        log("· Claude CLI 없음 (Claude Code 설치 후 다시 연결 가능)")

    # Claude Desktop
    home = Path.home()
    for path in (
        home / "Library" / "Application Support" / "Claude" / "claude_desktop_config.json",
        home / "AppData" / "Roaming" / "Claude" / "claude_desktop_config.json",
    ):
        if path.parent.exists():
            merge_json_mcp(path, entry)
            log(f"✓ Claude Desktop: {path}")

    # Cursor
    cursor = home / ".cursor" / "mcp.json"
    merge_json_mcp(cursor, entry)
    log(f"✓ Cursor: {cursor}")

    # Codex
    codex = home / ".codex" / "config.toml"
    if codex.parent.exists():
        def esc(p: Path) -> str:
            return str(p.absolute()).replace("\\", "\\\\")

        section = (
            f"\n[mcp_servers.{SERVER_NAME}]\n"
            f'command = "{esc(exe)}"\n'
            f'args = ["--mcp"]\n'
            f"\n[mcp_servers.{SERVER_NAME}.env]\n"
            f'BSD_WM_PORT = "{PORT}"\n'
        )
        text = codex.read_text(encoding="utf-8") if codex.exists() else ""
        text = re.sub(
            rf"\n?\[mcp_servers\.{re.escape(SERVER_NAME)}\][\s\S]*?(?=\n\[|\Z)",
            "",
            text,
        )
        text = re.sub(
            rf"\n?\[mcp_servers\.{re.escape(SERVER_NAME)}\.env\][\s\S]*?(?=\n\[|\Z)",
            "",
            text,
        )
        if codex.exists():
            shutil.copy2(codex, codex.with_suffix(".toml.bak-bsd-wm"))
        codex.write_text(text.rstrip() + "\n" + section, encoding="utf-8")
        log(f"✓ Codex(GPT): {codex}")
    else:
        log("· Codex 폴더 없음 — 나중에 Codex 설치 후 다시 연결")

    log("")
    log("완료! Claude / GPT 앱을 재시작한 뒤:")
    log('  「워터마크 스튜디오 시작해줘」')
    log("")
