#!/usr/bin/env bash
set -euo pipefail
# Static/periodic replay watcher for CHECK. Virtual validation only. Never signs transactions.
PROJECT_ROOT="${PROJECT_ROOT:-$PWD}"
cd "$PROJECT_ROOT"
NPZ="${NPZ:-DEX_DATA/fast_npz/base_CHECK_USDC_2PCT_2026_02_05_fee_replay_v2.npz}"
OUT_DIR="${OUT_DIR:-DEX_REPORTS/paper_live_check_static_85_0p5_336h_v1}"
SLEEP_S="${SLEEP_S:-900}"
PYTHON="${PYTHON:-python3}"
mkdir -p "$OUT_DIR"
LAST_SIG=""
while true; do
  if [[ ! -s "$NPZ" ]]; then echo "[wait] missing NPZ: $NPZ"; sleep "$SLEEP_S"; continue; fi
  SIG="$(stat -c '%Y:%s' "$NPZ")"
  if [[ "$SIG" != "$LAST_SIG" ]]; then
    RUN_DIR="$OUT_DIR/run_$(date -u +%Y%m%dT%H%M%SZ)"
    echo "[run] $(date -u +%Y-%m-%dT%H:%M:%SZ) CHECK static paper-replay npz=$NPZ out=$RUN_DIR"
    "$PYTHON" dex_platform/backtest/cl_fee_replay_fast_npz_v3.py       --npz "$NPZ" --out-dir "$RUN_DIR"       --fee-rates metadata_0_2515:0.002515       --time-from "${TIME_FROM:-2026-02-01T00:00:00Z}" --time-to "${TIME_TO:-2026-05-01T00:00:00Z}"       --strategies 'periodic_85_0.5_336h:85:0.5:336'       --capital-mode grid --capital-grid "${CAPITAL_GRID:-25}"       --max-avg-liquidity-share-pct 3 --max-p95-liquidity-share-pct 5 --max-p99-liquidity-share-pct 10 --max-liquidity-share-pct 25       --target-mdd-pct 20 --w-mdd 2 --top-n 10 --jobs "${JOBS:-4}" --fast-core
    ln -sfn "$RUN_DIR" "$OUT_DIR/latest"
    LAST_SIG="$SIG"
  else
    echo "[idle] $(date -u +%Y-%m-%dT%H:%M:%SZ) unchanged npz=$NPZ"
  fi
  sleep "$SLEEP_S"
done
