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

PROJECT_ROOT="${PROJECT_ROOT:-$(pwd)}"
cd "$PROJECT_ROOT"

SLEEP_S="${SLEEP_S:-900}"
TARGET_NPZ="${TARGET_NPZ:-DEX_DATA/fast_npz/bio_usdc_fresh_paper_live_fee_replay_v2.npz}"

mkdir -p DEX_REPORTS/paper_live_bio_macro_router_v1 DEX_DATA/fast_npz/_tmp

while true; do
  TS="$(date -u +%Y%m%dT%H%M%SZ)"
  TMP_NPZ="DEX_DATA/fast_npz/_tmp/bio_usdc_fresh_paper_live_fee_replay_v2_${TS}.npz"
  LOG="DEX_REPORTS/paper_live_bio_macro_router_v1/update_real_${TS}.log"

  echo "[update] ${TS} tmp=${TMP_NPZ}"

  if DRY_RUN=0 OUT_NPZ="$TMP_NPZ" bash scripts/run_bio_usdc_fresh_event_update_v1.sh 2>&1 | tee "$LOG"; then
    if [[ -s "$TMP_NPZ" ]]; then
      cp "$TARGET_NPZ" "${TARGET_NPZ}.bak_${TS}" 2>/dev/null || true
      mv "$TMP_NPZ" "$TARGET_NPZ"
      stat -c '[updated] %y %s %n' "$TARGET_NPZ"
    else
      echo "[error] tmp npz not created: $TMP_NPZ"
    fi
  else
    echo "[error] update command failed"
  fi

  sleep "$SLEEP_S"
done
