#!/usr/bin/python

from __future__ import print_function # support both python 2 and 3

import csv

# 5th row must be the first one containing question info

# Pretty-print single player's score, e.g., within one question
def formatScore(number: float) -> str:
    if number >= 1:
        return "(1 pt)"
    else:
        return "(%.2f pts)" % number

# Print to standard output an entire question with all its scored answers.
# plrs[n] gave answers[n], scoring scores[n]
# Arguments:
#   scores is array of floats
#   answers is array of string
#   plrs is array of string.
def print_info(scores, answers, plrs) -> None:
    stats = list(zip(scores, answers, plrs))
    stats = sorted(stats, key=lambda x:(-x[0], x[1]))
    ans = ''
    # All same answers come consecutively. When there is a new answer,
    # we're guaranteed to never see another earlier answer again in stats.
    for stat in stats:
        if stat[1] == ans:
            # same answer as prev one. Append player to the comma-separated
            # list of players that gave this answer.
            print(', '+stat[2], end='')
        else:
            # start a new answer with this first name
            ans = stat[1]
            print("\n%s %s -- %s" % (stat[1], formatScore(stat[0]), stat[2]),
                end='')

with open("a.csv", 'r') as csvfile:
    reader = csv.reader(csvfile)
    r = 0
    questions = False
    players = list() # playesr with score and rank
    plrs = list() # players only
    scores = list()
    answers = list()
    for row in reader:
        if not questions:
            if r == 2:
                players = row[3:]
                plrs = row[3:]
            elif r == 3:
                players = [[players[i], float(row[i+3])] for i in range(len(players))]
            elif r == 4:
                players = [players[i] + [int(row[i+3])] for i in range(len(players))]
                questions = True
            r += 1
        else:
            if row[0] != '':
                print_info(scores, answers, plrs) # process info of last question
                scores, answers = list(), list()
                # print info for next one
                print('\n\n[b]%s. %s[/b]' % (row[0], row[1]), end='')
            if row[2] == 'score':
                # score row. Turn all strings from the CSV into numbers.
                scores = map(lambda x:(float(x)), row[3:])
            if row[2] == 'answer': # answers row
                answers = row[3:]
    print_info(scores, answers, plrs)

print("\n")
print("[b]Results[/b]")
for row in sorted(players, key=lambda x:x[2]):
    print("%d. %s (%.2f)" % (row[2], row[0], row[1]))
