#!/usr/bin/env bash
# List + fetch call recordings from a CodeB tenant.
# European Digital Identity Wallet-enabled tenants use the same key surface.
# [compliance-archive-cookbook 2026-07-23]
#
# Auth: Bearer ak_... (mint at api-keys-admin.html) OR admin OIDC bearer.
# Endpoints:
#   GET /signal.ashx?recordings-list=1
#   GET /signal.ashx?recording=<callId>&download=1
set -euo pipefail

: "${CODEB_TENANT:?export CODEB_TENANT=https://phone.example.tld}"
: "${CODEB_API_KEY:?export CODEB_API_KEY=ak_...}"
OUT_DIR="${OUT_DIR:-./codeb-recordings}"
mkdir -p "$OUT_DIR"

# 1) List recordings (newest first, capped at 500 items server-side).
curl -sSf \
  -H "Authorization: Bearer ${CODEB_API_KEY}" \
  "${CODEB_TENANT}/signal.ashx?recordings-list=1" \
  -o "$OUT_DIR/index.json"

# 2) Extract callId list with jq and download each WAV.
jq -r '.items[].callId // empty' "$OUT_DIR/index.json" | while read -r CID; do
  [ -n "$CID" ] || continue
  echo "[fetch] $CID"
  curl -sSf \
    -H "Authorization: Bearer ${CODEB_API_KEY}" \
    "${CODEB_TENANT}/signal.ashx?recording=${CID}&download=1" \
    -o "$OUT_DIR/${CID}.wav"
done

echo "[done] items in $OUT_DIR"
