#!/usr/bin/env python2.7
# -*- coding: utf-8 -*-
__author__ = "Joan Puigcerver"
__email__ = "joapuipe@prhlt.upv.es"
__copyright__ = "Copyright 2015, Pattern Recognition and Human Language Technology"
__licence__ = "Public Domain"

import argparse
import logging
import sys

LOG_FMT = '%(asctime)-15s %(levelname)s %(filename)s:%(lineno)d %(message)s'
logging.basicConfig(format = LOG_FMT)

if __name__ == '__main__':
    parser = argparse.ArgumentParser(
        'ICDAR2015 Competition on KWS - Team Ranking Toolkit',
        formatter_class=argparse.ArgumentDefaultsHelpFormatter)
    parser.add_argument(
        '--bonus-weight', '-w', type=float, default=0.2,
        help='weight of the bonus points')
    parser.add_argument(
        'baselineA', type=float,
        help='baseline score for assigment A')
    parser.add_argument(
        'baselineB', type=float,
        help='baseline score for assignment B')
    parser.add_argument(
        'input', type=argparse.FileType('r'), nargs='?', default=sys.stdin,
        help='input file containing the name of the team and their scores, '+
        'one team per line')
    args = parser.parse_args()

    assignmentA, assignmentB, teams = [], [], []
    for line in args.input:
        line = line.split()
        if len(line) != 3 or line[0][:1] == '#':
            continue
        team, sA, sB = line[0], float(line[1]), float(line[2])
        assignmentA.append(sA if sA > args.baselineA else 0.0)
        assignmentB.append(sB if sB > args.baselineB else 0.0)
        teams.append(team)

    maxA = max(assignmentA)
    maxB = max(assignmentB)

    # Normalize scores in each assignment, per team
    if maxA > 0.0:
        assignmentA_normalized = {
            teams[i] : assignmentA[i] / maxA for i in range(len(teams)) }
    else:
        assignmentA_normalized = { t : 0.0 for t in teams }


    if maxB > 0.0:
        assignmentB_normalized = {
            teams[i] : assignmentB[i] / maxB for i in range(len(teams)) }
    else:
        assignmentB_normalized = { t : 0.0 for t in teams }

    global_scores = []
    for team in teams:
        sA = assignmentA_normalized[team]
        sB = assignmentB_normalized[team]
        sG = max(sA, sB) + args.bonus_weight * min(sA, sB)
        global_scores.append((sG, team))

    global_scores.sort(reverse=True)
    for (s, t) in global_scores:
        print t, s
