import re


def transform_link_to_references(
    section_with_all_links,
    all_links,
    regex_skip_sections_start,
    regex_skip_sections_end,
):
    """
    Goes through a section where all link are inlined and transform them in references

    :param section_with_all_links: An array of lines representing a section where all link are inlined.
    :param all_links: An array of links representing all unique list associated to section_with_all_links.
    :param regex_skip_sections_start: regex defining the start line that indicates a block of line that shouldn't be processed.
    :param regex_skip_sections_end: regex defining the end line that indicates a block of line that shouldn't be processed.
    :return section_with_references: A section (an array of lines), with all inlined links transformed into a reference link.
    """

    section_with_references = []

    skip = False

    for line in section_with_all_links:
        if skip:
            if re.search(regex_skip_sections_end, line):
                skip = False
        elif not skip:
            if re.search(regex_skip_sections_start, line):
                skip = True
            else:
                for i, link in enumerate(all_links):
                    link_to_reference = '](' + str(link) + ')'
                    # i is incremented by one in order to start references indexes at 1
                    line = line.replace(link_to_reference,
                                        '][' + str(i + 1) + ']')

        section_with_references.append(line)

    # By the end of the for loop skip should always be false otherwise it means that a codeblock is not closed.
    if skip:
        raise ValueError

    return section_with_references