#!/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_MICROSTRUCTURE_INTERVAL_SECONDS="${UFORIA_MICROSTRUCTURE_INTERVAL_SECONDS:-15}"
export UFORIA_MICROSTRUCTURE_LOOKBACK_HOURS="${UFORIA_MICROSTRUCTURE_LOOKBACK_HOURS:-6}"
export UFORIA_MICROSTRUCTURE_BOOTSTRAP_ON_START="${UFORIA_MICROSTRUCTURE_BOOTSTRAP_ON_START:-0}"
export UFORIA_MICROSTRUCTURE_BOOTSTRAP_LOOKBACK_HOURS="${UFORIA_MICROSTRUCTURE_BOOTSTRAP_LOOKBACK_HOURS:-120}"
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}"

RUNTIME_DIR="$REPO_ROOT/.runtime"
LOCK_DIR="$RUNTIME_DIR/microstructure-inference.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" ]]; then
    echo "Microstructure inference lock already held while another start is initializing." >&2
    exit 0
  fi
  if [[ -n "$existing_pid" ]] && kill -0 "$existing_pid" 2>/dev/null; then
    echo "Microstructure inference already running under PID $existing_pid." >&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

if [[ "${UFORIA_MICROSTRUCTURE_BOOTSTRAP_ON_START}" == "1" ]] && [[ "${UFORIA_MICROSTRUCTURE_BOOTSTRAP_LOOKBACK_HOURS}" != "0" ]]; then
  set +e
  caffeinate -i -m -s uv run uforia-admin microstructure infer-live-once \
    --lookback-hours "$UFORIA_MICROSTRUCTURE_BOOTSTRAP_LOOKBACK_HOURS"
  bootstrap_exit_code=$?
  set -e
  if [[ $bootstrap_exit_code -ne 0 ]]; then
    echo "Microstructure bootstrap catch-up exited with status $bootstrap_exit_code." >&2
  fi
fi

while true; do
  set +e
  caffeinate -i -m -s uv run uforia-admin microstructure infer-live-daemon \
    --interval-seconds "$UFORIA_MICROSTRUCTURE_INTERVAL_SECONDS" \
    --lookback-hours "$UFORIA_MICROSTRUCTURE_LOOKBACK_HOURS"
  exit_code=$?
  set -e
  echo "Microstructure inference exited with status $exit_code, restarting in 2s." >&2
  sleep 2
done
