from typing import OrderedDict


def build_meta_layer(root):
    """
    Build the meta layer from the provided root of the XML tree.

    :param root: The root element of the XML tree.
    :type root: :class:`etree.Element`

    :return: An OrderedDict containing the regulation metadata, suitable for direct
        transformation into JSON for use with the eRegs frontend.
    :rtype: :class:`collections.OrderedDict`:
    """

    meta_dict = OrderedDict()

    part_to_letter = {'1001': 'A', '1002': 'B', '1003': 'C',
                      '1004': 'D', '1005': 'E', '1006': 'F',
                      '1007': 'G', '1008': 'H', '1009': 'I',
                      '1010': 'J', '1011': 'K', '1012': 'L',
                      '1013': 'M', '1014': 'N', '1015': 'O',
                      '1016': 'P', '1017': 'Q', '1018': 'R',
                      '1019': 'S', '1020': 'T', '1021': 'U',
                      '1022': 'V', '1023': 'W', '1024': 'X',
                      '1025': 'Y', '1026': 'Z', '1027': 'AA',
                      '1028': 'BB', '1029': 'CC', '1030': 'DD',
                      '1070': '1070', '1071': '1071',
                      '1072': '1072', '1080': '1080',
                      '1081': '1081', '1090': '1090',
                      }

    preamble = root.find('{eregs}preamble')
    fdsys = root.find('{eregs}fdsys')
    eff_date = preamble.find('{eregs}effectiveDate').text
    cfr_title_num = int(fdsys.find('{eregs}cfrTitleNum').text)
    cfr_title_text = fdsys.find('{eregs}cfrTitleText').text
    statutory_name = fdsys.find('{eregs}title').text
    part = preamble.find('{eregs}cfr').find('{eregs}section').text

    part_letter = part_to_letter[part]

    meta_dict[part] = [
        {
            'cfr_title_number': cfr_title_num,
            'cfr_title_text': cfr_title_text,
            'effective_date': eff_date,
            'reg_letter': part_letter,
            'statutory_name': statutory_name
        }
    ]

    return meta_dict