# shellcheck shell=bash

_okstra_ctl_prepare() {
  okstra_central_bootstrap
  local home; home="$(okstra_central_home)"
  if [[ "${OKSTRA_CTL_SKIP_BACKFILL:-0}" != "1" ]]; then
    if ! OKSTRA_STATE_PATH="$home/state.json" python3 -c '
import json, os, sys
from pathlib import Path
state = Path(os.environ["OKSTRA_STATE_PATH"])
data = json.loads(state.read_text()) if state.is_file() else {}
sys.exit(0 if data.get("backfilledAt") else 1)
'; then
      _okstra_ctl_reindex >/dev/null 2>&1 || true
    fi
  fi
  if [[ "${OKSTRA_CTL_SKIP_RECONCILE:-0}" == "1" ]]; then
    return 0
  fi
  OKSTRA_HOME_RESOLVED="$home" \
  OKSTRA_CTL_LIB_DIR="$SCRIPT_DIR" \
  python3 - <<'PY'
import os, sys
sys.path.insert(0, os.environ["OKSTRA_CTL_LIB_DIR"])
from pathlib import Path
from okstra_ctl import reconcile_active, reconcile_recent
home = Path(os.environ["OKSTRA_HOME_RESOLVED"])
reconcile_active(home)
reconcile_recent(home)
PY
}
