#!/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_MS_CONFIG="${UFORIA_MS_CONFIG:-$REPO_ROOT/engines/microstructure/config/default.toml}"
export UFORIA_MS_MODE="${UFORIA_MS_MODE:-paper}"
export RUST_LOG="${RUST_LOG:-info}"

RUNTIME_DIR="$REPO_ROOT/.runtime"
LOCK_DIR="$RUNTIME_DIR/microstructure-live.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 live engine 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 live engine 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

while true; do
  set +e
  caffeinate -i -m -s cargo run -p uforia-ms-app -- --config "$UFORIA_MS_CONFIG" run --mode "$UFORIA_MS_MODE"
  exit_code=$?
  set -e
  echo "Microstructure live engine exited with status $exit_code, restarting in 2s." >&2
  sleep 2
done
