"""
Jason Yau 
10/30/2025

Use to quickly run all student source code from Webcourses on Eustis and output a csv using stdout.

====================================

Usage:

Go to assignments, P4, Download submissions. A file named submissions.zip (or similar) will download
Go to gradebook, export grades to CSV, a CSV will download

python3 cheaters.py <secret word>

====================================

"""


import os
import glob
from zipfile import ZipFile
import shutil
import subprocess
import re
from collections import Counter
import csv
import sys
    

script_path = os.path.abspath(__file__)
script_directory = os.path.dirname(script_path)

extracted_path = f"{script_directory}/extracted"
if (len(glob.glob(extracted_path)) != 0):
    shutil.rmtree(extracted_path)

submissions_zip = glob.glob(f"{script_directory}/submissions*.zip")
if len(submissions_zip) != 1:
    print(f"There were {len(submissions_zip)} submissions*.zip found. Exiting.")
    exit(1)
with ZipFile(submissions_zip[0], 'r') as zip_object:
    zip_object.extractall(extracted_path)


grades_zip = glob.glob(f"{script_directory}/*Grades-COP3502C*.csv")
if len(grades_zip) != 1:
    print(f"There were {len(grades_zip)} *Grades-COP3502C*.csv found. Exiting.")
    exit(1)

students = {}
with open(grades_zip[0], 'r') as csv_file:
    csv_reader = csv.reader(csv_file)
    for row in csv_reader:
        students[row[1]] = [row[0], False, False]


if len(sys.argv) <= 1:
    print(f"File usage: python3 cheaters.py <secret word>")
    exit(1)
else:
    secret_word = sys.argv[1]

source_code_files = sorted(glob.glob(f"{extracted_path}/*.c")+glob.glob(f"{extracted_path}/*.C"))
for source_code_file in source_code_files:
    file_name = os.path.basename(source_code_file)
    id = file_name.split('_')[1]
    if id == "LATE":
        id = file_name.split('_')[2]
    file_content = open(source_code_file, "r", encoding='utf-8', errors='replace').read()
    if secret_word in file_content:
        students[id][1] = True
    students[id][2] = True

submissions = 0
cheaters = 0
for id in students:
    if students[id][1]:
        print(students[id][0])
        cheaters += 1
    if students[id][2]:
        submissions += 1

print()
print(f"Total cheaters who used \"{secret_word}\": {cheaters}")
print(f"Total students who submitted: {submissions}")
print(f"Percent: {round(100*cheaters/submissions,2)}%")

shutil.rmtree(extracted_path)