#!/usr/bin/env modbuild

pbuild::prep() {
    :
}

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"
    # python 3.9: PanDDA2's torch==1.13.1 pin has no wheels past 3.10, README targets 3.9
    "$UV" venv --python 3.9 "$PREFIX/venv" || \
        std::die 42 "PanDDA2: 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"

    # xchem/PanDDA2 master @ 2026-08-18, pinned for reproducibility — the repo
    # has no usable release tags (only 'alpha'). Bump sha to update.
    local -r sha=d513af6d8c49b602d4fd91c084fe62b7fb19da8e
    # cpu extra-index: plain torch==1.13.1 from PyPI drags the ~2 GB CUDA build;
    # the project's own [tool.uv.pip] cpu index only applies inside its repo dir
    "$UV" pip install --python "$PREFIX/venv/bin/python" \
        --extra-index-url https://download.pytorch.org/whl/cpu \
        "pandda_2_gemmi @ git+https://github.com/xchem/PanDDA2.git@${sha}" || \
        std::die 42 "PanDDA2: uv pip install from GitHub failed"

    # First run gdown-fetches ~1 GB of CNN scoring models NEXT TO THE INSTALLED
    # CODE (pandda_gemmi/pandda/get_scoring_models.py) — read-only for users
    # under /opt/psi, so fetch them now into the exact dir the code checks.
    local cnn_dir
    cnn_dir=$("$PREFIX/venv/bin/python" -c 'import os, inspect; from pandda_gemmi.cnn import LitEventScoring; print(os.path.dirname(inspect.getfile(LitEventScoring)))') || \
        std::die 42 "PanDDA2: import pandda_gemmi.cnn failed — install is broken"
    local -r GD="$PREFIX/venv/bin/gdown"
    "$GD" 1b58MUIJdIYyYHr-UhASVCvIWtIgrLYtV -O "$cnn_dir/model_event.ckpt" && \
    "$GD" 1qyPqPylOguzXmt6XSFaXCKrnvb8gZ8E2 -O "$cnn_dir/model_event_config.yaml" && \
    "$GD" 15RnkrGtEmFvtBvIlwfaUE1QfQrD2npnu -O "$cnn_dir/event_score_quantiles.csv" && \
    "$GD" 17ow_rxuEvi0LitMP_jTWGMSDt-FfJCkR -O "$cnn_dir/model_build.ckpt" && \
    "$GD" 1HEXHZ6kfh92lQoWBHalGbUJ-iCsOIkFo -O "$cnn_dir/model_build_config.yaml" || \
        std::die 42 "PanDDA2: model fetch from Google Drive failed (blocked or quota) — download the 5 files by hand and copy them into ${cnn_dir}"

    [[ -x "$PREFIX/venv/bin/pandda2.analyse" ]] || \
        std::die 42 "PanDDA2: venv/bin/pandda2.analyse missing — install incomplete"
}
