#!/usr/bin/env bash
# Re-provision the ai_agent_sandbox write user after a refresh, then relink the
# write skill .env. Runs the Playwright POC (test/provisionSandbox.ts): it opens a
# browser — YOU complete the admin login.
#
# IMPORTANT: the sandbox is iso-prod, so log in with the PROD admin credentials.
# Those come from test/.env.sandbox (DOLI_ADMIN_LOGIN / DOLI_ADMIN_PASSWORD) — make
# sure they are prod's. The POC re-grants the agent's rights (incl. banque lire) and
# writes the new key to test/.ai_agent_sandbox.key.
set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
ROOT="${ARCO_ROOT:-$(cd "${SCRIPT_DIR}/../../../.." && pwd)}"
POC="${ROOT}/test/provisionSandbox.ts"

command -v deno >/dev/null || { echo "checkpoint-provision: deno not found (https://deno.land)" >&2; exit 1; }
[[ -f "${POC}" ]] || { echo "checkpoint-provision: missing ${POC}" >&2; exit 1; }
[[ -f "${ROOT}/test/.env.sandbox" ]] || echo "checkpoint-provision: WARN no test/.env.sandbox (admin creds) — login may fail" >&2

echo ">>> launching provisionSandbox.ts — complete the admin login in the browser (use PROD admin creds)"
( cd "${ROOT}/test" && deno run --allow-all provisionSandbox.ts )

# Scoped agents (test/scopes.ts). A refresh wipes every user, so they are
# re-created here rather than granted by hand — the 2026-07 failure where a
# refresh silently dropped hand-granted rights and nothing recorded it.
if [[ -f "${ROOT}/test/provisionAiUser.ts" ]]; then
  for scope in read sandbox-write; do
    echo ">>> provisioning scoped sandbox agent: ${scope}"
    ( cd "${ROOT}/test" \
      && DOLIBARR_ADDRESS="${DOLIBARR_SANDBOX_URL:-https://erp-sandbox.arcodange.lab}" \
         deno run --allow-all provisionAiUser.ts --scope "${scope}" --env sandbox ) \
      || echo "   WARN: scoped provisioning failed for '${scope}' — check test/scopes.ts" >&2
  done
fi

echo ">>> provisioning finished; relinking the write skill .env"
exec "${SCRIPT_DIR}/checkpoint-relink-env.sh"
