#!/usr/bin/env bash
# Cubie-native TEP three-wins reproduction script.
# Live-verified at master HEAD e72f742.
set -euo pipefail

REPO="${1:-${HOME}/cubie-math}"
cd "$REPO"

# 1. Build the detector
cargo build --release --package cubie-tep --bin tep_detect

# 2. Build the calibrator (only needed if regenerating thresholds)
cargo build --release --package cubie-tep --bin tep_calibrate_cells

# 3. (Optional) regenerate the V3 adaptive thresholds against d00 baseline.
# Skip this step on a fresh clone — the committed file is correct for V3.
# ./target/release/tep_calibrate_cells data/tep/d00_train.csv \
#     --ewma-lambda 0.2 --layout v3 \
#   | sed 's/ADAPTIVE_PASS_Z:/ADAPTIVE_PASS_Z_VERTEX:/; s/ADAPTIVE_FAIL_Z:/ADAPTIVE_FAIL_Z_VERTEX:/' \
#   > cubie-tep/src/baseline_braatz_adaptive_vertex.rs
# cargo build --release --package cubie-tep --bin tep_detect

# 4. Run the matched-FAR ROC harness
export PYTHONIOENCODING=utf-8
python3 tools/tep_matched_far_roc.py \
    --ewma-lambda 0.2 \
    --adaptive \
    --lo 0.80 --hi 0.83 \
    --target-far 0.01 \
    --wreath off \
    --layout v3

# Expected output (matched-FAR=0% peak):
#
#   Calibrated adaptive scale: k = 0.8150
#   d00 FAR achieved        = 0.000%  (0/960 shatters)
#
#   | Fault  | Trials | Events | FDR     | 95% CI exact         | PCA ref | Verdict |
#   | IDV-3  |    800 |    329 |  41.12% | [37.69%, 44.62%]     |  6.00%  | BEATS PCA |
#   | IDV-9  |    800 |    253 |  31.62% | [28.41%, 34.97%]     |  3.00%  | BEATS PCA |
#   | IDV-15 |    800 |    233 |  29.12% | [26.00%, 32.41%]     | 10.00%  | BEATS PCA |

# 5. (Optional) run the regression tests
cargo test --release --package cubie-tep --test three_wins_regression --test wreath_init_state
