#!/usr/bin/env python3
"""Read every page of a list: follow next_cursor, with the same filters, until has_more is false.

Requires Python 3.9+ and requests. Read-only: works with a test or a live key.

    export RELATIONSAI_API_KEY="rai_test_..."
    python3 pagination.py
"""
import os
import sys
from collections import Counter
from datetime import datetime, timedelta, timezone

import requests

api_key = os.environ.get("RELATIONSAI_API_KEY", "")
base_url = os.environ.get("RELATIONSAI_API_BASE", "https://voice-api.relationsai.com/v1").rstrip("/")
session = requests.Session()
session.headers["Authorization"] = f"Bearer {api_key}"


def get(path, params):
    # requests encodes query values correctly, including the "+" of an E.164 number (as %2B).
    r = session.get(f"{base_url}{path}", params=params, timeout=30)
    data = r.json()
    if not r.ok:
        e = data["error"]
        raise RuntimeError(f"{r.status_code} {e['code']} (request {e['request_id']}): {e['message']}")
    return data


def list_all(path, filters=None):
    """Yields every object of a list. The filters stay identical on every page: a cursor is bound to them."""
    cursor = None
    while True:
        params = {**(filters or {}), "limit": 100}
        if cursor:
            params["cursor"] = cursor
        page = get(path, params)
        yield from page["data"]
        if not page["has_more"]:
            return
        cursor = page["next_cursor"]


def main():
    if not api_key.startswith("rai_"):
        raise RuntimeError("Set RELATIONSAI_API_KEY to an API key (rai_test_... or rai_live_...).")
    # Every ended call of the last 24 hours, counted by outcome.
    since = (datetime.now(timezone.utc) - timedelta(hours=24)).isoformat(timespec="milliseconds").replace("+00:00", "Z")
    by_outcome = Counter(call["outcome"] or "unknown" for call in list_all("/calls", {"status": "ended", "created_after": since}))
    print(f"Ended calls since {since}: {sum(by_outcome.values())}")
    for outcome, count in by_outcome.items():
        print(f"  {outcome}: {count}")


if __name__ == "__main__":
    try:
        main()
    except (RuntimeError, requests.RequestException) as err:
        sys.exit(f"Error: {err}")
