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

# Self-contained reproducibility pipeline for `g0015_0138_lmu` (18/18 Gates, chi^2/dof = 0.5341)
ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
export PATH="$HOME/.cargo/bin:$HOME/.local/bin:/Library/TeX/texbin:/opt/homebrew/bin:$PATH"

cd "$ROOT_DIR"
echo "=== [1/4] Building Rust + PyO3 Hypergraph Engine (--release) ==="
.venv/bin/maturin develop --release

echo "=== [2/5] Running 22-Test Physics Calibration & Negative-Control Suite ==="
.venv/bin/pytest -v

echo "=== [3/5] Computing 2026-2035 Forward Experimental Predictions (Including Gate 19 Dark Matter) ==="
.venv/bin/toe forward-predictions --output-json runs/real_rule_tournament_v5/g0015_forward_predictions.json

echo "=== [4/5] Generating Publication Vector Figures (paper/figures/*.pdf) ==="
.venv/bin/python paper/generate_figures.py

echo "=== [5/5] Compiling LaTeX Manuscript to paper/main.pdf ==="
cd "$ROOT_DIR/paper"
if command -v pdflatex >/dev/null 2>&1 && command -v bibtex >/dev/null 2>&1; then
  pdflatex -interaction=nonstopmode main.tex
  bibtex main
  pdflatex -interaction=nonstopmode main.tex
  pdflatex -interaction=nonstopmode main.tex
  echo "Compiled paper/main.pdf successfully."
elif command -v tectonic >/dev/null 2>&1; then
  tectonic main.tex
  echo "Compiled paper/main.pdf via tectonic successfully."
else
  echo "Note: pdflatex/tectonic not found on PATH; paper/main.tex and paper/references.bib are ready for Overleaf/arXiv/TeXLive."
fi
