import requests
import pprint
import pandas as pd
import Apikeys
import time

pp = pprint.PrettyPrinter(indent=4)
APIKEY = Apikeys.CHUBB
HEADERS = {
    "accept": "application/json",
    "X-Api-Key": APIKEY,
}
BASEURL = "https://api.northpass.com/v2/"
IMPORTFILE = "/Users/normrasmussen/Downloads/CISA OLC users 031626-032726.csv"


def bulk_invite_and_group():
    """
    Bulk endpoint which invites new people and adds them to a group via this structure:
    {
    "email": "me@mac.com"
    "groups": "GroupA"
    }

    This function looks for the group in the CSV as well.
    """
    data = pd.read_csv(IMPORTFILE)
    groups = data["Group"].unique()
    groups = list(groups)
    print("Here are all groups within the CSV:")
    print(groups)
    print(" ")
    for group in groups:
        payload = ""
        print(group)
        tmp_group = data[data.Group == group]
        people = list(tmp_group["Email"])
        group = str(tmp_group["Group"].unique())[2:-2]
        print(f"Group --> {group} ...  Amount of People --> {len(people)}")
        url = f"{BASEURL}bulk/people"
        if len(people) > 1500:
            for chunk in range(0, len(people), 1500):
                i = chunk
                payload_1 = []
                i_to_add = people[i : i + 1500]
                for person in i_to_add:
                    miniload = {"email": person, "groups": group}
                    payload_1.append(miniload)
                print(f"The long length {group} payload has {len(payload_1)}")
                payload = {"data": {"attributes": {"people": payload_1}}}
                response = requests.post(url, headers=HEADERS, json=payload)
                print(f"Completed. Status code is {response.status_code}")
        else:
            payload_1 = []
            for person in people:
                miniload = {"email": person, "groups": group}
                payload_1.append(miniload)
            print(f"The {group} payload has {len(payload_1)}")
            payload = {"data": {"attributes": {"people": payload_1}}}
            response = requests.post(url, headers=HEADERS, json=payload)
            print(f"Completed. Status code is {response.status_code}")
            print(response.text)
        print("Running add props from func...")
        time.sleep(3)
        add_props_from_func(people, data, group)


def add_props_from_func(people, data, group):
    errorlist = []
    for learner_email in people:
        agency_name = data.loc[data["Email"] == learner_email, "AgencyName"]
        agname = str(agency_name.values)[2:-2]
        print(f"Learner: {learner_email} --> Agency: {agname} from Group: {group}")
        ppl_search = f"{BASEURL}people?filter[email][eq]={learner_email}"
        ppl_response = requests.get(ppl_search, headers=HEADERS)
        try:
            ppl_data = ppl_response.json()
            nextlink = ppl_data["links"]
            learner_uuid = ppl_data["data"][0]["id"]

            # Now update the props
            prop_url = f"{BASEURL}properties/people/bulk"
            payload = {
                "data": [
                    {
                        "attributes": {"properties": {"agency_name": agname}},
                        "id": learner_uuid,
                        "type": "person_properties",
                    }
                ]
            }
            propresponse = requests.post(prop_url, json=payload, headers=HEADERS)
            if propresponse.status_code != 200:
                error_tupe = (learner_uuid, learner_email, agname)
                errorlist.append(error_tupe)
            else:
                print(f"Looks like {learner_email} and {agname} was successful. Received status code: {propresponse.status_code}.")
        except (TypeError, IndexError) as e:
            error_tupe = (0, learner_email, agency_name)
            errorlist.append(error_tupe)
            print(f"{e} has occurred with {learner_email}")
        finally:
            pass
    print(f"Error list: {errorlist}")


def add_props_from_csv():
    errorlist = []
    data = pd.read_csv(IMPORTFILE)
    for dat in data.iterrows():
        agency_name = dat[1][3]
        # agency_name = "EMPLOYEE"
        learner_email = dat[1][2]
        ppl_search = f"{BASEURL}people?filter[email][eq]={learner_email}"
        ppl_response = requests.get(ppl_search, headers=HEADERS)
        try:
            ppl_data = ppl_response.json()
            learner_uuid = ppl_data["data"][0]["id"]

            # Now update the props
            prop_url = f"{BASEURL}properties/people/bulk"
            payload = {
                "data": [
                    {
                        "attributes": {"properties": {"agency_name": agency_name}},
                        "id": learner_uuid,
                        "type": "person_properties",
                    }
                ]
            }
            propresponse = requests.post(prop_url, json=payload, headers=HEADERS)
            print(propresponse.status_code)
            if propresponse.status_code != 200:
                error_tupe = (learner_uuid, learner_email, agency_name)
                errorlist.append(error_tupe)
            else:
                print(f"Looks like {learner_email} and {agency_name} was successful.")
        except TypeError as e:
            print(e)
            pass
        finally:
            print(f"Error list: {errorlist}")


if __name__ == "__main__":
    bulk_invite_and_group()
