import requests
import pandas as pd
import Apikeys

csv = "/Users/normrasmussen/Downloads/client-learners.csv"
apiKey = Apikeys.wildhealth_edportal
baseUrlemail = "https://api.northpass.com/v2/people?filter[email][eq]="


def readcsv(csv, apiKey, baseUrlemail):
    emails = []
    data = pd.read_csv(csv)
    emails.extend(data["email"].tolist())
    getfromEmail(emails, baseUrlemail, apiKey, data)


def getfromEmail(emails, baseUrlemail, apiKey, data):
    email_ids = {}
    errors = []
    for email in emails:
        url = baseUrlemail + f"{email}"
        headers = {
            "accept": "*/*",
            "x-api-key": apiKey,
            "content-type": "application/json",
        }
        response = requests.get(url, headers=headers)
        if response.status_code == 200:
            response = response.json()
            try:
                uuid = response["data"][0]["id"]
                print(uuid)
                email_ids.update({email: uuid})
            except Exception as e:
                errors.append(email)
                pass
        else:
            print("Another Error!")

    data["uuid"] = data["email"].map(email_ids)
    data.dropna(how="any", inplace=True)
    assignProps(data, apiKey)
    errorstoCsv(errors)


def errorstoCsv(errors):
    errorcsv = pd.DataFrame(errors)
    errorcsv.to_csv(
        path_or_buf="/Users/normrasmussen/Downloads/Emails_Not_Northpass.csv",
        index=False,
    )


def assignProps(data, apiKey):
    for row in data.itertuples():
        print(row)
        ts_id = row[2]
        ts_role = row[3]
        uuid = row[4]
        url = "https://api.northpass.com/v2/properties/people/bulk"
        payload = {
            "data": [
                {
                    "type": "person_properties",
                    "attributes": {
                        "properties": {"user_id": ts_id, "role_type": ts_role}
                    },
                    "id": uuid,
                }
            ]
        }
        headers = {
            "accept": "application/json",
            "content-type": "application/json",
            "X-Api-Key": apiKey,
        }
        response = requests.post(url, json=payload, headers=headers)
        print(response)


if __name__ == "__main__":
    readcsv(csv, apiKey, baseUrlemail)
