# Follow a call until it settles, polling with backoff. Prefer webhooks in production.
# Python 3.9+ with requests.
import os
import random
import sys
import time
from datetime import datetime, timezone

import requests

base = os.environ.get("RELATIONSAI_API_BASE", "https://voice-api.relationsai.com/v1")
call_id = os.environ.get("CALL_ID") or sys.exit("Set CALL_ID to a call id (call_...)")
deadline = time.monotonic() + float(os.environ.get("TIMEOUT_SECONDS", "300"))
headers = {"Authorization": f"Bearer {os.environ['RELATIONSAI_API_KEY']}"}

delay = 2.0
last = ""
while time.monotonic() < deadline:
    r = requests.get(f"{base}/calls/{call_id}", headers=headers, timeout=30)
    if r.status_code in (429, 503):
        time.sleep(float(r.headers.get("Retry-After", "5")))
        continue
    body = r.json()
    if not r.ok:
        err = body["error"]
        sys.exit(f"{err['code']}: {err['message']} (request {err['request_id']})")
    a = body["artifacts"]
    now = (
        f"status={body['status']} outcome={body['outcome']} settled={body['settled']} "
        f"transcript={a['transcript']['state']} recording={a['recording']['state']} analysis={a['analysis']['state']}"
    )
    if now != last:
        print(f"{datetime.now(timezone.utc).isoformat()} {now}", flush=True)
    last = now
    if body["settled"]:
        cost = f"{body['cost']['amount']} {body['cost']['currency']} (minor units)" if body["cost"] else "none"
        print(f"Settled: {body['duration_seconds']}s, {body['billable_minutes']} billable minutes, cost {cost}")
        sys.exit(0)
    # Exponential backoff with jitter, capped at 15 seconds.
    time.sleep(delay * random.uniform(0.8, 1.2))
    delay = min(delay * 1.5, 15.0)

sys.exit(f"{call_id} did not settle in time; it is still being processed, check again later")
