# Catch anything your webhook handler missed: list recent calls and sync the settled ones
# that your system has not recorded yet. Run it on a schedule, for example hourly. Python 3.9+ with requests.
import json
import os
import sys
import time
from datetime import datetime, timedelta, timezone

import requests

base = os.environ.get("RELATIONSAI_API_BASE", "https://voice-api.relationsai.com/v1")
since = os.environ.get("SINCE") or (datetime.now(timezone.utc) - timedelta(hours=24)).isoformat(timespec="milliseconds").replace("+00:00", "Z")
# Stand-in for your database: the call ids you have already written back.
store_file = os.environ.get("SYNC_STORE", "./synced-calls.json")
synced = set()
if os.path.exists(store_file):
    with open(store_file) as f:
        synced = set(json.load(f))
headers = {"Authorization": f"Bearer {os.environ['RELATIONSAI_API_KEY']}"}

cursor = None
checked = added = 0
while True:
    params = {"limit": 100, "created_after": since, "status": "ended", **({"cursor": cursor} if cursor else {})}
    r = requests.get(f"{base}/calls", params=params, headers=headers, timeout=30)
    if r.status_code == 429:
        time.sleep(float(r.headers.get("Retry-After", "5")))
        continue  # same cursor, same filters
    page = r.json()
    if not r.ok:
        err = page["error"]
        sys.exit(f"{err['code']}: {err['message']} (request {err['request_id']})")
    for call in page["data"]:
        checked += 1
        if not call["settled"] or call["id"] in synced:
            continue  # not final yet, or already synced
        print(f"sync {call['id']} record={call['metadata'].get('crm_record_id', '-')} outcome={call['outcome']}")
        synced.add(call["id"])
        added += 1
    if not page["has_more"]:
        break
    cursor = page["next_cursor"]

with open(store_file, "w") as f:
    json.dump(sorted(synced), f)
print(f"checked {checked} ended calls since {since}, synced {added} new")
