#!/bin/sh
# Runs a Crumple crash test from CI and fails the build when the agent is not ready.
# Needs curl and jq. Settings come from environment variables; see tether.wamasoda.com/docs/production.
set -eu

: "${CRUMPLE_API_KEY:?Set CRUMPLE_API_KEY}"
BASE="${CRUMPLE_BASE_URL:-https://tether.wamasoda.com}"
SUITE="${CRUMPLE_SUITE:-full}"
REPS="${CRUMPLE_REPETITIONS:-3}"
MIN="${CRUMPLE_MIN_SCORE:-85}"
FAIL_ON_HARM="${CRUMPLE_FAIL_ON_HARM:-true}"

call() {
  out=$(curl -sS -X "$1" "$BASE$2" -H "authorization: Bearer $CRUMPLE_API_KEY" -H "content-type: application/json" ${3:+-d "$3"})
  err=$(printf '%s' "$out" | jq -r '.error.message // empty')
  if [ -n "$err" ]; then echo "Crumple: $err" >&2; exit 2; fi
  printf '%s' "$out" | jq '.data'
}

VERSION_ID="${CRUMPLE_AGENT_VERSION_ID:-}"
if [ -z "$VERSION_ID" ]; then
  : "${CRUMPLE_AGENT_ID:?Set CRUMPLE_AGENT_VERSION_ID, or CRUMPLE_AGENT_ID and CRUMPLE_MODEL}"
  : "${CRUMPLE_MODEL:?Set CRUMPLE_MODEL}"
  PROMPT=""
  if [ -n "${CRUMPLE_SYSTEM_PROMPT_FILE:-}" ]; then PROMPT=$(cat "$CRUMPLE_SYSTEM_PROMPT_FILE"); fi
  body=$(jq -n --arg p "${CRUMPLE_PROVIDER:-anthropic}" --arg m "$CRUMPLE_MODEL" --arg k "${CRUMPLE_MODEL_KEY_ID:-}" \
    --arg s "$PROMPT" --arg n "${CRUMPLE_VERSION_NOTES:-CI ${GITHUB_SHA:-${CI_COMMIT_SHA:-}}}" \
    '{provider:$p, model:$m, modelKeyId:(if $k=="" then null else $k end), systemPrompt:(if $s=="" then null else $s end), notes:$n} | with_entries(select(.value != null or .key == "modelKeyId"))')
  VERSION_ID=$(call POST "/api/v1/agents/$CRUMPLE_AGENT_ID/versions" "$body" | jq -r '.versionId')
  echo "Registered a new agent version: $VERSION_ID"
fi

RUN_ID=$(call POST /api/v1/tests "$(jq -n --arg v "$VERSION_ID" --arg s "$SUITE" --argjson r "$REPS" '{agentVersionId:$v, suiteId:$s, repetitions:$r}')" | jq -r '.runId')
echo "Crash test $RUN_ID started ($SUITE, x$REPS)"

while :; do
  p=$(call POST "/api/v1/tests/$RUN_ID/step")
  status=$(printf '%s' "$p" | jq -r '.status')
  echo "$(printf '%s' "$p" | jq -r '"\(.done)/\(.total) episodes"')"
  case "$status" in done|failed|cancelled) break ;; esac
  if [ "$(printf '%s' "$p" | jq -r '.last // empty')" = "" ]; then sleep 2; fi
done

summary=$(call GET "/api/v1/tests/$RUN_ID")
printf '%s' "$summary" | jq -r '"Score \(.score // "none") (\(.verdict // "no verdict")). Report: \(.reportUrl)"'
printf '%s' "$summary" | jq -r '(.anomalies // [])[] | "  \(.type): \(.title). \(.summary)"'
printf '%s' "$summary" | jq -r '(.recommendations // [])[] | "  [\(.priority)] \(.title)"'

score=$(printf '%s' "$summary" | jq -r '.score // -1')
harm=$(printf '%s' "$summary" | jq -r '.counts.harm // 0')
if [ "$status" != "done" ] || [ "$(jq -n --argjson s "$score" --argjson m "$MIN" '$s < $m')" = "true" ]; then
  echo "Crash test failed: score below $MIN or the run did not finish." >&2; exit 1
fi
if [ "$FAIL_ON_HARM" = "true" ] && [ "$harm" -gt 0 ]; then
  echo "Crash test failed: $harm episodes caused harm." >&2; exit 1
fi
echo "Crash test passed."
