from typing import List
from typing import Iterable
import re


def get_next_heading_of_level(buffer_contents: List[str], level: int) -> int:
    """get_next_heading_of_level

    Given a buffer, get the line that the next buffer of the given level occurs on.
    Will either be the given level, or any lower level. Lower in this content means
    that if given 3, a heading of level 3, 2 or 1 will be valid.

    This should most likley be used with get_section_line, to validate that the
    chosen heading falls inside the correct area.
    """

    section_index: int = -1

    # Search forward in the buffer and find the next line of interest.
    buffer_iterator: Iterable[str] = iter(buffer_contents)

    for line_index, line in enumerate(buffer_iterator):
        if re.findall(rf"^#{{1,{level}}} ", line):
            section_index = line_index
            break

    return section_index