# Send a webhook_endpoint.test event to an endpoint and wait for the delivery result. Python 3.9+ with requests.
import os
import sys
import time

import requests

base = os.environ.get("RELATIONSAI_API_BASE", "https://voice-api.relationsai.com/v1")
endpoint_id = os.environ.get("WEBHOOK_ENDPOINT_ID") or sys.exit("Set WEBHOOK_ENDPOINT_ID to an endpoint id (we_...)")
auth = {"Authorization": f"Bearer {os.environ['RELATIONSAI_API_KEY']}"}


def call(method, path, extra=None):
    r = requests.request(method, f"{base}{path}", headers={**auth, **(extra or {})}, timeout=30)
    body = r.json()
    if not r.ok:
        err = body["error"]
        sys.exit(f"{err['code']}: {err['message']} (request {err['request_id']})")
    return body


queued = call("POST", f"/webhook-endpoints/{endpoint_id}/test")
print(f"Queued {queued['id']} for event {queued['event_id']}")

# 202 means the event was accepted for delivery, not that your server received it.
deadline = time.monotonic() + float(os.environ.get("WAIT_SECONDS", "20"))
while time.monotonic() < deadline:
    time.sleep(2)
    page = call("GET", f"/webhook-endpoints/{endpoint_id}/deliveries?limit=20")
    d = next((x for x in page["data"] if x["id"] == queued["id"]), None)
    if d and d["status"] != "pending":
        print(f"{d['id']} {d['status']} attempts={d['attempts']} http={d['response_status']} error={d['error']}")
        sys.exit(0 if d["status"] == "succeeded" else 1)
print("Still pending; check the delivery log again shortly")
