#!/usr/bin/env bash
# Re-seed erp-sandbox to a clean iso-prod checkpoint (ADR-0003). Wraps
# ops/sandbox/sandbox-lifecycle.sh.
#
# DESTRUCTIVE: wipes ALL sandbox data — including the ai_agent_sandbox write user
# and its API key (iso-prod overwrites llx_user with prod's). After it completes
# you MUST re-provision:  arcodange sandbox checkpoint provision
#
#   checkpoint-refresh.sh --yes            # db re-seed + documents (logo) sync
#   checkpoint-refresh.sh --yes --db-only  # db re-seed only (skip documents)
set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
ROOT="${ARCO_ROOT:-$(cd "${SCRIPT_DIR}/../../../.." && pwd)}"
LIFECYCLE="${ROOT}/ops/sandbox/sandbox-lifecycle.sh"
[[ -f "${LIFECYCLE}" ]] || { echo "checkpoint-refresh: missing ${LIFECYCLE}" >&2; exit 1; }

MODE="refresh"; YES=0
while [[ $# -gt 0 ]]; do
  case "$1" in
    --yes) YES=1; shift ;;
    --db-only) MODE="refresh-from-prod"; shift ;;
    *) echo "checkpoint-refresh: unknown arg '$1'" >&2; exit 2 ;;
  esac
done

if [[ "${YES}" != "1" ]]; then
  cat >&2 <<EOF
checkpoint-refresh: this WIPES all erp-sandbox data and re-seeds iso-prod from prod.
  - the ai_agent_sandbox write user + its key are wiped → you re-provision after
  - prod is read ONLY (structural guarantee, ADR-0003); only the sandbox is written
Re-run with --yes to proceed. Then: arcodange sandbox checkpoint provision
EOF
  exit 3
fi

echo ">>> re-seeding erp-sandbox (${MODE}) — ~2-3 min (scale-down, pg_dump prod, restore, scale-up)"
bash "${LIFECYCLE}" "${MODE}"
echo
echo ">>> iso-prod checkpoint restored. The write agent was wiped — bring it back with:"
echo "      arcodange sandbox checkpoint provision"
