#!/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-admin}"
REFRESH_SCOPE="${UFORIA_REFRESH_SCOPE:-all}"

if ! command -v "$UFORIA_BIN" >/dev/null 2>&1; then
  echo "Hourly refresh requires '$UFORIA_BIN' on PATH." >&2
  exit 1
fi

if ! "$UFORIA_BIN" build --help >/dev/null 2>&1; then
  echo "Hourly refresh requires an admin CLI with 'build' commands. Current binary: $UFORIA_BIN" >&2
  exit 1
fi

case "$REFRESH_SCOPE" in
  all|options|derived) ;;
  *)
    echo "Invalid UFORIA_REFRESH_SCOPE: $REFRESH_SCOPE (expected all, options, or derived)" >&2
    exit 1
    ;;
esac

START=$(python3 - <<'PY'
from datetime import datetime, timedelta, timezone
end = datetime.now(timezone.utc).replace(minute=0, second=0, microsecond=0)
start = end - timedelta(days=3)
print(start.strftime("%Y-%m-%dT%H:00:00Z"))
PY
)

END=$(python3 - <<'PY'
from datetime import datetime, timezone
end = datetime.now(timezone.utc).replace(minute=0, second=0, microsecond=0)
print(end.strftime("%Y-%m-%dT%H:00:00Z"))
PY
)

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
)

START_DATE=$(python3 - <<'PY'
from datetime import datetime, timedelta, timezone
end = datetime.now(timezone.utc).replace(minute=0, second=0, microsecond=0)
start = end - timedelta(days=3)
print(start.date().isoformat())
PY
)

END_DATE=$(python3 - <<'PY'
from datetime import datetime, timezone
print(datetime.now(timezone.utc).date().isoformat())
PY
)

run_options_for_underlying() {
  local underlying="$1"
  local lower_underlying
  lower_underlying=$(printf '%s' "$underlying" | tr '[:upper:]' '[:lower:]')
  "$UFORIA_BIN" ingest deribit-dvol --underlying "$underlying" --start "$START" --end "$END"
  "$UFORIA_BIN" ingest deribit-funding --underlying "$underlying" --start "$START" --end "$END"
  "$UFORIA_BIN" build vol-index --underlying "$underlying" --source dvol --start "$START" --end "$END"
  "$UFORIA_BIN" build rvvix --underlying "$underlying" --source dvol --start "$START" --end "$END"
  "$UFORIA_BIN" build surface-features --underlying "$underlying" --start "$START" --end "$END" || true
  "$UFORIA_BIN" build qvvix --underlying "$underlying" --source dvol --ts "$TS" || true
  "$UFORIA_BIN" build razor --underlying "$underlying" --start "$START" --end "$END" || true
  "$UFORIA_BIN" build options-surface --underlying "$underlying" --start "$START" --end "$END" || true
  "$UFORIA_BIN" build options-carry --underlying "$underlying" --start "$START" --end "$END" || true
  "$UFORIA_BIN" build options-skew --underlying "$underlying" --start "$START" --end "$END" || true
  "$UFORIA_BIN" build options-dislocations --underlying "$underlying" --start "$START" --end "$END" || true
  "$UFORIA_BIN" build options-positioning --underlying "$underlying" --start "$START" --end "$END" || true
  "$UFORIA_BIN" build vol-cone --underlying "$underlying" --start "$START" --end "$END" || true
  "$UFORIA_BIN" build term-structure-momentum --underlying "$underlying" --start "$START" --end "$END" || true
  "$UFORIA_BIN" build gamma-exposure --underlying "$underlying" --start "$START" --end "$END" || true
  "$UFORIA_BIN" build funding-context --underlying "$underlying" --start "$START" --end "$END" || true
  "$UFORIA_BIN" build straddle-breakeven --underlying "$underlying" --start "$START" --end "$END" || true
  "$UFORIA_BIN" build surface-factor-rv --underlying "$underlying" --start "$START" --end "$END" || true
  "$UFORIA_BIN" build ml-carry-toxicity --underlying "$underlying" --start "$START" --end "$END" || true
  "$UFORIA_BIN" build expiry-flow-map --underlying "$underlying" --start "$START" --end "$END" || true
  "$UFORIA_BIN" build adaptive-hedging --underlying "$underlying" --start "$START" --end "$END" || true
  "$UFORIA_BIN" build sessionality-clocks --underlying "$underlying" --start "$START" --end "$END" || true
  "$UFORIA_BIN" build funding-basis-skew --underlying "$underlying" --start "$START" --end "$END" || true
  "$UFORIA_BIN" build options-signals --underlying "$underlying" --start "$START" --end "$END" || true
  "$UFORIA_BIN" build vol-regime-transitions --underlying "$underlying" --start "$START" --end "$END" || true
  "$UFORIA_BIN" validate vol-suite --underlying "$underlying" --start "$START" --end "$END" > "$REPO_ROOT/data/validation-${lower_underlying}-latest.json" || true
  "$UFORIA_BIN" validate options-family --underlying "$underlying" --start "$START" --end "$END" > "$REPO_ROOT/data/options-validation-${lower_underlying}-latest.json" || true
}

run_derived_for_underlying() {
  local underlying="$1"
  "$UFORIA_BIN" build perps-signals --asset "$underlying" --start "$START" --end "$END" || true
  "$UFORIA_BIN" build perps-composites --asset "$underlying" --start "$START" --end "$END" || true
  "$UFORIA_BIN" build perps-transitions --asset "$underlying" --start "$START" --end "$END" || true
  "$UFORIA_BIN" build composite --asset "$underlying" --start "$START" --end "$END" || true
  "$UFORIA_BIN" build composite-components --asset "$underlying" --start "$START" --end "$END" || true
  "$UFORIA_BIN" build composite-transitions --asset "$underlying" --start "$START" --end "$END" || true
}

compact_datasets() {
  local dataset
  for dataset in "$@"; do
    "$UFORIA_BIN" maintenance compact --dataset "$dataset" --start-date "$START_DATE" --end-date "$END_DATE" || true
  done
}

for UNDERLYING in BTC ETH; do
  if [[ "$REFRESH_SCOPE" == "all" || "$REFRESH_SCOPE" == "options" ]]; then
    run_options_for_underlying "$UNDERLYING"
  fi
  if [[ "$REFRESH_SCOPE" == "all" || "$REFRESH_SCOPE" == "derived" ]]; then
    run_derived_for_underlying "$UNDERLYING"
  fi
done

if [[ "$REFRESH_SCOPE" == "all" || "$REFRESH_SCOPE" == "options" ]]; then
  "$UFORIA_BIN" build options-rv --start "$START" --end "$END" || true
  "$UFORIA_BIN" build btc-eth-dispersion --start "$START" --end "$END" || true

  compact_datasets \
    dvol_snapshot \
    funding_rate_snapshot \
    vol_index_series \
    vvix_series \
    surface_features \
    razor_series \
    options_surface_snapshot \
    options_carry_series \
    options_skew_series \
    options_dislocation_series \
    options_relative_value_series \
    options_positioning_series \
    options_signal_series \
    vol_cone_series \
    term_structure_momentum_series \
    gamma_exposure_series \
    funding_context_series \
    straddle_breakeven_series \
    vol_regime_transition_series
fi

if [[ "$REFRESH_SCOPE" == "all" || "$REFRESH_SCOPE" == "derived" ]]; then
  compact_datasets \
    perps_signal_series \
    perps_composite_series \
    perps_transition_series \
    composite_signal_series \
    composite_component_series \
    composite_transition_series
fi
