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

pp = pprint.PrettyPrinter(indent=4)
APIKEY = Apikeys.KARBON
HEADERS = {
    "accept": "application/json",
    "X-Api-Key": APIKEY,
}
BASEURL = "https://api.northpass.com/v2/"
IMPORTFILE = "/Users/normrasmussen/Downloads/karbon-invite-users.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.
    """
    groups_list = []
    df = pd.DataFrame()
    data = pd.read_csv(IMPORTFILE)
    df2 = data[[ "email", "customer_name", "customer_id" ]].copy()
    customer_ids = df2["customer_id"].unique()
    customer_ids = list(customer_ids)
    for row in df2.itertuples():
        groupname = f"{row[2]}--{row[3]}"
        groups_list.append(groupname)

    for customer in customer_ids:
        payload = ""
        tmp_group = data[data['customer_id'] == customer]
        people = list(tmp_group["email"])
        cust = str(tmp_group["customer_id"].unique())[2:-2]
        url = f"{BASEURL}bulk/people"
        payload_1 = []
        for group in groups_list:
            for person in people:
                if cust in group:
                    miniload = {"email": person, "groups": group}
                    payload_1.append(miniload)
        print(f"The {group} payload has {len(payload_1)}")
        payload = {"data": {"attributes": {"people": payload_1}}}
        print(payload)
        response = requests.post(url, headers=HEADERS, json=payload)
        print(f"Completed. Status code is {response.status_code}")
        print(response.text)

if __name__ == "__main__":
    bulk_invite_and_group()
