"""
MCP Auto-Installer for El Gringo
==================================

Configures El Gringo as an MCP server in Claude Code's ~/.claude/mcp.json.

Usage:
    elgringo mcp install   — add/update MCP config
    elgringo mcp status    — check current MCP status
    elgringo mcp remove    — remove MCP config
"""

import json
import os
import sys
from pathlib import Path


def _find_mcp_server() -> str:
    """Find the mcp_server.py path."""
    # Try via installed package
    try:
        import elgringo.server
        server_dir = Path(elgringo.server.__file__).parent
        mcp_path = server_dir / "mcp_server.py"
        if mcp_path.exists():
            return str(mcp_path)
    except (ImportError, AttributeError):
        pass

    # Try relative to this file (development install)
    cli_dir = Path(__file__).parent
    candidates = [
        cli_dir.parent / "server" / "mcp_server.py",
        cli_dir.parent.parent / "mcp_server.py",
    ]
    for candidate in candidates:
        if candidate.exists():
            return str(candidate.resolve())

    return ""


def _find_python() -> str:
    """Find the venv Python executable (not the system/Xcode one)."""
    venv_python = Path.home() / ".venvs" / "ai-platform" / "bin" / "python3"
    if venv_python.exists():
        return str(venv_python)
    return sys.executable


def _find_start_script() -> str:
    """Find the start_mcp.sh script."""
    # Try relative to this file (development install)
    project_root = Path(__file__).parent.parent.parent
    script = project_root / "start_mcp.sh"
    if script.exists():
        return str(script.resolve())
    return ""


def _get_env_from_config() -> dict:
    """Pull API keys from ~/.elgringo/config.yml for MCP env block."""
    env = {}
    try:
        from elgringo.cli.setup import load_config, CONFIG_FILE
        if CONFIG_FILE.exists():
            config = load_config()
            api_keys = config.get("api_keys", {})
            key_map = {
                "openai": "OPENAI_API_KEY",
                "gemini": "GEMINI_API_KEY",
                "xai": "XAI_API_KEY",
                "groq": "GROQ_API_KEY",
                "anthropic": "ANTHROPIC_API_KEY",
            }
            for config_name, env_name in key_map.items():
                value = api_keys.get(config_name)
                if value:
                    env[env_name] = value
    except Exception:
        pass

    # Also include PYTHONPATH so imports work
    project_root = Path(__file__).parent.parent.parent
    env["PYTHONPATH"] = str(project_root.resolve())

    return env


def _get_mcp_json_path() -> Path:
    """Get the path to ~/.claude/mcp.json."""
    return Path.home() / ".claude" / "mcp.json"


def install_mcp():
    """Add or update ai-team entry in ~/.claude/mcp.json."""
    # Prefer start_mcp.sh (handles venv, secrets, local vs remote detection)
    start_script = _find_start_script()
    mcp_server = _find_mcp_server()

    if not start_script and not mcp_server:
        print("\033[91mError:\033[0m Could not find start_mcp.sh or mcp_server.py")
        print("  Expected at: ElGringo/start_mcp.sh or elgringo/server/mcp_server.py")
        return False

    env_vars = _get_env_from_config()
    mcp_json_path = _get_mcp_json_path()

    # Read or create mcp.json
    if mcp_json_path.exists():
        try:
            data = json.loads(mcp_json_path.read_text())
        except (json.JSONDecodeError, OSError):
            data = {}
    else:
        mcp_json_path.parent.mkdir(parents=True, exist_ok=True)
        data = {}

    # Ensure mcpServers key exists
    if "mcpServers" not in data:
        data["mcpServers"] = {}

    # Build the entry — prefer start_mcp.sh, fallback to direct python
    if start_script:
        entry = {
            "command": start_script,
            "args": [],
        }
        if env_vars:
            entry["env"] = env_vars
        display_cmd = start_script
    else:
        python_path = _find_python()
        entry = {
            "command": python_path,
            "args": [mcp_server],
        }
        if env_vars:
            entry["env"] = env_vars
        display_cmd = f"{python_path} {mcp_server}"

    # Remove old "el-gringo" entry if present (renamed to ai-team)
    if "el-gringo" in data["mcpServers"]:
        del data["mcpServers"]["el-gringo"]

    # Add/update as "ai-team"
    data["mcpServers"]["ai-team"] = entry

    # Write back
    mcp_json_path.write_text(json.dumps(data, indent=2) + "\n")

    print("\n\033[92mMCP server configured!\033[0m")
    print(f"  Config: {mcp_json_path}")
    print(f"  Command: {display_cmd}")
    if env_vars:
        key_names = [k for k in env_vars if k != "PYTHONPATH"]
        if key_names:
            print(f"  API keys: {', '.join(key_names)}")
    print("\n  \033[1mRestart Claude Code to activate.\033[0m\n")
    return True


def check_mcp_status():
    """Check if el-gringo is configured in MCP."""
    mcp_json_path = _get_mcp_json_path()

    if not mcp_json_path.exists():
        print(f"\n  \033[93mNo MCP config found\033[0m at {mcp_json_path}")
        print("  Run: elgringo mcp install\n")
        return

    try:
        data = json.loads(mcp_json_path.read_text())
    except (json.JSONDecodeError, OSError) as e:
        print(f"\n  \033[91mError reading MCP config:\033[0m {e}\n")
        return

    servers = data.get("mcpServers", {})
    entry = servers.get("el-gringo") or servers.get("ai-team")
    entry_name = "el-gringo" if "el-gringo" in servers else "ai-team" if "ai-team" in servers else None

    if not entry:
        print("\n  \033[93mEl Gringo not found in MCP config\033[0m")
        print("  Run: elgringo mcp install\n")
        return

    command = entry.get("command", "?")
    args = entry.get("args", [])
    env = entry.get("env", {})

    print("\n\033[1m  El Gringo MCP Status\033[0m\n")
    print(f"  \033[92mInstalled\033[0m (as \"{entry_name}\")")
    print(f"  Command: {command}")
    if args:
        server_path = args[0]
        exists = os.path.isfile(server_path)
        status = "\033[92mexists\033[0m" if exists else "\033[91mmissing\033[0m"
        print(f"  Server:  {server_path} ({status})")
    if env:
        keys = [k for k in env if k.endswith("_KEY")]
        print(f"  API keys: {', '.join(keys) if keys else 'none'}")
    print()


def remove_mcp():
    """Remove el-gringo (and legacy ai-team) from MCP config."""
    mcp_json_path = _get_mcp_json_path()

    if not mcp_json_path.exists():
        print("  \033[2mNo MCP config found\033[0m\n")
        return

    try:
        data = json.loads(mcp_json_path.read_text())
    except (json.JSONDecodeError, OSError):
        return

    servers = data.get("mcpServers", {})
    removed = []
    for name in ("el-gringo", "ai-team"):
        if name in servers:
            del servers[name]
            removed.append(name)

    if not removed:
        print("  \033[2mEl Gringo not in MCP config\033[0m\n")
        return

    mcp_json_path.write_text(json.dumps(data, indent=2) + "\n")
    print(f"\n  \033[92mRemoved\033[0m {', '.join(removed)} from {mcp_json_path}")
    print("  Restart Claude Code to apply.\n")


def handle_mcp_command(args: list):
    """Route mcp subcommands."""
    subcmd = args[0] if args else "status"

    if subcmd == "install":
        install_mcp()
    elif subcmd == "status":
        check_mcp_status()
    elif subcmd == "remove":
        remove_mcp()
    else:
        print("\n\033[1m  elgringo mcp\033[0m — MCP server management\n")
        print("  \033[96minstall\033[0m   Add El Gringo to Claude Code's MCP config")
        print("  \033[96mstatus\033[0m    Check current MCP configuration")
        print("  \033[96mremove\033[0m    Remove El Gringo from MCP config\n")
