import csv


def get_stats(csv_path):
    """Parse aligned results csv file to get results.

    Args:
      csv_path: str, aligned result path, e.g., xx_corresp.txt

    Returns:
      stat_dict, dict, keys: true positive (TP), deletion (D), insertion (I), 
        substitution (S), error rate (ER), ground truth number (N)
    """
    with open(csv_path, 'r') as fr:
        reader = csv.reader(fr, delimiter='\t')
        lines = list(reader)

    lines = lines[1 :]

    TP, D, I, S = 0, 0, 0, 0
    align_counter = []
    ref_counter = []

    for line in lines:
        line = line[0 : -1]
        [alignID, _, _, alignPitch, _, refID, _, _, refPitch, _] = line

        if alignID != '*' and refID != '*':
            if alignPitch == refPitch:
                TP += 1
            else:
                S += 1

        if alignID == '*':
            D += 1

        if refID == '*':
            I += 1

    N = TP + D + S
    ER = (D + I + S) / N

    print('TP: {}, D: {}, I: {}, S: {}'.format(TP, D, I, S))
    print('ER: {:.4f}'.format(ER))

    stat_dict = {'TP': TP, 'D': D, 'I': I, 'S': S, 'ER': ER, 'N': N}
    return stat_dict