#!/usr/bin/env bash
# provision-token — mint (idempotently) a scoped API token on this deployment.
#
# Resolve-or-create the self-host user, mint a (bot,tx) token, and print ONLY the token on stdout so
# it pipes straight into the command that needs it.
#
# Usage (the operator runs it — it needs the stack's ADMIN_TOKEN, the same secret the stack signs with):
#   ADMIN_TOKEN=<admin-secret> ADMIN_API_URL=http://127.0.0.1:<ADMIN_API_PORT> \
#     deploy/compose/bin/provision-token
#   → vxa_...                                   # the scoped token, nothing else, on stdout
#
#   or, from deploy/compose, letting the Makefile read the port out of .env:
#   make -s provision-token ADMIN_TOKEN=<admin-secret>
#
# Env knobs:
#   ADMIN_TOKEN     (required) the stack admin secret (X-Admin-API-Key).
#   ADMIN_API_URL   (required) admin-api's base. THERE IS NO DEFAULT, and that is a correctness
#                   rule rather than tidiness: this script does not READ from admin-api, it
#                   CREATES A USER and MINTS A SCOPED (bot,tx) TOKEN. On a host that runs more
#                   than one stack, a default of 127.0.0.1:18057 is a DIFFERENT DEPLOYMENT — so
#                   the failure is not a wrong answer, it is a real account with a live token on
#                   somebody else's stack, handed to the operator as though it were theirs.
#                   Same class as F111; `make provision-token` supplies it from the deployment's
#                   own .env, which is where a deployment default belongs.
#   EMAIL           the self-host user's email (default self-host@vexa.ai) — stable, so reruns reuse it.
#   SCOPES          comma scopes (default bot,tx — bots + transcript reads; the dashboard needs both).
#   MAX_BOTS        max_concurrent_bots on create (default 5).
set -euo pipefail

: "${ADMIN_API_URL:?is required -- admin-api base for THIS stack, on the port THIS deployment publishes (ADMIN_API_PORT in its .env). No default, deliberately: a host-port default addresses whatever else is listening on this machine, and this script does not read, it MINTS A TOKEN. From deploy/compose the Makefile fills it in: make -s provision-token ADMIN_TOKEN=...}"
ADMIN_API="${ADMIN_API_URL%/}"
EMAIL="${EMAIL:-self-host@vexa.ai}"
SCOPES="${SCOPES:-bot,tx}"
MAX_BOTS="${MAX_BOTS:-5}"
: "${ADMIN_TOKEN:?set ADMIN_TOKEN (the stack admin secret the stack signs with)}"

H=(-H "X-Admin-API-Key: ${ADMIN_TOKEN}")
_id() { python3 -c 'import sys,json;print(json.load(sys.stdin)["id"])'; }
_tok() { python3 -c 'import sys,json;print(json.load(sys.stdin)["token"])'; }

# Resolve-or-create the user (admin-api's create is itself idempotent: existing email → 200 + the row).
uid="$(curl -fsS "${H[@]}" "${ADMIN_API}/admin/users/email/${EMAIL}" 2>/dev/null | _id 2>/dev/null || true)"
if [ -z "${uid}" ]; then
  uid="$(curl -fsS "${H[@]}" -H 'Content-Type: application/json' \
        -d "{\"email\":\"${EMAIL}\",\"max_concurrent_bots\":${MAX_BOTS}}" \
        "${ADMIN_API}/admin/users" | _id)"
fi

# Mint a fresh scoped token for that user (tokens are additive; old ones keep working until deleted).
curl -fsS "${H[@]}" -X POST "${ADMIN_API}/admin/users/${uid}/tokens?scopes=${SCOPES}" | _tok
