#!/usr/bin/env bash
# Download a call's recording to a local file. 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_...)}"

recording=$(curl -sS --fail-with-body "$BASE/calls/$CALL_ID/recording" \
  -H "Authorization: Bearer $RELATIONSAI_API_KEY") || { echo "$recording" >&2; exit 1; }

state=$(jq -r '.state' <<<"$recording")
if [ "$state" != "ready" ]; then
  echo "No recording to download (state=$state)"
  exit 0
fi
# The link needs no API key and expires at .expires_at: download it now, do not store it.
out="${OUT_FILE:-$CALL_ID.audio}"
curl -sS --fail -o "$out" "$(jq -r '.url' <<<"$recording")"
echo "Saved $out ($(wc -c <"$out" | tr -d ' ') bytes), link expired at $(jq -r '.expires_at' <<<"$recording")"
