#!/usr/bin/env bash
# Follow a call until it settles, polling with backoff. Prefer webhooks in production. Needs: curl, jq.
set -euo pipefail
BASE="${RELATIONSAI_API_BASE:-https://voice-api.relationsai.com/v1}"
: "${CALL_ID:?Set CALL_ID to a call id (call_...)}"
deadline=$(( $(date +%s) + ${TIMEOUT_SECONDS:-300} ))
delay=2

while [ "$(date +%s)" -lt "$deadline" ]; do
  call=$(curl -sS --fail-with-body --retry 3 "$BASE/calls/$CALL_ID" \
    -H "Authorization: Bearer $RELATIONSAI_API_KEY") || { echo "$call" >&2; exit 1; }
  jq -r '"status=\(.status) outcome=\(.outcome) settled=\(.settled) transcript=\(.artifacts.transcript.state)"' <<<"$call"
  if [ "$(jq -r '.settled' <<<"$call")" = "true" ]; then
    jq -r '"Settled: \(.duration_seconds)s, \(.billable_minutes) billable minutes, cost \(.cost.amount // "none") \(.cost.currency // "")"' <<<"$call"
    exit 0
  fi
  sleep "$delay"
  delay=$(( delay * 2 > 15 ? 15 : delay * 2 ))
done
echo "$CALL_ID did not settle in time; check again later" >&2
exit 1
