import requests
import Apikeys
import pandas as pd

apiKey = Apikeys.doximity_internal


def get_email():
    error_list = []
    df = pd.read_csv("/Users/normrasmussen/Downloads/doximity.csv")
    for row in df.itertuples():
        email = row[1]
        email = email.lower()
        group_id = row[2]
        group_id = group_id.replace("'", "")
        get_uuid(email, group_id, apiKey, error_list)
        # print(f"Email: {email} & Group: {group_id}")
    print(error_list)


def get_uuid(email, group_id, apiKey, error_list):
    count = 0
    url = f"https://api.northpass.com/v2/people?filter[email][eq]={email}"
    headers = {
        "accept": "*/*",
        "x-api-key": apiKey,
        "content-type": "application/json",
    }
    try:
        count += 1
        print(f"Row: {count}, email: {email}")
        response = requests.get(url, headers=headers)
        data = response.json()
        try:
            uuid = data["data"][0]["id"]
            add_to_group(apiKey, uuid, group_id)
        except IndexError as e:
            print(f"Error, Index, {e}")
            error_list.append(email)
            pass
        response.raise_for_status()
    except requests.HTTPError as ex:
        print(f"Error getting the uuid!! Details - {ex}")
        raise ex
    except requests.Timeout:
        print("Timeout error")
    finally:
        pass


def add_to_group(apiKey, uuid, group_id):
    print(f"Adding uuid {uuid}  to group {group_id}")
    url = f"https://api.northpass.com/v2/groups/{group_id}/relationships/people"
    payload = {"data": [{"type": "people", "id": uuid}]}
    headers = {
        "accept": "application/json",
        "content-type": "application/json",
        "X-Api-Key": apiKey,
    }
    try:
        response = requests.post(url, json=payload, headers=headers)
        print(response.status_code)
        response.raise_for_status()
    except requests.HTTPError as ex:
        print(f"Error adding to group!! Details - {ex}")
        raise ex
    except requests.Timeout:
        print("Timeout error")


if __name__ == "__main__":
    get_email()
