# Download a call's recording to a local file. Python 3.9+ with requests.
import os
import sys

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_...)")

r = requests.get(
    f"{base}/calls/{call_id}/recording",
    headers={"Authorization": f"Bearer {os.environ['RELATIONSAI_API_KEY']}"},
    timeout=30,
)
recording = r.json()
if not r.ok:
    err = recording["error"]
    sys.exit(f"{err['code']}: {err['message']} (request {err['request_id']})")
if recording["state"] != "ready":
    print(f"No recording to download (state={recording['state']})")
    sys.exit(0)

# The link needs no API key and expires at recording["expires_at"]: download it now, do not store it.
out = os.environ.get("OUT_FILE", f"{call_id}.audio")
with requests.get(recording["url"], stream=True, timeout=60) as audio:
    if not audio.ok:
        sys.exit(f"Download failed with {audio.status_code}; read the recording again for a fresh link")
    with open(out, "wb") as f:
        for chunk in audio.iter_content(chunk_size=65536):
            f.write(chunk)
print(f"Saved {out} ({os.path.getsize(out)} bytes, {audio.headers.get('Content-Type')})")
