# Register a webhook endpoint for the key's mode. Prints the signing secret once. Python 3.9+ with requests.
import json
import os
import sys

import requests

base = os.environ.get("RELATIONSAI_API_BASE", "https://voice-api.relationsai.com/v1")
url = os.environ.get("WEBHOOK_URL") or sys.exit("Set WEBHOOK_URL to your public HTTPS endpoint")

r = requests.post(
    f"{base}/webhook-endpoints",
    headers={
        "Authorization": f"Bearer {os.environ['RELATIONSAI_API_KEY']}",
    },
    json={
        "url": url,
        "description": "CRM sync",
        "events": ["call.ended", "call.settled", "campaign.completed"],
    },
    timeout=30,
)
endpoint = r.json()
if not r.ok:
    err = endpoint["error"]
    sys.exit(f"{err['code']}: {err['message']} {json.dumps(err['details'])} (request {err['request_id']})")
print(f"Created {endpoint['id']} livemode={endpoint['livemode']} events={','.join(endpoint['events'])}")
# Shown only in this response: put it in your secret store now.
print(f"Signing secret: {endpoint['secret']}")
