# Usage:
# Bash command:
# X_API_KEY=<your-api-key-found-in-copilot-workspace-settings-page> X_API_PASSWORD=<your-api-password> python3 copilot_calls_example.py

# powershell equivalent:
# $env:X_API_KEY = <your-api-key-found-in-copilot-workspace-settings-page>
# $env:X_API_PASSWORD = <your-api-password>
# python3.exe copilot_calls_example.py

# Windows Command Prompt equivalent:
# set X_API_KEY=<your-api-key-found-in-copilot-workspace-settings-page>
# set X_API_PASSWORD=<your-api-password>
# python3.exe copilot_calls_example.py

import os
import time
import json
import requests
import sys
from requests.models import PreparedRequest
from datetime import datetime

max_calls_str = os.getenv("MAX_CALLS", default="500")
MAX_CALLS_TO_FETCH = int(max_calls_str)
MAX_RETRIES = 3

COPILOT_API_BASE = 'https://rest-api.copilot.clari.com'
CALLS_URL = COPILOT_API_BASE + '/calls'
HEADERS = {
    "X-Api-Key": os.getenv("X_API_KEY"),
    "X-Api-Password": os.getenv("X_API_PASSWORD"),
}


def fetch_calls(skip):
    params = {
        'filterStatus': 'POST_PROCESSING_DONE',
        'sortTime': 'desc',
        'skip': skip,
        'includePagination': False,
        # 'filterTimeGt': '2024-05-14T00:00:00Z',
    }
    # sys.stderr.write(f"params: {params}\n")

    req = PreparedRequest()
    req.prepare_url(CALLS_URL, params)
    result = requests.get(req.url, headers=HEADERS)

    time.sleep(0.1)

    if result.status_code != 200:
        raise RuntimeError('Error fetching calls' + str(result.content))

    return json.loads(result.content)


if __name__ == '__main__':

    done = False
    count = 0
    retry = 0
    sys.stderr.write(f"{datetime.now()} fetching {MAX_CALLS_TO_FETCH} calls\n")
    while not done:
        try:
            response = fetch_calls(count)
            calls = response['calls']

            # when there are no more calls being returned.
            if len(calls) == 0:
                sys.stderr.write("No more calls matching the criteria\n")
                done = True

            for call in calls:
                # break on the actual count instead of printing more calls than needed.
                if count >= MAX_CALLS_TO_FETCH:
                    done = True
                    break
                count += 1
                print(f"{call['id']},{call['time']},\"{call['title']}\",{call['metrics']['call_duration']}")

            retry = 0
        except Exception as error:
            sys.stderr.write(f"Caught exception, {error}, \n")
            if retry >= MAX_RETRIES:
                sys.stderr.write("Max retries\n")
                done = True
            else:
                retry += 1
                sys.stderr.write(f"Retry {retry}, after 30s\n")
                time.sleep(30)
