import requests
import pandas as pd
import Apikeys

baseCsv = "/Users/normrasmussen/Downloads/Incomplete list of Users.csv"
baseUrl = "https://api.northpass.com/v2/people/"
baseUrlname = "https://api.northpass.com/v2/people?filter[name][eq]="
baseUrlemail = "https://api.northpass.com/v2/people?filter[email][eq]="
apikey = Apikeys.client


def getfromEmail(baseUrlemail, baseCsv, apiKey):
    uuids = []
    errors = []
    emails = pd.read_csv(baseCsv, usecols=["EMAIL"])
    emails = emails["EMAIL"].to_list()
    for email in emails:
        email = email.rstrip()
        url = baseUrlemail + f"{email}"
        headers = {
            "accept": "*/*",
            "x-api-key": apiKey,
            "content-type": "application/json",
        }
        response = requests.get(url, headers=headers)
        json = response.json()
        try:
            uuid = json["data"][0]["id"]
            uuids.append(uuid)
        except Exception as e:
            # print(email)
            errors.append(email)
            # print(str(e))
            # print(response.text)
            pass
    # print(uuids)
    print(errors)
    addtoGroup(apiKey, uuids)


def addtoGroup(apiKey, uuids):
    number = 0
    for x in uuids:
        url = f"https://api.northpass.com/v2/people/{x}/relationships/groups"
        payload = {
            "data": [
                {
                    "type": "membership-groups",
                    "id": "7b5e5417-bc9f-454a-89a1-347c04225e03",
                }
            ]
        }
        headers = {
            "accept": "application/json",
            "content-type": "application/json",
            "X-Api-Key": apiKey,
        }
        response = requests.post(url, json=payload, headers=headers)
        # print(response)
        try:
            number += 1
            pass
        except Exception as e:
            print(str(e))
            print(response.text)
            print(x)
            pass
        finally:
            print(f"{number} people added to the group!")


if __name__ == "__main__":
    getfromEmail(baseUrlemail, baseCsv, apiKey)
