import pprint
import csv
import json
import requests
import Apikeys

APIKEY = Apikeys.DATASNIPPER
groups_dict = {}
pp = pprint.PrettyPrinter(indent=4)


def get_groups(APIKEY):
    count = 0
    groups = []

    while True:
        count += 1
        url = f"https://api.northpass.com/v2/groups?page={count}"
        headers = {"accept": "application/json", "X-Api-Key": APIKEY}
        response = requests.get(url, headers=headers)
        data = response.json()
        nextlink = data["links"]

        for response in data["data"]:
            # created_at = response["attributes"]["created_at"]
            # if created_at.startswith("2023"):
            group_id = response["id"]
            group_name = response["attributes"]["name"]
            # print(group_name)
            groups_dict = {group_name: group_id}
            groups.append(groups_dict)

        if "next" not in nextlink:
            break

    with open(
        "/Users/normrasmussen/Downloads/Datasnipper-Groups.csv", "a+", newline='\n'
    ) as csvfile:
        for group in groups:
            for key, value in group.items():
                csvwriter = csv.writer(csvfile)
                csvwriter.writerow([key, value])


if __name__ == "__main__":
    get_groups(APIKEY)
