#!/usr/bin/env bash
# Create a test-mode campaign with three recipients and start it. Needs: curl, jq.
# Every request runs, so the script looks for its campaign by name first: running it again never
# creates a second campaign or starts one twice.
set -euo pipefail
BASE="${RELATIONSAI_API_BASE:-https://voice-api.relationsai.com/v1}"
AGENT_ID="${AGENT_ID:-agent_1ZltiWzxrXmMprGD6q63}" # the test-mode Sample agent unless you set your own
NAME="${CAMPAIGN_NAME:-November renewals (test)}"
if [[ "${RELATIONSAI_API_KEY:-}" != rai_test_* ]]; then
  echo "Run this example with a test key (rai_test_...): it calls the test-mode numbers +1202555010x." >&2
  exit 2
fi
# Consent is recorded only with CONSENT_GRANTED=true: set it only if your workspace requires consent
# and, for real people, only when they really agreed to be called.
CONSENT=$([ "${CONSENT_GRANTED:-}" = "true" ] && echo ',"consent_granted":true' || true)

api() { # method, path, [JSON body]
  local out
  out=$(curl -sS --fail-with-body -X "$1" "$BASE$2" -H "Authorization: Bearer $RELATIONSAI_API_KEY" \
    ${3:+-H "Content-Type: application/json" -d "$3"}) || { echo "$1 $2: $out" >&2; return 1; }
  echo "$out"
}

# Already created by an earlier run? (Newest first; one page is enough for this example.)
campaign=$(api GET "/campaigns?limit=100" | jq --arg n "$NAME" '[.data[] | select(.name == $n)][0] // empty')

if [ -z "$campaign" ]; then
  # Recipients are contacts (an upsert is safe to repeat): these test numbers answer, do not answer, talk longer.
  ids=()
  for phone in +12025550100 +12025550101 +12025550105; do
    contact=$(api POST /contacts/upsert "{\"phone_number\":\"$phone\"$CONSENT}")
    ids+=("$(jq -r '.id' <<<"$contact")")
  done
  campaign=$(api POST /campaigns "$(jq -n --arg name "$NAME" --arg agent "$AGENT_ID" \
    '{name: $name, agent_id: $agent, concurrency_limit: 2, contact_ids: $ARGS.positional}' --args "${ids[@]}")")
  echo "Created $(jq -r '.id' <<<"$campaign") status=$(jq -r '.status' <<<"$campaign")"
fi

# Start only a draft: starting a finished campaign again would call everyone again.
if [ "$(jq -r '.status' <<<"$campaign")" != "draft" ]; then
  jq -r '"Already \(.status) \(.id): not starting it again"' <<<"$campaign"
  exit 0
fi
started=$(api POST "/campaigns/$(jq -r '.id' <<<"$campaign")/start")
jq -r '"Started \(.id) status=\(.status) run=\(.run_number) recipients=\(.recipient_count)"' <<<"$started"
