#!/usr/bin/python

import csv, random, sys

if len(sys.argv) != 3:
    print 'Usage:'
    print 'python markerallocation.py startmap markinglist'
    print 'startmap: Go to MarkUs->Assignment->Graders tab. Click the download link'
    print '          and save the "Group / Grader map CSV" file somewhere on the'
    print '          course account. This argument is the path to that CSV file.'
    print 'markinglist: This is the path to a CSV file you have to create. In the CSV'
    print '             file, each line should be like this:   graderid,X'
    print '             where graderid is a grader\'s Quest ID, and X is the number'
    print '             of assignments that grader has to mark.'
    print
    sys.exit(0)


random.seed()


student_list = [] 
assns_to_mark = 0

marker_list = []
positions_available = 0


# read startmap
f = open(sys.argv[1], 'r')
for row in csv.reader(f):
    if len(row) == 1:
        assns_to_mark += 1
    student_list.append(row);
f.close()
random.shuffle(student_list)

# read markinglist
f = open(sys.argv[2], 'r')
for row in csv.reader(f):
        positions_available += int(row[1])
	marker_list.append([row[0], int(row[1])])
f.close()


if assns_to_mark != positions_available:
    print 'Counting Error:'
    print 'There are %d assignments that have to be assigned to TAs' % assns_to_mark
    print 'But the sum of the numbers in %s is %d' % (sys.argv[2], positions_available)
    sys.exit(0)


for marker in marker_list:
    i = marker[1]
    while(i > 0):
        if len(student_list[-1]) == 2: # this student already has a TA assigned
            print "%s,%s" % (student_list[-1][0], student_list[-1][1])
        else:
            print "%s,%s" % (student_list[-1][0], marker[0])
            i -= 1;
        student_list.pop()