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

SCRIPT_VERSION="watch_paper_live_bio_v4_tuned_2026_05_05"
echo "[script_version] $0 SCRIPT_VERSION=${SCRIPT_VERSION}"

# Virtual LP watchdog only. It never signs transactions.
# It reruns paper_live_virtual_lp_v1.py when the input NPZ changes.

NPZ="${NPZ:-DEX_DATA/fast_npz/bio_usdc_may2026_full.npz}"
OUT_DIR="${OUT_DIR:-DEX_REPORTS/paper_live_virtual_lp_bio_v4_tuned_watch}"
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
    echo "[run] $(date -u +%Y-%m-%dT%H:%M:%SZ) npz=${NPZ} sig=${SIG}"
    "${PYTHON}" dex_platform/scripts/paper_live_virtual_lp_v1.py \
      --npz "${NPZ}" \
      --out-dir "${OUT_DIR}" \
      --append-events \
      --fee-rates metadata \
      --routing-mode rolling_v4 \
      --total-capital-usd 600 \
      --lookback-hours 48 \
      --decision-hours 24 \
      --max-current-liquidity-share-pct 10 \
      --bio-micro-min-drift-pct 0 \
      --bio-micro-min-trend-ratio 0 \
      --bio-macro-lookback-hours 720 \
      --bio-macro-kill-drift-pct 0 \
      --bio-bull-min-fee-budget-pct-day 0.05 \
      --bio-bull-max-toxicity 1 \
      --check-bear-max-drift-pct -999 \
      --check-bear-min-fee-budget-pct-day 999 \
      --prewarm-hours 24 \
      --warmup-probe-hours 24 \
      --warmup-min-span-fraction 0.4 \
      --warmup-min-return-pct -5 \
      --warmup-max-mdd-pct 8 \
      --warmup-min-pnl-mdd 0 \
      --warmup-min-time-in-range-pct 0 \
      --warmup-max-p99-share-pct 10 \
      --warmup-max-max-share-pct 25 \
      --dema-enable \
      --dema-fast-hours 12 \
      --dema-slow-hours 48 \
      --dema-slope-hours 12 \
      --dema-min-slow-slope-pct -0.5 \
      --dema-no-fast-above-slow \
      --health-check-enable \
      --health-min-micro-drift-pct -20 \
      --no-reentry-after-exit \
      --health-max-total-dd-pct 2 \
      --strict-mdd-pct 20 \
      --min-pnl-mdd 2 \
      --max-p99-liquidity-share-pct 10 \
      --max-liquidity-share-pct 25
    LAST_SIG="${SIG}"
  else
    echo "[idle] $(date -u +%Y-%m-%dT%H:%M:%SZ) unchanged npz=${NPZ}"
  fi

  sleep "${SLEEP_S}"
done
