from typing import List
from typing import Dict
from typing import Any
from typing import Tuple


def partition_ast(content: List[Dict[str, Any]], ref_level: int = 0) -> Tuple[List[Dict[str, Any]], int]:
    """
    Partition AST, recursive function to create a hierarchial tree out of a stream of markdown elements.

    Markdown elements are typically treated as a flat stream of tokens - which is sufficient for most needs.
    For this project and understanding of heading hierarchy.


    Args:
        content: List of AST parsing elements as from mistune
        ref_level: The markdown heading level expected. Set to 0 when starting naively
    Returns:
        List containing a tree of elements
        Number of elements parsed in within the sub-list

    """
    new_content = []
    ii = 0
    while ii < len(content):
        if content[ii]['type'] == 'heading':
            if content[ii]['level'] <= ref_level:
                break
            if ii + 1 == len(content):
                new_content.append(content[ii])
                ii = ii + 1
                break
            else:
                sub_content, jj = partition_ast(content[ii + 1:], content[ii]['level'])
                fixed_header = content[ii]
                fixed_header['children'].extend(sub_content)
                new_content.append(fixed_header)
                ii = ii + jj + 1
        else:
            new_content.append(content[ii])
            ii = ii + 1
    return new_content, ii