"""poolclaw-mcp setup — one-command MCP installation for Claude Code.

Usage:
    poolclaw-mcp-setup YOUR_TOKEN
    poolclaw-mcp-setup YOUR_TOKEN --server https://poolclaw-python.onrender.com

Automatically finds ~/.claude/.mcp.json, merges the poolclaw entry,
and prints a success message. No manual file editing needed.
"""
from __future__ import annotations

import json
import os
import shutil
import sys
from pathlib import Path


def _find_claude_configs() -> list[Path]:
    """Return all Claude Code config files that should receive the MCP entry.

    Claude Code reads MCPs from multiple locations depending on version:
    - ~/.claude.json           (legacy, some versions still read this)
    - ~/.claude/settings.json  (user-global settings, all sessions)

    We write to BOTH to ensure the MCP is available everywhere.
    """
    return [
        Path.home() / ".claude.json",
        Path.home() / ".claude" / "settings.json",
    ]


def _write_mcp_entry(config_path: Path, entry: dict) -> bool:
    """Merge the poolclaw MCP entry into a Claude Code config file.

    Returns True if the file was written, False on error.
    """
    existing: dict = {}
    if config_path.exists():
        try:
            existing = json.loads(config_path.read_text(encoding="utf-8"))
        except (json.JSONDecodeError, OSError):
            existing = {}

    if "mcpServers" not in existing:
        existing["mcpServers"] = {}

    existing["mcpServers"]["poolclaw"] = entry

    # Atomic write: .tmp then rename — prevents corruption on crash
    config_path.parent.mkdir(parents=True, exist_ok=True)
    tmp_path = config_path.with_suffix(".json.tmp")
    tmp_path.write_text(
        json.dumps(existing, indent=2) + "\n",
        encoding="utf-8",
    )
    tmp_path.replace(config_path)
    return True


def main() -> None:
    args = sys.argv[1:]

    if not args or args[0] in ("-h", "--help"):
        print("Usage: poolclaw-mcp-setup YOUR_TOKEN [--server URL]")
        print()
        print("Automatically configures PoolClaw MCP in Claude Code.")
        print("After running this command, restart Claude Code.")
        sys.exit(0)

    token = args[0]
    server = "https://poolclaw-python.onrender.com"
    if "--server" in args:
        idx = args.index("--server")
        if idx + 1 < len(args):
            server = args[idx + 1]

    # Resolve absolute path so Claude Code finds it regardless of its PATH
    exe_name = "poolclaw-mcp.exe" if sys.platform == "win32" else "poolclaw-mcp"
    command = shutil.which("poolclaw-mcp") or os.path.join(
        os.path.dirname(sys.executable), exe_name
    )

    mcp_entry = {
        "type": "stdio",
        "command": command,
        "env": {
            "POOLCLAW_SERVER": server,
            "POOLCLAW_TOKEN": token,
        },
    }

    # Write to ALL Claude Code config locations
    written_paths: list[str] = []
    for config_path in _find_claude_configs():
        if _write_mcp_entry(config_path, mcp_entry):
            written_paths.append(str(config_path))

    # Also write a local credentials file (~/.poolclaw/mcp.json) so the MCP
    # server can load the token even if Claude Code doesn't pass env vars.
    # This is the same pattern used by Blender MCP (reads config from disk).
    creds_dir = Path.home() / ".poolclaw"
    creds_dir.mkdir(parents=True, exist_ok=True)
    creds_path = creds_dir / "mcp.json"
    creds_path.write_text(
        json.dumps(
            {
                "token": token,
                "server": server,
                "frontend": "https://poolclaw-frontend.onrender.com",
            },
            indent=2,
        )
        + "\n",
        encoding="utf-8",
    )
    written_paths.append(str(creds_path))

    print()
    print("  PoolClaw MCP configured successfully!")
    print()
    for p in written_paths:
        print(f"  Config: {p}")
    print(f"  Server: {server}")
    print(f"  Token:  {token[:4]}{'*' * (len(token) - 4)} (stored in config, not shown in full)")
    print()
    print("  Next step: restart Claude Code, then say:")
    print('  "Create a pool to build an AI social network"')
    print()


if __name__ == "__main__":
    main()
