#!/usr/bin/env bash
# Design-partner runbook, step 1: register the protocol BEFORE the dataset is built.
# The protocol fixes the labels, metrics, comparators and margins the results are
# judged against. Set TESSERA_PROTOCOL_BODY to the path of the JSON body you
# agreed with the partner (see the runbook page for its shape).
#
# The Idempotency-Key is derived from the request body, so the same body is
# the same request (a safe retry) and a changed body is a new protocol. Set
# TESSERA_IDEMPOTENCY_SALT to register a second protocol with an identical body.
set -euo pipefail

: "${TESSERA_API_BASE:?e.g. https://api.staging.tessera.zone/v1}"
: "${TESSERA_API_KEY:?the tsk_ key of the partner project}"
: "${TESSERA_PROTOCOL_BODY:?path to the agreed protocol JSON body}"
: "${TESSERA_STATE_DIR:?set by the runner; ids are handed between steps}"
AUTH=(-H "Authorization: Bearer $TESSERA_API_KEY")

KEY="docs-partner-protocol-$(python3 -c '
import hashlib, os, sys
body = open(sys.argv[1], "rb").read()
salt = os.environ.get("TESSERA_IDEMPOTENCY_SALT", "").encode()
print(hashlib.sha256(body + salt).hexdigest()[:24])
' "$TESSERA_PROTOCOL_BODY")"

if ! PROTOCOL="$(curl -sS --fail-with-body -X POST "$TESSERA_API_BASE/protocols" "${AUTH[@]}" \
  -H "Content-Type: application/json" \
  -H "Idempotency-Key: $KEY" \
  --data-binary "@$TESSERA_PROTOCOL_BODY")"; then
  echo "registering the protocol failed:" >&2
  printf '%s\n' "$PROTOCOL" >&2
  exit 1
fi
printf '%s' "$PROTOCOL" | python3 -c '
import json, sys
protocol = json.load(sys.stdin)
print("protocol_id:", protocol["protocol_id"])
print("provenance:", protocol["provenance"])
print("protocol_fingerprint:", protocol["protocol_fingerprint"])
print("declared_at:", protocol["declared_at"])
' | tee "$TESSERA_STATE_DIR/protocol.txt"
printf '%s' "$PROTOCOL" | python3 -c 'import json,sys; print(json.load(sys.stdin)["protocol_id"])' \
  > "$TESSERA_STATE_DIR/protocol_id"
