#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""Script to retrieve contributors from GitHub API

Initially generated by ChatGPT (Jan 30 version): https://help.openai.com/en/articles/6825453-chatgpt-release-notes
"""

import requests
import operator

def get_contributors(repo_owner, repo_name):
    url = f"https://api.github.com/repos/{repo_owner}/{repo_name}/stats/contributors"
    contributors = {}

    while url:
        response = requests.get(url, timeout=(3.05, 27))

        if response.status_code != 200:
            raise Exception(f"Failed to retrieve contributors: {response.json()['message']}")

        for contributor in response.json():
            contributions = contributor["weeks"]
            mod_lines = sum([week["d"] + week["a"] for week in contributions])
            contributors[contributor["author"]["login"]] = mod_lines

        if "next" in response.links:
            url = response.links["next"]["url"]
        else:
            url = None

    return sorted(contributors.items(), key=operator.itemgetter(1), reverse=True)

if __name__ == "__main__":
    repo_owner = "librosa"
    repo_name = "librosa"

    contributors = get_contributors(repo_owner, repo_name)
    for contributor, mod_lines in contributors:
        print(f"{contributor:30s}|\t{mod_lines:7d} lines added/deleted")
