"""Install mongosh for GBS tools. Run: point-topic-mcp-install-mongosh

GBS tools use mongosh (shell) instead of PyMongo to avoid Python SSL issues
in cloud/EC2 environments. mongosh must be installed on the system.

Usage:
    sudo point-topic-mcp-install-mongosh   # Linux (needs sudo for apt/yum/dnf)
    point-topic-mcp-install-mongosh        # macOS (brew usually doesn't need sudo)
"""

import os
import platform
import shutil
import subprocess
import sys


def _mongosh_installed() -> bool:
    return shutil.which("mongosh") is not None


def _run(cmd: list[str], check: bool = True) -> subprocess.CompletedProcess:
    return subprocess.run(
        cmd,
        check=check,
        capture_output=False,
        text=True,
    )


def _linux_id() -> tuple[str, str]:
    """Return (ID, VERSION_ID) from /etc/os-release."""
    try:
        with open("/etc/os-release") as f:
            data = {}
            for line in f:
                if "=" in line:
                    k, v = line.strip().split("=", 1)
                    data[k] = v.strip('"')
            return data.get("ID", ""), data.get("VERSION_ID", "")
    except OSError:
        return "", ""


def _install_macos() -> int:
    if shutil.which("brew"):
        return _run(["brew", "install", "mongosh"]).returncode
    print("macOS: install Homebrew first (https://brew.sh) then run: brew install mongosh", file=sys.stderr)
    return 1


def _install_ubuntu_debian() -> int:
    gpg_key = "/usr/share/keyrings/mongodb-server-8.0.gpg"
    list_file = "/etc/apt/sources.list.d/mongodb-org-8.0.list"
    try:
        out = subprocess.run(["lsb_release", "-cs"], capture_output=True, text=True, check=True)
        codename = out.stdout.strip()
    except (subprocess.CalledProcessError, FileNotFoundError):
        print("Could not detect Ubuntu/Debian codename. Try: lsb_release -cs", file=sys.stderr)
        return 1
    for cmd in [
        f"curl -fsSL https://www.mongodb.org/static/pgp/server-8.0.asc | sudo gpg -o {gpg_key} --dearmor",
        f'echo "deb [ signed-by={gpg_key} ] https://repo.mongodb.org/apt/ubuntu {codename}/mongodb-org/8.0 multiverse" | sudo tee {list_file}',
    ]:
        if os.system(cmd) != 0:
            return 1
    if subprocess.run(["sudo", "apt-get", "update"], check=False).returncode != 0:
        return 1
    return subprocess.run(["sudo", "apt-get", "install", "-y", "mongodb-mongosh"], check=False).returncode


def _install_rhel_amazon() -> int:
    pkg_mgr = "dnf" if shutil.which("dnf") else "yum"
    r = subprocess.run(["sudo", pkg_mgr, "install", "-y", "mongodb-mongosh"], capture_output=False)
    if r.returncode == 0:
        return 0
    dist_id, ver = _linux_id()
    if "amazon" in dist_id:
        repo_ver = "2" if ver and "2" in str(ver) else "2023"
        base = f"https://repo.mongodb.org/yum/amazon/{repo_ver}/mongodb-org/8.0/x86_64/"
    elif dist_id in ("rhel", "rocky", "almalinux"):
        major = ver.split(".")[0] if ver else "9"
        base = f"https://repo.mongodb.org/yum/redhat/{major}/mongodb-org/8.0/x86_64/"
    else:
        base = "https://repo.mongodb.org/yum/redhat/9/mongodb-org/8.0/x86_64/"
    repo = f"""[mongodb-org-8.0]
name=MongoDB Repository
baseurl={base}
gpgcheck=1
enabled=1
gpgkey=https://www.mongodb.org/static/pgp/server-8.0.asc
"""
    tmp = "/tmp/mongodb-org-8.0.repo"
    try:
        with open(tmp, "w") as f:
            f.write(repo)
        subprocess.run(["sudo", "cp", tmp, "/etc/yum.repos.d/mongodb-org-8.0.repo"], check=True)
        r = subprocess.run(["sudo", pkg_mgr, "install", "-y", "mongodb-mongosh"], capture_output=False)
        return r.returncode
    except Exception as e:
        print(f"Failed: {e}. Install manually: https://www.mongodb.com/docs/mongodb-shell/install/", file=sys.stderr)
        return 1


def main() -> int:
    if _mongosh_installed():
        out = subprocess.run(["mongosh", "--version"], capture_output=True, text=True)
        ver = out.stdout or out.stderr or "unknown"
        print(f"mongosh already installed: {ver.split(chr(10))[0]}")
        return 0

    print("Installing mongosh for GBS tools...")
    system = platform.system()
    if system == "Darwin":
        return _install_macos()
    if system == "Linux":
        dist_id, _ = _linux_id()
        if dist_id in ("ubuntu", "debian", "pop"):
            return _install_ubuntu_debian()
        if dist_id in ("amazon", "rhel", "fedora", "centos", "rocky", "almalinux"):
            return _install_rhel_amazon()
        print(f"Unsupported Linux distro: {dist_id}. Install manually: https://www.mongodb.com/docs/mongodb-shell/install/", file=sys.stderr)
        return 1

    print(f"Unsupported OS: {system}. Install manually: https://www.mongodb.com/docs/mongodb-shell/install/", file=sys.stderr)
    return 1


if __name__ == "__main__":
    sys.exit(main())
