import csv


def make_segmentation_dict(segmentations_tsv_path):
    """
    Load a segmentations TSV file. Rows of `segmentations_tsv_path` look like this:

    tag                 read_id: pos:       L_0    A_0:    P_0:     P_1:     RR:    P(A)L:  AL:
    polya-segmentation  fc06...  161684804  47.0   1851.0  8354.0   11424.0  73.76  75.18   35.23

    Note that this function only takes the first available segmentation for each read, i.e.
    if a read id appears more than once in the TSV, only the first segmentation is kept, and
    later occurrences of the read id in the TSV are ignored.
    """
    segments = {}
    # loop thru TSV and update the list of segmentations:
    with open(segmentations_tsv_path, 'r') as f:
        headers = ['tag', 'read_id', 'pos', 'L_start', 'A_start', 'P_start', 'P_end', 'rate', 'plen', 'alen']
        rdr = csv.DictReader(f, delimiter='\t', quoting=csv.QUOTE_NONE, fieldnames=headers)
        for row in rdr:
            if row['read_id'] not in list(segments.keys()):
                segments[row['read_id']] = { 'L_start': int(float(row['L_start'])),
                                             'A_start': int(float(row['A_start'])),
                                             'P_start': int(float(row['P_start'])),
                                             'P_end': int(float(row['P_end'])) }
    return segments