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

ROOT="${ROOT:-$(pwd)}"
OUT_DIR="${OUT_DIR:-DEX_REPORTS/portfolio_router_v4_rolling_dema_health}"
TOTAL_CAPITAL="${TOTAL_CAPITAL:-600}"
FEE_RATES="${FEE_RATES:-metadata}"
PYTHON="${PYTHON:-python3}"

NPZS=(
  "${ROOT}/../base_CHECK_USDC_2PCT_2026_02_05_fee_replay_v2(4).npz"
  "${ROOT}/../base_CHECK_USDC_2PCT_2026_02_05_scaled_may26.npz"
  "${ROOT}/../check_usdc_025_new_2026-04-01_00-00-00Z.npz"
  "${ROOT}/../bio_usdc_apr2026_full_corrected(1).npz"
  "${ROOT}/../bio_usdc_apr_v2.npz"
  "${ROOT}/../bio_usdc_combined_apr17_may3.npz"
  "${ROOT}/../bio_usdc_feb_mar_full(1).npz"
  "${ROOT}/../bio_usdc_feb_mar_v2.npz"
  "${ROOT}/../bio_usdc_may2026_full.npz"
  "${ROOT}/../synd_usdc_apr_full2(1).npz"
  "${ROOT}/../weth_usdc_030_2026_02_05_v1.npz"
  "${ROOT}/../bio_usdc_03_2026-04-01_00-00-00Z.npz"
  "${ROOT}/../rsc_weth_03_2026-04-01_00-00-00Z.npz"
  "${ROOT}/../virtual_weth_005_2026-04-01_00-00-00Z.npz"
)

# Keep only files that exist; server paths may differ.
EXISTING=()
for p in "${NPZS[@]}"; do
  if [[ -f "$p" ]]; then
    EXISTING+=("$p")
  fi
done

if [[ ${#EXISTING[@]} -eq 0 ]]; then
  echo "No NPZ files found. Set ROOT so ROOT/../*.npz points to your uploaded NPZ location." >&2
  exit 2
fi

mkdir -p "$OUT_DIR"
"$PYTHON" dex_platform/backtest/portfolio_router_v4.py \
  --npzs "${EXISTING[@]}" \
  --out-dir "$OUT_DIR" \
  --fee-rates "$FEE_RATES" \
  --routing-mode rolling_v4 \
  --total-capital-usd "$TOTAL_CAPITAL" \
  --lookback-hours 48 \
  --decision-hours 12 \
  --bio-macro-lookback-hours 168 \
  --bio-macro-kill-drift-pct -5 \
  --prewarm-hours 168 \
  --warmup-probe-hours 168 \
  --warmup-max-mdd-pct 12 \
  --warmup-min-pnl-mdd 1.5 \
  --warmup-min-time-in-range-pct 40 \
  --warmup-max-p99-share-pct 10 \
  --dema-enable \
  --dema-fast-hours 48 \
  --dema-slow-hours 168 \
  --dema-slope-hours 24 \
  --dema-min-slow-slope-pct 0 \
  --health-check-enable \
  --health-min-micro-drift-pct -1 \
  --health-probe-enable \
  --health-probe-hours 72 \
  --health-probe-min-return-pct -2 \
  --health-probe-max-mdd-pct 12 \
  --health-probe-min-time-in-range-pct 25 \
  --health-probe-max-p99-share-pct 10

echo "Results: $OUT_DIR"
