# Create or update the contact with this phone number. 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 = {
    "phone_number": os.environ.get("PHONE", "+12025550100"),
    "name": "Asha Rao",
    "language": "en",
}
# Set CONSENT_GRANTED=true only when the person really agreed to be called: it is recorded as their consent.
if os.environ.get("CONSENT_GRANTED") == "true":
    contact["consent_granted"] = True

r = requests.post(
    f"{base}/contacts/upsert",
    headers={
        "Authorization": f"Bearer {os.environ['RELATIONSAI_API_KEY']}",
    },
    json=contact,
    timeout=30,
)
body = r.json()
if not r.ok:
    err = body["error"]
    sys.exit(f"{err['code']}: {err['message']} (request {err['request_id']})")
print(f"{'Created' if r.status_code == 201 else 'Updated'} {body['id']}")
print(f"phone={body['phone_number']} consent={body['consent_granted']} do_not_call={body['do_not_call']}")
