#!/usr/bin/env bash
# Reproducible Python environment recipes for the EvoMO PyTorch rewrite.
#
# Host this was verified on: AMD Instinct MI300X (gfx942), ROCm 7.1.0,
# system Python 3.12.3, uv 0.13.1, single GPU.
#
# Creates (or recreates from scratch) both environments:
#
#   env A  ${EVOMO_ENV_A:-/tmp/evomo_env}         evox 2.0.0a1 + evoxc 0.1.0 on
#                                                 numpy / iree(rocm) / xla(rocm)
#   env B  ${EVOMO_ENV_B:-/tmp/evomo_env_legacy}  torch 2.9.1+rocm6.4 + evox 1.4.1
#                                                 (the legacy PyTorch evomo)
#
# Both venvs are wiped first, so re-running the script on a machine that already
# has them yields exactly the same package set; it needs network access.
# The pins and the reasons for them are documented in scripts/README.md.
#
#   ./scripts/setup_env.sh                          # both environments
#   EVOMO_SKIP_LEGACY=1 ./scripts/setup_env.sh      # only env A
#   EVOMO_ENV_A=/tmp/a EVOMO_ENV_B=/tmp/b ./scripts/setup_env.sh
#
# NOTE: uv is not on PATH on this host; UV defaults to /root/.local/bin/uv.
set -euo pipefail

UV="${UV:-/root/.local/bin/uv}"
PY_VER="${EVOMO_PYTHON:-3.12}"
ENV_A="${EVOMO_ENV_A:-/tmp/evomo_env}"
ENV_B="${EVOMO_ENV_B:-/tmp/evomo_env_legacy}"
PYTHON_A="$ENV_A/bin/python"
PYTHON_LEGACY="$ENV_B/bin/python"

log() { printf '\n== %s\n' "$*"; }
die() { printf 'setup_env.sh: %s\n' "$*" >&2; exit 1; }

[ -x "$UV" ] || die "uv not found at '$UV' (set UV=/path/to/uv)"

# ---------------------------------------------------------------------------
# env A -- the 2.0 stack: evox 2.0.0a1 (evoxc-based) + the compiled backends.
# ---------------------------------------------------------------------------
# iree-base-* 3.13.0, NOT 3.11.x: 3.11's iree-compile SIGSEGVs on while-loop
# heavy (MO/NSGA-II) StableHLO, which is exactly this smoke. evoxc's own extras
# pin >=3.13.0,<3.14.
#
# jax-rocm7-pjrt 0.10.2, NOT the current 0.11/0.12: the newer wheels link
# against the ROCm pip "sysdeps" libraries (librocm_sysdeps_drm.so.2 ...) that a
# system ROCm install does not ship, so the PJRT plugin fails its ABI gate.
# 0.10.2 links only against system ROCm 7 libraries.
log "env A: creating venv at $ENV_A (python $PY_VER)"
"$UV" venv --clear --python "$PY_VER" "$ENV_A"

log "env A: installing pinned packages"
"$UV" pip install --python "$PYTHON_A" \
    numpy==2.5.4 \
    pytest==9.2.0 \
    evoxc==0.1.0 \
    evox==2.0.0a1 \
    iree-base-compiler==3.13.0 \
    iree-base-runtime==3.13.0 \
    jax-rocm7-pjrt==0.10.2

# ---------------------------------------------------------------------------
# env B -- the legacy PyTorch stack (torch from the ROCm 6.4 wheel index).
# ---------------------------------------------------------------------------
if [ -z "${EVOMO_SKIP_LEGACY:-}" ]; then
    log "env B: creating venv at $ENV_B (python $PY_VER)"
    "$UV" venv --clear --python "$PY_VER" "$ENV_B"

    log "env B: installing pinned packages"
    # Two steps on purpose. torch MUST be pinned with its local version segment
    # (`2.9.1+rocm6.4`) and MUST be installed from the ROCm index alone: a bare
    # `torch==2.9.1` also matches PyPI's CUDA build `2.9.1+cu128`, which uv
    # ranks higher and installs instead (~2 GB of nvidia-* wheels on a
    # ROCm-only host). Mixing `--index-url` with an extra PyPI index makes uv
    # resolve `torch` from PyPI first and then declare the ROCm pin
    # unsatisfiable, so the two installs stay separate; `evox` only requires
    # `torch>=2.6.0`, so the second step leaves the installed ROCm torch alone.
    "$UV" pip install --python "$PYTHON_LEGACY" \
        --index-url https://download.pytorch.org/whl/rocm6.4 \
        torch==2.9.1+rocm6.4
    "$UV" pip install --python "$PYTHON_LEGACY" \
        numpy==2.5.4 \
        pytest==9.2.0 \
        evox==1.4.1
fi

# ---------------------------------------------------------------------------
# verification
# ---------------------------------------------------------------------------
log "verifying env A"
"$PYTHON_A" - <<'PY'
import importlib.metadata as md

import numpy
import evox
import evoxc

versions = ", ".join(
    f"{name} {md.version(name)}"
    for name in ("numpy", "evoxc", "evox", "iree-base-compiler", "iree-base-runtime", "jax-rocm7-pjrt")
)
print(f"  ok: {versions}")
print(f"  ok: evox imports from {evox.__file__}")
PY

# The xla backend's only hard prerequisite: the PJRT plugin must resolve every
# shared library it was linked against (this is the check that 0.11/0.12 fail).
PLUGIN="$("$PYTHON_A" -c \
    'import sysconfig; print(sysconfig.get_paths()["purelib"] + "/jax_plugins/xla_rocm7/xla_rocm_plugin.so")')"
[ -f "$PLUGIN" ] || die "PJRT plugin missing: $PLUGIN"
if ldd "$PLUGIN" 2>/dev/null | grep -q "not found"; then
    ldd "$PLUGIN" 2>/dev/null | grep "not found" >&2
    die "PJRT plugin at $PLUGIN has unresolved shared libraries"
fi
echo "  ok: PJRT plugin resolves (EVOXC_PJRT_PLUGIN=$PLUGIN)"

if [ -z "${EVOMO_SKIP_LEGACY:-}" ]; then
    log "verifying env B"
    "$PYTHON_LEGACY" - <<'PY'
import importlib.metadata as md

import torch

print(f"  ok: torch {torch.__version__}")
if not torch.__version__.endswith("+rocm6.4"):
    raise SystemExit(f"setup_env.sh: expected the ROCm 6.4 torch build, got {torch.__version__}")
print(f"  ok: evox {md.version('evox')}, numpy {md.version('numpy')}")
try:
    print(f"  ok: pytorch-triton-rocm {md.version('pytorch-triton-rocm')}")
except md.PackageNotFoundError:
    raise SystemExit("setup_env.sh: pytorch-triton-rocm missing -- not the ROCm torch build")
print(f"  ok: torch.cuda.is_available() = {torch.cuda.is_available()}")
if torch.cuda.is_available():
    print(f"  ok: device = {torch.cuda.get_device_name(0)}")
PY
fi

log "done"
cat <<'EOF'
Next steps:
  source scripts/env.sh            # env A (evox 2.0 / iree / xla)
  source scripts/env.sh --legacy   # env B (torch / legacy evomo)
  python scripts/smoke_backends.py --backend numpy|iree|xla
See scripts/README.md for the measured numbers and the known failure modes.
EOF