# Change a contact safely: read its ETag, send it in If-Match, and re-read on a conflict.
# Python 3.9+ with requests.
import os
import sys

import requests

base = os.environ.get("RELATIONSAI_API_BASE", "https://voice-api.relationsai.com/v1")
contact_id = os.environ.get("CONTACT_ID") or sys.exit("Set CONTACT_ID to a contact id (ct_...)")
auth = {"Authorization": f"Bearer {os.environ['RELATIONSAI_API_KEY']}"}


def fail(body):
    err = body["error"]
    sys.exit(f"{err['code']}: {err['message']} (request {err['request_id']})")


for attempt in range(3):
    read = requests.get(f"{base}/contacts/{contact_id}", headers=auth, timeout=30)
    contact = read.json()
    if not read.ok:
        fail(contact)
    etag = read.headers["ETag"]

    # Decide the change from what you just read.
    change = {"name": contact["name"] or "Asha Rao", "language": "hi"}

    r = requests.patch(
        f"{base}/contacts/{contact_id}",
        headers={**auth, "If-Match": etag},
        json=change,
        timeout=30,
    )
    body = r.json()
    if r.ok:
        print(f"Updated {body['id']}: language={body['language']}, new ETag {r.headers.get('ETag')}")
        sys.exit(0)
    if body["error"]["code"] != "version_conflict":
        fail(body)
    print("The contact changed since it was read; reading it again")

sys.exit("Gave up after repeated conflicts")
