#!/usr/bin/env bash
# Clean end-to-end reproduction of the Soft-Elo Table 2 claim (arXiv:2606.13221v3).
#
# Run this from a checkout of this Space repo:
#   bash run.sh                                   # compute only; no Hub writes, no token needed
#   PUBLISH=1 HF_TOKEN=hf_... bash run.sh         # also publish results/, environment/ and the log
#                                                 # to this Space
#
# Optional overrides: WORK=/some/dir (default ./work, next to this script).
#
# Stages: main suite (8 judges x leave-one-model-out) -> literal-rule tie audit ->
# tolerance audit (tight-tol reruns) -> paired bootstrap -> comparison table + verdict.
# With PUBLISH=1 it uploads results/, environment/ and its own log to the Space only.
set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
export WORK="${WORK:-"$SCRIPT_DIR/work"}"
PUBLISH="${PUBLISH:-0}"

mkdir -p "$WORK/logs" "$WORK/environment"
exec > >(tee "$WORK/logs/run_sh_clean.log") 2>&1

echo "== run.sh clean run start =="
date -u +"%Y-%m-%dT%H:%M:%SZ"
echo "publish: $PUBLISH (1 = upload results/, environment/ and this log to the Space)"
echo "work: $WORK"
echo "python: $(python3 --version 2>&1)"
python3 --version > "$WORK/environment/python_version.txt" 2>&1
uname -a > "$WORK/environment/platform.txt"
echo "platform: $(uname -srm), cores: $(nproc)"

# --- clone the authors' pinned code -------------------------------------------
cd "$WORK"
if [ ! -d SoftElo ]; then git clone https://github.com/kargibora/SoftElo; fi
cd SoftElo
git checkout b4d34712a3931a85ec7a2929d6ce7c63d5b2dfcf
echo "authors' commit: $(git rev-parse HEAD)"

# --- build the locked environment ---------------------------------------------
pip install --quiet uv==0.13.10
uv sync --project reproduction --locked --python 3.12
cp reproduction/uv.lock "$WORK/environment/uv.lock"
uv run --project reproduction python -c "import platform, importlib.metadata as m; pkgs = sorted((d.metadata['Name'], d.version) for d in m.distributions()); print('\n'.join(f'{n}=={v}' for n, v in pkgs))" > "$WORK/environment/pip_freeze.txt"
echo "environment captured: uv.lock + pip freeze + python/platform"

# --- stage scripts come from this Space checkout --------------------------------
for f in run_repro.py run_literal.py run_tol.py run_bootstrap.py table.py; do
  test -f "$SCRIPT_DIR/scripts/$f" || { echo "missing $SCRIPT_DIR/scripts/$f — run from a Space checkout"; exit 1; }
done
echo "stage scripts: $SCRIPT_DIR/scripts/"

# --- stages ---------------------------------------------------------------------
uv run --project reproduction python "$SCRIPT_DIR/scripts/run_repro.py"
uv run --project reproduction python "$SCRIPT_DIR/scripts/run_literal.py"
uv run --project reproduction python "$SCRIPT_DIR/scripts/run_tol.py"
uv run --project reproduction python "$SCRIPT_DIR/scripts/run_bootstrap.py"
uv run --project reproduction python "$SCRIPT_DIR/scripts/table.py"

# --- optional publish ------------------------------------------------------------
if [ "$PUBLISH" = "1" ]; then
  echo "publishing results/, environment/ and the run log to the Space..."
  # publish via the same locked env (it has huggingface_hub; the base image does not)
  uv run --project reproduction python - <<'PY'
import os
from huggingface_hub import HfApi
api = HfApi(token=os.environ["HF_TOKEN"])
work = os.environ["WORK"]
api.upload_folder(folder_path=f"{work}/SoftElo/results", repo_id="melomba2/soft-elo-table2-reproduction",
                  repo_type="space", path_in_repo="results",
                  commit_message="Clean run: results/ (all stage outputs + Table 2 comparison + verdict.json)")
api.upload_folder(folder_path=f"{work}/environment", repo_id="melomba2/soft-elo-table2-reproduction",
                  repo_type="space", path_in_repo="environment",
                  commit_message="Clean run: environment/ (uv.lock, pip freeze, python, platform)")
api.upload_folder(folder_path=f"{work}/logs", repo_id="melomba2/soft-elo-table2-reproduction",
                  repo_type="space", path_in_repo="logs",
                  commit_message="Clean run: full run.sh log")
print("space upload done")
PY
else
  echo "PUBLISH!=1: skipping uploads (results live in $WORK/SoftElo/results)"
fi

echo "RUN.SH DONE"
date -u +"%Y-%m-%dT%H:%M:%SZ"
