import collections


def trainval_log_statistic(trainval_log):
    """
    Args:
        trainval_log (dict): output of function: read_trainval_log_file
    :return:
    e.g.:
    >>> result = {
    >>>     'total_epoch': 100,
    >>>     'last_top-1_val_accuracy': 0.87,
    >>>     'last_top-2_val_accuracy': 0.95,
            ...
    >>>     'max_top-1_val_accuracy': 0.88,
    >>>     'last_top-1_epoch': 65,
    >>>     'max_top-2_val_accuracy': 0.96,
    >>>     'last_top-2_epoch': 45,
            ...
    >>> }
    """
    result = {'total_epoch': len(trainval_log['epoch'])}
    # last top-k validation accuracy
    for k in range(len(trainval_log['val_accuracy'][0])):
        result[f'last_top-{k + 1}_val_accuracy'] = trainval_log['val_accuracy'][-1][k]
    # max top-k validation accuracy
    top_k_acc = collections.OrderedDict()
    for k in range(len(trainval_log['val_accuracy'][0])):
        top_k_acc[str(k + 1)] = []
        for epoch in trainval_log['epoch']:
            top_k_acc[str(k + 1)].append(trainval_log['val_accuracy'][epoch-1][k])
    for key in top_k_acc.keys():
        max_acc = max(top_k_acc[key])
        max_acc_epoch = trainval_log['epoch'][top_k_acc[key].index(max_acc)]
        result[f'max_top-{key}_val_accuracy'] = max_acc
        result[f'max_top-{key}_epoch'] = max_acc_epoch
    return result