import requests
import sys
import pandas as pd
import Apikeys

# Enter your API Key between the quotation marks.
apiKey = ""
groupName = sys.argv[1]
peopleCsv = "/path/to/file/peopletogroups.csv"


def createGroup(groupName, apiKey):
    # apiKey = input("What is your API Key?  ")
    # Create a Group endpoint - params: group_uuid
    url = "https://api.northpass.com/v2/groups"
    payload = {"data": {"attributes": {"name": f"{groupName}"}}}
    headers = {
        "accept": "application/json",
        "content-type": "application/json",
        "X-Api-Key": apiKey,
    }
    groupresponse = requests.post(url, json=payload, headers=headers)
    if "already have a group with this name" in groupresponse.text:
        groupName = input("Group already created, what name would you like instead? ")
        print("Got it, thanks! Attempting to create the group now.")
        createGroup(groupName, apiKey)
    else:
        readCSV(apiKey, groupresponse)


def readCSV(apiKey, groupresponse):
    people = []
    readExport = pd.read_csv(
        peopleCsv,
        usecols=["UUID"],
        skipinitialspace=True,
    )
    people.extend(readExport["UUID"].tolist())
    getgroupId(people, groupresponse, apiKey)


def getgroupId(people, groupresponse, apiKey):
    groupresponse = groupresponse.json()
    groupID = groupresponse["data"]["id"]
    ppltoGroup(people, groupID, apiKey)


def ppltoGroup(people, groupID, apiKey):
    for uuid in people:
        payload = {
            "data": [
                {"type": "people", "id": uuid},
            ]
        }
        # Add People to a Group. Params needed: group_uuid
        url = f"https://api.northpass.com/v2/groups/{groupID}/relationships/people"
        headers = {
            "accept": "*/*",
            "content-type": "application/json",
            "X-Api-Key": apiKey,
        }
        response = requests.post(url, json=payload, headers=headers)
        if "404" in response.text:
            print("Error returned for this user. Collecting names.")
            errorNames(apiKey, uuid)
        else:
            pass


def errorNames(apiKey, uuid):
    url = f"https://api.northpass.com/v2/people/{uuid}"
    headers = {"accept": "application/json", "X-Api-Key": apiKey}
    response = requests.get(url, headers=headers)
    response = response.json()
    errorList = []
    names = response["data"]["attributes"]["full_name"]
    errorList.append(names)
    fullNames(errorList)


def fullNames(errorList):
    print(errorList)


if __name__ == "__main__":
    createGroup(groupName, apiKey)
