from perceval.backends.core.github import GitHub, CATEGORY_REPO
import json
import os
import os.path

token = [""]

directory = "repos_info"

for filename in os.listdir("."):
    if not filename.endswith(".json"):
        continue

    with open(filename) as jsonfile:
        parsed_json = json.load(jsonfile)
        for repo in parsed_json["items"]:
            repo_url = repo["html_url"]
            if (repo_url.startswith("https://github.com/")):
                try:
                    owner_project = repo_url[19:]
                except ValueError:
                    print("Error: " + repo_url)
                    continue
                if owner_project[-1] == "/":
                    owner_project = owner_project[:-1]
                owner, repository = owner_project.split('/')

                if os.path.isfile("{}/{}_{}_repoinfo.json".format(directory, owner, repository)):
                    continue
                print(owner, repository)
                try:
                    repo_api = GitHub(owner=owner, repository=repository, api_token=token)
                    for item in repo_api.fetch(category=CATEGORY_REPO):
                        json.dump(item, open("{}/{}_{}_repoinfo.json".format(directory, owner, repository), "w"), indent=4)
                except:
                    print("Error: " + repo_url)
