import csv


def close_history(args):
    """close the history file and print the best record in the history file"""
    args.hist_file.close()
    args.hist_file = open(args.results_dir+'/history.csv', 'r', newline='')
    reader = csv.DictReader(args.hist_file)
    best_epoch = 0
    best = {}
    for epoch, record in enumerate(reader):
        if not best or record['val_loss'] < best['val_loss']:
            best = record
            best_epoch = epoch+1

    print('\nThe best avg val_loss: {}, avg val_cost: {}%, avg val_acc: {}%\n'
           .format(best['val_loss'], best['cost'], best['acc']))

    return best_epoch