import requests
import pandas as pd
from pathlib import Path
import os

basefile = "/Users/normrasmussen/Downloads/MizunoCompletions_with_PGAIDs.csv"
api_key = "stXNF84HWL8aCGeRjHEo2rJ1U"
uuid_url = "https://api.northpass.com/v2/people?filter[email][eq]="
group_url = "https://api.northpass.com/v2/groups/"
headers = {
    "accept": "*/*",
    "x-api-key": api_key,
    "content-type": "application/json",
}

def load_file(basefile):
    row_dict = {}
    dict_list = []
    basefile = Path(basefile)
    completions = pd.read_csv(basefile)
    try:
        if os.path.isfile(basefile):
            print(f"File found! Importing {basefile}")
            for email in completions.itertuples():
                row_num = email[0]
                row_dict = {"row_num": row_num}
                email = email[3]
                url = uuid_url + f"{email}"
                response = requests.get(url, headers=headers)
                if response.status_code == 200:
                    response = response.json()
                    gid = response["data"][0]["relationships"]["groups"]["data"][0]["id"]
                    url2 = group_url + f"{gid}"
                    response = requests.get(url2, headers=headers)
                    data = response.json()
                    group_name = data["data"]["attributes"]["name"]
                    row_dict["group"] = group_name
                dict_list.append(row_dict)
    except TypeError as e:
        pass
    finally:
        for info in dict_list:
            row = info['row_num']
            group = info['group']
            completions.loc[completions.index[row], "Group Name"] = group
        print(completions)
        completions.to_csv(
                "/Users/normrasmussen/Downloads/MizunoCompletions_with_PGAIDs.csv",
                index=False
                )


if __name__ == "__main__":
    load_file(basefile)
