#!/bin/zsh
set -euo pipefail

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

export PATH="/app/.venv/bin:/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}"
export UFORIA_MICROSTRUCTURE_BAR_INTERVAL_SECONDS="${UFORIA_MICROSTRUCTURE_BAR_INTERVAL_SECONDS:-15}"
export UFORIA_MICROSTRUCTURE_BAR_LOOKBACK_MINUTES="${UFORIA_MICROSTRUCTURE_BAR_LOOKBACK_MINUTES:-180}"
UFORIA_BIN="${UFORIA_BIN:-uforia-admin}"

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

if ! "$UFORIA_BIN" microstructure build-live-bars --help >/dev/null 2>&1; then
  echo "Microstructure bar builder requires an admin CLI with 'microstructure build-live-bars'." >&2
  exit 1
fi

while true; do
  END_TS=$(python3 - <<PY
from datetime import datetime, timezone
print(datetime.now(timezone.utc).replace(second=0, microsecond=0).strftime("%Y-%m-%dT%H:%M:00Z"))
PY
)
  START_TS=$(python3 - <<PY
from datetime import datetime, timedelta, timezone
end = datetime.now(timezone.utc).replace(second=0, microsecond=0)
start = end - timedelta(minutes=int("${UFORIA_MICROSTRUCTURE_BAR_LOOKBACK_MINUTES}"))
print(start.strftime("%Y-%m-%dT%H:%M:00Z"))
PY
)

  for ASSET in BTC ETH; do
    "$UFORIA_BIN" microstructure build-live-bars --asset "$ASSET" --start "$START_TS" --end "$END_TS"
  done

  sleep "$UFORIA_MICROSTRUCTURE_BAR_INTERVAL_SECONDS"
done
