#!/bin/zsh
set -euo pipefail

REPO_ROOT="$(cd "$(dirname "$0")/.." && pwd)"
cd "$REPO_ROOT"

export PATH="/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:$PATH"
export UFORIA_DATA_ROOT="${UFORIA_DATA_ROOT:-$REPO_ROOT/data}"
export UFORIA_DB_ENABLED="${UFORIA_DB_ENABLED:-true}"
export UFORIA_DB_DSN="${UFORIA_DB_DSN:-postgresql:///uforia?user=$USER}"
export UFORIA_DB_READ_MODE="${UFORIA_DB_READ_MODE:-db}"
export UFORIA_DB_WRITE_MODE="${UFORIA_DB_WRITE_MODE:-db}"
UFORIA_BIN="${UFORIA_BIN:-uforia}"

RUNTIME_DIR="$REPO_ROOT/.runtime"
LOCK_DIR="$RUNTIME_DIR/refresh-hot.lock"
mkdir -p "$RUNTIME_DIR"

if mkdir "$LOCK_DIR" 2>/dev/null; then
  echo "$$" > "$LOCK_DIR/pid"
else
  existing_pid="$(cat "$LOCK_DIR/pid" 2>/dev/null || true)"
  if [[ -z "$existing_pid" ]] || kill -0 "$existing_pid" 2>/dev/null; then
    echo "Hot refresh already running." >&2
    exit 0
  fi
  rm -rf "$LOCK_DIR"
  mkdir "$LOCK_DIR" 2>/dev/null || exit 0
  echo "$$" > "$LOCK_DIR/pid"
fi

cleanup() {
  if [[ -f "$LOCK_DIR/pid" ]] && [[ "$(cat "$LOCK_DIR/pid" 2>/dev/null || true)" = "$$" ]]; then
    rm -rf "$LOCK_DIR"
  fi
}

trap cleanup EXIT INT TERM

HOT_LOOKBACK_HOURS="${UFORIA_REFRESH_HOT_LOOKBACK_HOURS:-24}"
HOT_TS=$(python3 - <<PY
from datetime import datetime, timezone
ts = datetime.now(timezone.utc).replace(second=0, microsecond=0)
print(ts.strftime("%Y-%m-%dT%H:%M:00Z"))
PY
)
HOT_HOURLY_TS=$(python3 - <<PY
from datetime import datetime, timedelta, timezone
ts = datetime.now(timezone.utc).replace(minute=0, second=0, microsecond=0) - timedelta(hours=1)
print(ts.strftime("%Y-%m-%dT%H:00:00Z"))
PY
)
HOT_START=$(python3 - <<PY
from datetime import datetime, timedelta, timezone
end = datetime.now(timezone.utc).replace(second=0, microsecond=0)
start = end - timedelta(hours=int("${HOT_LOOKBACK_HOURS}"))
print(start.strftime("%Y-%m-%dT%H:%M:00Z"))
PY
)
PERPS_HOT_LOOKBACK_HOURS="${UFORIA_REFRESH_HOT_PERPS_LOOKBACK_HOURS:-6}"
PERPS_HOT_START=$(python3 - <<PY
from datetime import datetime, timedelta, timezone
end = datetime.now(timezone.utc).replace(second=0, microsecond=0)
start = end - timedelta(hours=int("${PERPS_HOT_LOOKBACK_HOURS}"))
print(start.strftime("%Y-%m-%dT%H:%M:00Z"))
PY
)

for UNDERLYING in BTC ETH; do
  "$UFORIA_BIN" ingest deribit-dvol --underlying "$UNDERLYING" --start "$HOT_START" --end "$HOT_TS" || true
  "$UFORIA_BIN" ingest deribit-funding --underlying "$UNDERLYING" --start "$HOT_START" --end "$HOT_TS" || true
  "$UFORIA_BIN" build vol-index --underlying "$UNDERLYING" --source dvol --start "$HOT_START" --end "$HOT_TS" || true
  "$UFORIA_BIN" build rvvix --underlying "$UNDERLYING" --source dvol --start "$HOT_START" --end "$HOT_TS" || true
  "$UFORIA_BIN" build qvvix --underlying "$UNDERLYING" --source dvol --ts "$HOT_HOURLY_TS" || true
  "$UFORIA_BIN" build razor --underlying "$UNDERLYING" --start "$HOT_START" --end "$HOT_TS" || true

  "$UFORIA_BIN" build surface-features --underlying "$UNDERLYING" --start "$HOT_START" --end "$HOT_TS" || true
  "$UFORIA_BIN" build options-surface --underlying "$UNDERLYING" --start "$HOT_START" --end "$HOT_TS" || true
  "$UFORIA_BIN" build options-carry --underlying "$UNDERLYING" --start "$HOT_START" --end "$HOT_TS" || true
  "$UFORIA_BIN" build options-skew --underlying "$UNDERLYING" --start "$HOT_START" --end "$HOT_TS" || true
  "$UFORIA_BIN" build options-dislocations --underlying "$UNDERLYING" --start "$HOT_START" --end "$HOT_TS" || true
  "$UFORIA_BIN" build options-positioning --underlying "$UNDERLYING" --start "$HOT_START" --end "$HOT_TS" || true
  "$UFORIA_BIN" build vol-cone --underlying "$UNDERLYING" --start "$HOT_START" --end "$HOT_TS" || true
  "$UFORIA_BIN" build term-structure-momentum --underlying "$UNDERLYING" --start "$HOT_START" --end "$HOT_TS" || true
  "$UFORIA_BIN" build gamma-exposure --underlying "$UNDERLYING" --start "$HOT_START" --end "$HOT_TS" || true
  "$UFORIA_BIN" build funding-context --underlying "$UNDERLYING" --start "$HOT_START" --end "$HOT_TS" || true
  "$UFORIA_BIN" build straddle-breakeven --underlying "$UNDERLYING" --start "$HOT_START" --end "$HOT_TS" || true
  "$UFORIA_BIN" build surface-factor-rv --underlying "$UNDERLYING" --start "$HOT_START" --end "$HOT_TS" || true
  "$UFORIA_BIN" build ml-carry-toxicity --underlying "$UNDERLYING" --start "$HOT_START" --end "$HOT_TS" || true
  "$UFORIA_BIN" build expiry-flow-map --underlying "$UNDERLYING" --start "$HOT_START" --end "$HOT_TS" || true
  "$UFORIA_BIN" build adaptive-hedging --underlying "$UNDERLYING" --start "$HOT_START" --end "$HOT_TS" || true
  "$UFORIA_BIN" build sessionality-clocks --underlying "$UNDERLYING" --start "$HOT_START" --end "$HOT_TS" || true
  "$UFORIA_BIN" build funding-basis-skew --underlying "$UNDERLYING" --start "$HOT_START" --end "$HOT_TS" || true
  "$UFORIA_BIN" build options-signals --underlying "$UNDERLYING" --start "$HOT_START" --end "$HOT_TS" || true
  "$UFORIA_BIN" build vol-regime-transitions --underlying "$UNDERLYING" --start "$HOT_START" --end "$HOT_TS" || true

  "$UFORIA_BIN" build perps-signals --asset "$UNDERLYING" --start "$PERPS_HOT_START" --end "$HOT_TS" || true
  "$UFORIA_BIN" build perps-composites --asset "$UNDERLYING" --start "$PERPS_HOT_START" --end "$HOT_TS" || true
  "$UFORIA_BIN" build perps-transitions --asset "$UNDERLYING" --start "$PERPS_HOT_START" --end "$HOT_TS" || true

  "$UFORIA_BIN" build composite --asset "$UNDERLYING" --start "$HOT_START" --end "$HOT_TS" || true
  "$UFORIA_BIN" build composite-components --asset "$UNDERLYING" --start "$HOT_START" --end "$HOT_TS" || true
  "$UFORIA_BIN" build composite-transitions --asset "$UNDERLYING" --start "$HOT_START" --end "$HOT_TS" || true
done

"$UFORIA_BIN" build options-rv --start "$HOT_START" --end "$HOT_TS" || true
"$UFORIA_BIN" build btc-eth-dispersion --start "$HOT_START" --end "$HOT_TS" || true
