#! /usr/bin/env python3

import argparse
import csv
import json
import os

from perceval.backends.core.github import GitHub

# token = ["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"]
# token = ["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"]

# Parse command line arguments
parser = argparse.ArgumentParser(
    description = "Simple parser for GitHub issues and pull requests"
    )
# parser.add_argument("-t", "--token",
#                     '--nargs', nargs='+',
#                     help = "GitHub token")
parser.add_argument("-r", "--repos_csv",
                    help = "CSV with GitHub repositories, with column 'Source code repo' as 'https://github.com/owner/repo'")
args = parser.parse_args()

with open(args.repos_csv) as csv_file:
    reader = csv.reader(csv_file)
    for row in reader:
        # Owner and repository names
        # I remove the first 18 characters for "https://github.com/"
        print(row)
        if not row or not row[5].startswith("https://github.com/"):
            continue
        repo_url = row[5]

        if (repo_url.startswith("https://github.com/")):

            # os.system("python3 github-open-with-error-log.py -t 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 -r EsupPortail/esup-smsu-ap")
            # os.system("python3 github-open-with-error-log.py -t " + args.token[0] + " -r " + repo_url[19:])
            try:
                owner_project = repo_url[19:]
                if owner_project[-1] == "/":
                    owner_project = owner_project[:-1]
                print("python3 github-open-with-error-log.py -r " + owner_project)
                os.system("python3 github-open-with-error-log.py -r " + owner_project)
            except ValueError:
                print("Error: " + repo_url)
