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

Usage:
    poolclaw-mcp-setup YOUR_TOKEN
    poolclaw-mcp-setup YOUR_TOKEN --server https://poolclaw.io

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_config() -> Path:
    """Return the path to Claude Code's main config file (~/.claude.json)."""
    return Path.home() / ".claude.json"


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]

    config_path = _find_claude_config()

    # Read existing config or start fresh
    existing: dict = {}
    if config_path.exists():
        try:
            existing = json.loads(config_path.read_text(encoding="utf-8"))
        except (json.JSONDecodeError, OSError):
            existing = {}

    # 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
    )

    # Write to global mcpServers key — the format Claude Code actually reads
    if "mcpServers" not in existing:
        existing["mcpServers"] = {}

    existing["mcpServers"]["poolclaw"] = {
        "type": "stdio",
        "command": command,
        "env": {
            "POOLCLAW_SERVER": server,
            "POOLCLAW_TOKEN": token,
        },
    }

    config_path.write_text(
        json.dumps(existing, indent=2) + "\n",
        encoding="utf-8",
    )

    print()
    print("  PoolClaw MCP configured successfully!")
    print()
    print(f"  Config: {config_path}")
    print(f"  Server: {server}")
    print(f"  Token:  {token[:12]}...{token[-4:]}")
    print()
    print("  Next step: restart Claude Code, then say:")
    print('  "Create a pool to build an AI social network"')
    print()


if __name__ == "__main__":
    main()
