"""Engineer runtime install/detection helpers.

Bootstrap uses Codex app-server (`codex app-server`) as the engineer runtime.
In BYOC environments we cannot assume a pinned machine image, so bootstrap
ensures a pinned Codex release is available.
"""

from __future__ import annotations

import platform
from pathlib import Path
import shutil
import sys
import tarfile
import tempfile
import urllib.request
import zipfile

from bootstrap.constants import CODEX_GITHUB_REPO, CODEX_RELEASE_TAG


def _download(url: str, dest: Path) -> None:
    with urllib.request.urlopen(url) as resp, dest.open("wb") as fh:
        fh.write(resp.read())


def ensure_codex(
    *,
    tag: str | None = None,
    download_dir: Path | None = None,
) -> Path:
    """Ensure the pinned `codex` binary is available and return its path."""

    resolved_tag = tag or CODEX_RELEASE_TAG
    base_dir = (download_dir or Path(tempfile.mkdtemp())).resolve()

    install_dir = base_dir / "codex" / resolved_tag
    install_dir.mkdir(parents=True, exist_ok=True)

    exe_name = "codex.exe" if sys.platform == "win32" else "codex"
    installed = install_dir / exe_name
    if installed.exists():
        installed.chmod(installed.stat().st_mode | 0o111)
        return installed.resolve()

    url, archive_type, extracted_name = _build_codex_download(resolved_tag)
    archive_path = install_dir / f"codex.{archive_type}"
    _download(url, archive_path)

    if archive_type == "zip":
        with zipfile.ZipFile(archive_path, "r") as zf:
            zf.extractall(path=install_dir)
    elif archive_type == "tar.gz":
        with tarfile.open(archive_path, "r:gz") as tf:
            tf.extractall(path=install_dir)
    else:  # pragma: no cover - defensive
        raise RuntimeError(f"unsupported archive type: {archive_type}")

    found = next(install_dir.rglob(extracted_name), None)
    if found is None:
        raise RuntimeError("codex binary not found after extraction")

    found.chmod(found.stat().st_mode | 0o111)
    if found.name != exe_name:
        shutil.move(str(found), str(installed))
    installed.chmod(installed.stat().st_mode | 0o111)
    return installed.resolve()


def _build_codex_download(tag: str) -> tuple[str, str, str]:
    """Return (download_url, archive_type, extracted_binary_name) for codex."""

    system = sys.platform
    machine = platform.machine().lower()

    if "arm" in machine or "aarch64" in machine:
        arch = "aarch64"
    else:
        arch = "x86_64"

    if system == "win32":
        target = f"{arch}-pc-windows-msvc.exe"
        archive_type = "zip"
        extracted_name = f"codex-{target}"
        filename = f"{extracted_name}.zip"
    elif system.startswith("darwin"):
        target = f"{arch}-apple-darwin"
        archive_type = "tar.gz"
        extracted_name = f"codex-{target}"
        filename = f"{extracted_name}.tar.gz"
    elif system.startswith("linux"):
        # Codex publishes both gnu and musl builds; prefer musl for portability.
        target = f"{arch}-unknown-linux-musl"
        archive_type = "tar.gz"
        extracted_name = f"codex-{target}"
        filename = f"{extracted_name}.tar.gz"
    else:  # pragma: no cover - defensive
        raise RuntimeError(f"unsupported platform: {system}")

    url = f"https://github.com/{CODEX_GITHUB_REPO}/releases/download/{tag}/{filename}"
    return url, archive_type, extracted_name
