#!/usr/bin/env bash
set -euo pipefail

ROOT=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")/.." && pwd)
RELEASE="$ROOT/dualcoach/releases/v1.1.0"
BASE="$ROOT/dualcoach/releases/v1.0.0/delivered"
TOOLS="$BASE/verification-tools"
WHEELHOUSE="$BASE/wheelhouse"
PYTHON=/home/cube/miniconda3/bin/python3.12

TEMP=$(mktemp -d /tmp/dualcoach-v11-installed-replay.XXXXXX)
cleanup() {
    chmod -R u+rwX "$TEMP" 2>/dev/null || true
    rm -rf "$TEMP"
}
trap cleanup EXIT

install -m 0600 \
    "$RELEASE/artifacts/hermes_agent-0.17.0-py3-none-any.whl" \
    "$TEMP/hermes_agent-0.17.0-py3-none-any.whl"
install -m 0600 \
    "$RELEASE/artifacts/physique_checkin_cli-0.1.0-py3-none-any.whl" \
    "$TEMP/physique_checkin_cli-0.1.0-py3-none-any.whl"
install -m 0600 \
    "$RELEASE/preexecution-product-binding.json" \
    "$TEMP/preexecution-product-binding.json"

"$PYTHON" -I -m venv "$TEMP/venv"
chmod 0700 "$TEMP/venv"
mapfile -t dependencies < <(find "$WHEELHOUSE" -type f -name '*.whl' | sort)
PIP_CONFIG_FILE=/dev/null PIP_NO_INDEX=1 \
    "$TEMP/venv/bin/python" -I -m pip install \
    --no-index \
    --no-deps \
    --no-compile \
    "${dependencies[@]}" \
    "$TEMP/hermes_agent-0.17.0-py3-none-any.whl" \
    "$TEMP/physique_checkin_cli-0.1.0-py3-none-any.whl" \
    >/dev/null

SITE_PACKAGES=$(
    "$TEMP/venv/bin/python" -I -c \
        "import sysconfig; print(sysconfig.get_paths()['purelib'])"
)
EVIDENCE="$TEMP/evidence"
cd "$TEMP"
"$TEMP/venv/bin/python" -B -I "$TOOLS/source_golden_path.py" \
    --installed-venv "$TEMP/venv" \
    --installed-site-packages "$SITE_PACKAGES" \
    --profile-wheel "$TEMP/physique_checkin_cli-0.1.0-py3-none-any.whl" \
    --hermes-wheel "$TEMP/hermes_agent-0.17.0-py3-none-any.whl" \
    --product-binding "$TEMP/preexecution-product-binding.json" \
    --evidence-root "$EVIDENCE"
"$TEMP/venv/bin/python" -B -I \
    "$TOOLS/verify_source_golden_path.py" "$EVIDENCE"
