#!/usr/bin/env python3
"""
generate_group_data.py - parses the groups/keys CSVs and generates student_data.json

This parses
    the group assignments CSV (containing student ID, name and group), and
    the TA group CSV (containing uvanetid, groups, first name and last name)

and generates student_data.json, which contains a mapping from group to
list of students, where a student consists of a name and list of SSH keys.

Requires `anyascii` PyPI package.
"""
import csv
import json
import os
import string
import sys
from anyascii import anyascii
from collections import defaultdict

students_by_group = defaultdict(dict)


groups_filename = sys.argv[1] if len(sys.argv) > 1 else "student_groups.csv"
tas_filename = sys.argv[2] if len(sys.argv) > 2 else "ta_groups.csv"


def next_name(name: str):
    """Generates the next name in the sequence foo, foo1, foo2, foo3, ..."""
    if name[-1].isdigit():
        n = int(name[-1])
        n += 1
        return name[:-1] + str(n)
    return name + "1"


if not os.path.exists(groups_filename) or not os.path.exists(tas_filename):
    print("Usage: parse_csv.py <groups_csv> <ta_groups_csv>\n")
    print("By default, uses student_groups.csv and ta_groups.csv.")

# Excel CSV is braindead and emits a byte-order mark for UTF-8.
# Using encoding='utf-8-sig' strips this.

with open(groups_filename, "r", encoding="utf-8-sig") as f:
    reader = csv.DictReader(f, delimiter=";")
    for row in reader:
        name = (
            row["FirstName"].strip().split()[0].lower() + row["LastName"][0].lower()
        ).replace("'", "")
        group = row["webtech groep"].lower()
        uid = row["UvAnetID"]

        if any(s not in string.ascii_letters for s in name):
            print(name, " -> ", anyascii(name))
            name = anyascii(name)

        if not uid:
            print(
                f"Warning: no student ID for {row['FirstName']} {row['MiddleName']} {row['LastName']}? Using name..."
            )
            uid = name

        first_name = row["FirstName"]
        last_name = f"{row['MiddleName']} {row['LastName']}".strip()

        students_by_group[group][uid] = {
            "name": name,
            "uid": uid,
            "first_name": first_name,
            "last_name": last_name,
            "is_ta": False,
        }

with open(tas_filename, "r", encoding="utf-8-sig") as f:
    reader = csv.DictReader(f, delimiter=";")

    for row in reader:
        uid = row["UvAnetID"]

        if not uid:
            print(
                f"Warning: no UID for {row['Voornaam']} {row['Achternaam']}? skipping"
            )
            continue

        groups = row["Groepen"]

        name = uid  # row["Voornaam"].lower() + row["Achternaam"][0].lower()
        if name.isnumeric():
            name = row["Voornaam"].lower() + row["Achternaam"][0].lower()

        for group in groups.strip().split(","):
            students_by_group[group][uid] = {
                "name": name,
                "uid": uid,
                "first_name": row["Voornaam"],
                "last_name": row["Achternaam"],
                "is_ta": True,
            }

    # Special case: add accounts for certain TAs to all groups
    for group in students_by_group.values():
        group["skampen"] = {
            "name": "skampen",
            "uid": "skampen",
            "first_name": "Sam",
            "last_name": "van Kampen",
            "is_ta": True,
        }
        group["wpetri"] = {
            "name": "wpetri",
            "uid": "wpetri",
            "first_name": "Wouter",
            "last_name": "Petri",
            "is_ta": True,
        }

for group, students in students_by_group.items():
    unique_names = set(student["name"] for student in students.values())
    if len(unique_names) != len(students):
        print(f"Group {group} has non-unique names! Please correct manually.")

with open("student_data.json", "w") as f:
    json.dump(students_by_group, f, indent=4)

print("wrote data to student_data.json")
