"""devmemory install - 交互式为当前项目配置 MCP"""
import json
import platform
from pathlib import Path

IDES = [
    ("Kiro",           lambda root: root / ".kiro/settings/mcp.json",  "standard", False),
    ("Cursor",         lambda root: root / ".cursor/mcp.json",         "standard", False),
    ("Claude Code",    lambda root: root / ".mcp.json",                "standard", False),
    ("Windsurf",       lambda root: root / ".windsurf/mcp.json",       "standard", False),
    ("VSCode",         lambda root: root / ".vscode/mcp.json",         "standard", False),
    ("Trae",           lambda root: root / ".trae/mcp.json",           "standard", False),
    ("OpenCode",       lambda root: root / "opencode.json",            "opencode", False),
    ("Claude Desktop", lambda _: _claude_desktop_path(),               "standard", True),
]

RUNNERS = [
    ("devmemory（pip/pipx 安装）", lambda pdir: ("devmemory", ["--project-dir", pdir])),
    ("uvx devmemory（无需安装）",  lambda pdir: ("uvx", ["devmemory@latest", "--project-dir", pdir])),
]


def _claude_desktop_path() -> Path | None:
    s = platform.system()
    if s == "Darwin":
        return Path.home() / "Library/Application Support/Claude/claude_desktop_config.json"
    if s == "Windows":
        import os
        return Path(os.environ.get("APPDATA", "")) / "Claude/claude_desktop_config.json"
    if s == "Linux":
        return Path.home() / ".config/Claude/claude_desktop_config.json"
    return None


def _build_config(cmd: str, args: list[str], fmt: str) -> dict:
    if fmt == "opencode":
        return {"type": "local", "command": [cmd] + args, "enabled": True}
    return {"command": cmd, "args": args}


def _merge_config(filepath: Path, key: str, server_name: str, server_config: dict) -> bool:
    config = {}
    if filepath.exists():
        try:
            config = json.loads(filepath.read_text("utf-8"))
        except (json.JSONDecodeError, OSError):
            config = {}
    config.setdefault(key, {})
    if server_name in config[key] and config[key][server_name] == server_config:
        return False
    config[key][server_name] = server_config
    filepath.parent.mkdir(parents=True, exist_ok=True)
    filepath.write_text(json.dumps(config, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
    return True


def _choose(prompt: str, options: list[tuple], allow_all: bool = False) -> list | None:
    for i, (label, *_) in enumerate(options, 1):
        print(f"  {i}. {label}")
    if allow_all:
        print(f"  a. 全部安装")
    print()
    choice = input(f"{prompt}: ").strip().lower()
    if not choice:
        return None
    if allow_all and choice == "a":
        return list(range(len(options)))
    nums = {int(p.strip()) - 1 for p in choice.split(",") if p.strip().isdigit()}
    selected = [i for i in nums if 0 <= i < len(options)]
    return selected or None


def run_install(project_dir: str | None = None):
    pdir = str(Path(project_dir or ".").resolve()).replace("\\", "/")
    print(f"项目目录: {pdir}\n")

    # 1. 选择启动方式
    print("启动方式：")
    runner_indices = _choose("选择启动方式 [1]", RUNNERS)
    if runner_indices is None:
        runner_indices = [0]  # 默认 pip/pipx
    cmd, args = RUNNERS[runner_indices[0]][1](pdir)
    print(f"  → {cmd} {' '.join(args)}\n")

    # 2. 选择 IDE
    print("支持的 IDE：")
    valid_ides = []
    for name, path_fn, fmt, is_global in IDES:
        p = path_fn(Path(pdir))
        if p is None:
            continue
        tag = " (全局)" if is_global else ""
        valid_ides.append((f"{name}{tag}", path_fn, fmt))

    ide_indices = _choose("选择 IDE（编号，逗号分隔多选，a=全部）", valid_ides, allow_all=True)
    if ide_indices is None:
        print("未选择，退出")
        return

    # 3. 写入配置
    print()
    root = Path(pdir)
    for idx in ide_indices:
        label, path_fn, fmt = valid_ides[idx]
        filepath = path_fn(root)
        if filepath is None:
            continue
        server_config = _build_config(cmd, args, fmt)
        key = "mcp" if fmt == "opencode" else "mcpServers"
        changed = _merge_config(filepath, key, "devmemory", server_config)
        status = "✓ 已更新" if changed else "- 无变更"
        print(f"  {status}  {label}")

    print("\n安装完成")
