#!/usr/bin/env bash
# Quickstart step 7 — bundle the model, create a slot, activate, batch score.
set -euo pipefail

: "${TESSERA_API_BASE:?e.g. https://api.staging.tessera.zone/v1}"
: "${TESSERA_API_KEY:?your tsk_test_… key}"
: "${TESSERA_STATE_DIR:=.}"
AUTH=(-H "Authorization: Bearer $TESSERA_API_KEY")
MODEL_ID="$(cat "$TESSERA_STATE_DIR/model_id")"

# --- 1. promotion bundle: pins every artifact by fingerprint ------------------
# Optional, explicit acknowledgement after reviewing this model's evaluation.
# The registry still refuses blocking gates and rechecks the exact advisory set.
MODEL="$(curl -sS "$TESSERA_API_BASE/models/$MODEL_ID" "${AUTH[@]}")"
BODY="$(printf '%s' "$MODEL" | python3 -c '
import json, os, sys
model = json.load(sys.stdin)
promotion = model.get("promotion") or {}
verdict = promotion.get("verdict")
raw = os.environ.get("TESSERA_QUICKSTART_ACKNOWLEDGEMENT", "")
ack = json.loads(raw) if raw else None
if raw and (
    not isinstance(ack, dict) or set(ack) != {"gates", "reason"}
    or not isinstance(ack["gates"], list) or not ack["gates"]
    or not all(isinstance(gate, str) for gate in ack["gates"])
    or not isinstance(ack["reason"], str) or not ack["reason"].strip()
):
    raise SystemExit("Acknowledgement must contain gate IDs and a non-empty reason")
if verdict == "promotable":
    print("{}")
elif verdict == "needs_acknowledgement":
    # No input means no consent: let the API return its refusal and request ID.
    # The operator names the advisory gates they accept; the bundle acknowledges
    # those that are failing now, and the API refuses any failing gate left out.
    gates = [gate for gate in (ack or {}).get("gates", []) if gate in promotion.get("advisory", [])]
    print(json.dumps({"acknowledge_gates": {"gates": gates, "reason": ack["reason"]}} if gates else {}))
else:
    raise SystemExit("Promotion is blocked or unavailable; inspect the model and evaluation")
')"
BUNDLE="$(curl -sS -X POST "$TESSERA_API_BASE/models/$MODEL_ID/bundles" "${AUTH[@]}" \
  -H "Content-Type: application/json" \
  -H "Idempotency-Key: quickstart-bundle" -d "$BODY")"
BUNDLE_ID="$(printf '%s' "$BUNDLE" | python3 -c '
import json, sys
bundle = json.load(sys.stdin)
if not bundle.get("bundle_id"):
    raise SystemExit("Bundle creation failed: " + json.dumps(bundle, sort_keys=True))
print(bundle["bundle_id"])
')"
printf '%s' "$BUNDLE" | python3 -c '
import json, sys
bundle = json.load(sys.stdin)
print("bundle %s pins contract v%s" % (bundle["bundle_id"], bundle["pins"]["contract_version"]))
'

# --- 2. a deployment slot: the stable name scores are served under ------------
SLOT="$(curl -sS -X POST "$TESSERA_API_BASE/slots" "${AUTH[@]}" \
  -H "Content-Type: application/json" \
  -H "Idempotency-Key: quickstart-slot" \
  -d '{
    "environment": "test",
    "name": "quickstart",
    "entity_type": "user",
    "mode": "live",
    "scoring": "batch_only"
  }')"
SLOT_ID="$(printf '%s' "$SLOT" | python3 -c 'import json,sys; print(json.load(sys.stdin)["slot_id"])')"

# --- 3. activate: re-verifies every pinned fingerprint before serving ---------
ACTIVATED="$(curl -sS -X POST "$TESSERA_API_BASE/slots/$SLOT_ID:activate" "${AUTH[@]}" \
  -H "Content-Type: application/json" \
  -d '{"bundle_id": "'"$BUNDLE_ID"'"}')"
printf '%s' "$ACTIVATED" | python3 -c '
import json, sys
slot = json.load(sys.stdin)
print("slot %s: active_bundle_id=%s" % (slot["name"], slot["active_bundle_id"]))
'

# --- 4. batch score every user as of the sample window's end ------------------
REFRESH="$(curl -sS -X POST "$TESSERA_API_BASE/slots/quickstart/refreshes" "${AUTH[@]}" \
  -H "Content-Type: application/json" \
  -H "Idempotency-Key: quickstart-refresh" \
  -d '{"cutoff": "2025-07-01T00:00:00Z"}')"
REFRESH_ID="$(printf '%s' "$REFRESH" | python3 -c 'import json,sys; print(json.load(sys.stdin)["refresh_id"])')"

for _ in $(seq 1 600); do
  REFRESH="$(curl -sS "$TESSERA_API_BASE/slots/quickstart/refreshes/$REFRESH_ID" "${AUTH[@]}")"
  STATUS="$(printf '%s' "$REFRESH" | python3 -c 'import json,sys; print(json.load(sys.stdin)["status"])')"
  case "$STATUS" in succeeded|failed) break ;; esac
  sleep 2
done
printf '%s' "$REFRESH" | python3 -c '
import json, sys
refresh = json.load(sys.stdin)
print(json.dumps({k: refresh[k] for k in ("refresh_id", "status", "entities_scored", "cutoff")}, indent=2))
'
