"""Genesis — universal autonomous AI agent."""

import platform
import subprocess
import sys
import urllib.request
import stat
from pathlib import Path

try:
    from importlib.metadata import version as _pkg_version
    __version__ = _pkg_version("genesis-ai-cli")
except Exception:
    __version__ = "0.1.9"

REPO = "deadraid/genesis"

PLATFORM_MAP = {
    ("Darwin", "arm64"): "genesis-macos-aarch64",
    ("Darwin", "x86_64"): "genesis-macos-x86_64",
    ("Linux", "x86_64"): "genesis-linux-x86_64",
    ("Linux", "aarch64"): "genesis-linux-aarch64",
    ("Windows", "AMD64"): "genesis-windows-x86_64",
}


def _get_binary_name():
    system = platform.system()
    machine = platform.machine()
    key = (system, machine)

    name = PLATFORM_MAP.get(key)
    if not name:
        print(f"Unsupported platform: {system} {machine}", file=sys.stderr)
        print(f"Supported: {list(PLATFORM_MAP.keys())}", file=sys.stderr)
        sys.exit(1)

    if system == "Windows":
        name += ".exe"
    return name


def _get_bin_dir():
    return Path(__file__).parent / "bin"


def _ensure_binary():
    bin_dir = _get_bin_dir()
    ext = ".exe" if platform.system() == "Windows" else ""
    binary = bin_dir / f"genesis{ext}"

    if binary.exists():
        try:
            current = subprocess.run(
                [str(binary), "--version"],
                capture_output=True, text=True, timeout=5,
            ).stdout.strip()
            if current in (__version__, f"v{__version__}"):
                return binary
            print(f"Updating genesis {current} → v{__version__}...")
            binary.unlink()
        except Exception:
            binary.unlink(missing_ok=True)

    bin_dir.mkdir(parents=True, exist_ok=True)

    binary_name = _get_binary_name()
    url = f"https://github.com/{REPO}/releases/download/v{__version__}/{binary_name}"

    print(f"Downloading genesis v{__version__}...")
    print(f"  {url}")

    try:
        urllib.request.urlretrieve(url, binary)
        if platform.system() != "Windows":
            binary.chmod(binary.stat().st_mode | stat.S_IEXEC | stat.S_IXGRP | stat.S_IXOTH)
        print("genesis installed successfully.")
    except Exception as e:
        print(f"Failed to download genesis: {e}", file=sys.stderr)
        print(f"Download manually: https://github.com/{REPO}/releases/tag/v{__version__}", file=sys.stderr)
        sys.exit(1)

    return binary


def main():
    binary = _ensure_binary()
    result = subprocess.run([str(binary)] + sys.argv[1:])
    sys.exit(result.returncode)


if __name__ == "__main__":
    main()
