from typing import OrderedDict


def build_toc_layer(root):
    """
    Build the paragraph table-of-contents layer from the provided root of the XML tree.

    :param root: A root element containing tableOfContents elements.
    :type root: :class:`etree.Element`

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

    toc_dict = OrderedDict()

    # Look for all tables of contents in the given element and add them
    # to the layer.
    tables_of_contents = root.findall('.//{eregs}tableOfContents')
    for toc in tables_of_contents:
        parent = toc.getparent()
        if parent.tag == '{eregs}content':
            parent = parent.getparent()

        label = parent.get('label')

        # Warn user about elements without labels
        if label is None:
            raise ValueError("TOC parent element {} has no label; this will cause JSON issues.".format(parent.tag))

        toc_dict[label] = []

        # Build sections
        for section in toc.findall('{eregs}tocSecEntry'):
            target = section.get('target').split('-')
            subject = section.find('{eregs}sectionSubject').text
            toc_entry = {'index': target, 'title': subject}
            toc_dict[label].append(toc_entry)

        # Build appendix sections
        for appendix_section in toc.findall('{eregs}tocAppEntry'):
            target = appendix_section.get('target').split('-')
            subject = appendix_section.find('{eregs}appendixSubject').text
            toc_entry = {'index': target, 'title': subject}
            toc_dict[label].append(toc_entry)

        # Build interp sections
        for interp_section in toc.findall('{eregs}tocInterpEntry'):
            target = interp_section.get('target').split('-')
            subject = interp_section.find('{eregs}interpTitle').text
            toc_entry = {'index': target, 'title': subject}
            toc_dict[label].append(toc_entry)

    return toc_dict