#!/usr/bin/env modbuild

# qFit (multiconformer model building), uv route from the sha-pinned GitHub
# tarball. Upstream traps differ by era, so both hooks branch on V_PKG:
# - 3.x (2022): numpy<1.22 caps Python at 3.10; MIQP solvers (cvxopt, cplex)
#   only in environment.yml -> pip explicitly; logtools imports pkg_resources
#   at runtime and uv venvs ship no setuptools -> pin setuptools<81
#   (>=81 removed pkg_resources entirely).
# - 2024.3+ : numpy relaxed to <2 -> Python 3.12; solvers switched to
#   cvxpy+pyscipopt and moved into install_requires (no CPLEX size cap);
#   pkg_resources import removed. BUT structure I/O now imports
#   iotbx/scitbx/cctbx/mmtbx, and cctbx-base is only in environment.yml,
#   not install_requires (same conda-only trap as the old solvers)
#   -> pip cctbx-base explicitly (manylinux_2_28 wheel, Ra RHEL8 = glibc 2.28).
# - both eras: use_scm_version needs git metadata the tarball lacks
#   -> SETUPTOOLS_SCM_PRETEND_VERSION

pbuild::configure() {
    # modbuild's shell strips ~/.local/bin from PATH; override with UV=/path/to/uv if needed
    UV="${UV:-$HOME/.local/bin/uv}"
    export UV_CACHE_DIR="/opt/psi/MX/.uv-cache"
    export UV_PYTHON_INSTALL_DIR="$PREFIX/python"
    case "$V_PKG" in
        3.*) PY=3.10 ;;   # numpy<1.22 has no 3.11+ wheels
        *)   PY=3.12 ;;   # numpy<2 -> 1.26.x wheels up to 3.12
    esac
    "$UV" venv --python "$PY" "$PREFIX/venv" || std::die 42 "uv venv failed - is uv at \$UV?"
}

pbuild::compile() {
    :
}

pbuild::install() {
    UV="${UV:-$HOME/.local/bin/uv}"
    export UV_CACHE_DIR="/opt/psi/MX/.uv-cache"
    export CC=gcc
    export SETUPTOOLS_SCM_PRETEND_VERSION="${V_PKG}"
    local extras=()
    case "$V_PKG" in
        # cplex is the IBM Community Edition pip wheel (problem-size limited);
        # full CPLEX needs an academic license, see README.
        3.*) extras=('setuptools<81' cvxopt cplex) ;;
        # cctbx-base: conda-only dep upstream forgot in install_requires;
        # PyPI wheel (not conda - anaconda repo is unreachable from Ra)
        *)   extras=(cctbx-base) ;;
    esac
    "$UV" pip install --python "$PREFIX/venv/bin/python" \
        "${extras[@]}" "$SRC_DIR" || \
        std::die 42 "qfit install failed - check build log above"
    [[ -x "$PREFIX/venv/bin/qfit_protein" ]] || std::die 42 "qfit_protein missing from venv"
    # full import chain (hits iotbx, solvers, ...) - catches forgotten runtime deps at build time
    "$PREFIX/venv/bin/python" -c "import qfit" || std::die 42 "qfit import failed - missing runtime dep?"
}
