from typing import OrderedDict


def get_priority_ordered_labels(label_id_priority_fname):
    """ ordered_priority_dict = get_priority_ordered_labels(label_id_priority_fname)
    read the input .csv file into a priority dictionary struct

    Args:
        label_id_priority_fname:    with Header = Label, ID, Priority

    Returns:
        ordered_priority_dict:      {priority_number: {'label': label_str, 'ID': str_number}}
                                    sorted with largest priority number first
    """
    # create the ordered_priority_dict for return, and a id_priority reverse dict 4 lookups
    priority_tuples_list = []

    # read the file
    lines = ''
    try:
        with open(label_id_priority_fname, 'r') as fh:
            lines = fh.readlines()
    except:
        print('failed opening: ', label_id_priority_fname)
        lines = ''
        pass

    # read the .csv lines into the dict   Header = Label, ID, Priority
    if len(lines) > 0:
        for line in lines:
            ln_list = line.strip().split(',')
            if len(ln_list) > 1 and ln_list[0] != 'Label':
                #                   Fix name clash: .xml "Id" vs .csv "ID" - Renaming csv-ID as label_ID
                # tuple:                    (    priority,     {label: label_name,     ID: ID_number}    )
                priority_tuples_list.append((int(ln_list[2]), {'label': ln_list[0], 'label_ID': ln_list[1]}))

    return OrderedDict(sorted(priority_tuples_list, reverse=True))