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

basefile = "/Users/normrasmussen/Downloads/talkspace-paid-learners.csv"
api_key = Apikeys.talkspace_1099
prop_url = "https://api.northpass.com/v2/properties/people/"
headers = {
        "accept": "*/*",
        "x-api-key": api_key,
        "content-type": "application/json",
        }
dict_list = []
row_dict = {}

def load_file(basefile):
    basefile = Path(basefile)
    completions = pd.read_csv(basefile)
    try:
        if os.path.isfile(basefile):
            print(f"File found! Importing {basefile}")
            for uuid in completions.itertuples():
                row_num = uuid[0]
                uuid = uuid[2]
                row_dict = {"row_num":row_num}
                url = prop_url + f"{uuid}"
                response = requests.get(url, headers=headers)
                if response.status_code == 200:
                    data = response.json()
                    company = data["data"]["attributes"]["properties"]["company"]
                    row_dict["company"] = company
                elif response.status_code == 404:
                    row_dict["company"] = "User Not Found"
                dict_list.append(row_dict)
        print("No errors! Passing along the dictionary!")
    except KeyError as e:
        print(e)
    finally:
        for info in dict_list:
            print(info)
            row = info['row_num']
            comp = info['company']
            completions.loc[completions.index[row], "Company"] = comp
        print(completions)
        completions.to_csv(
                "/Users/normrasmussen/Downloads/client_learners_w_Company.csv",
                index=False
                )

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

