import re


def update_anchor_ids(page_html, page_key):
    """
    Changes internal anchors to make sure they are unique within the print page.

    For example, changes all instances in pagename.html of id="#anchor" to id="#pagename-anchor"

    It does this only for the h1-h6 tags.
    """
    # Regex demo / tests: https://regex101.com/r/mlAPNH/3
    href_regex = re.compile(
        r"<([^\s]+).*?id=\"([^\"]*?)\".*?>",
        flags=re.IGNORECASE,
    )
    matches = re.finditer(href_regex, page_html)

    change_tags = ["h1", "h2", "h3", "h4", "h5", "h6", "sup", "li"]
    for m in matches:
        tag_text = m.group(1)
        if tag_text not in change_tags:
            continue
        id_text = m.group(2)
        match_text = m.group()
        new_text = match_text.replace(id_text, page_key + "-" + id_text)

        page_html = page_html.replace(match_text, new_text)

    return page_html