#!/usr/bin/env bash
# Change a contact safely with If-Match. Needs: curl, jq.
set -euo pipefail
BASE="${RELATIONSAI_API_BASE:-https://voice-api.relationsai.com/v1}"
: "${CONTACT_ID:?Set CONTACT_ID to a contact id (ct_...)}"

# Read the contact and keep its ETag header.
etag=$(curl -sS --fail-with-body -D - -o /dev/null "$BASE/contacts/$CONTACT_ID" \
  -H "Authorization: Bearer $RELATIONSAI_API_KEY" | tr -d '\r' | awk -F': ' 'tolower($1)=="etag" {print $2}') ||
  { echo "Could not read $CONTACT_ID" >&2; exit 1; }
echo "ETag: $etag"

# A 412 version_conflict means someone changed it in between: read again and reapply.
contact=$(curl -sS --fail-with-body -X PATCH "$BASE/contacts/$CONTACT_ID" \
  -H "Authorization: Bearer $RELATIONSAI_API_KEY" \
  -H "If-Match: $etag" \
  -H "Content-Type: application/json" \
  -d '{"language": "hi"}') || { echo "$contact" >&2; exit 1; }
jq -r '"Updated \(.id): language=\(.language)"' <<<"$contact"
