import re


def fix_links(chunk, tag2file):
    """Find and fix the the destinations of hyperlinks using HTML or markdown syntax

    Fix any link in a string text so that they can target a different html document.
    First use regex on a HTML text to find any HTML or markdown hyperlinks
    (e.g. <a href="#sec1"> or [sec1](#sec1) ). Then use a dictionary to prepend the
    filename to the value of a link's href attribute (e.g. <a href="02_jupyterbook.html#sec1">)
    :param str chunk: text string
    :param dict tag2file: dictionary mapping a tag to a file basename e.g. tag2file['sec1']='02_jupyterbook'
    :return: chunk with fixed links
    :rtype: str
    """
    chunk_out = chunk
    # html links
    pattern_tag = r'[\w _\-:]'
    pattern = r'<' + pattern_tag + '+ href=[\\\]{0,2}["\']#(' + pattern_tag + '+)[\\\]{0,2}["\'][^>]*>'
    for m in re.finditer(pattern, chunk):
        match = m.group()
        tag = m.group(1)
        fixed_tag = match.replace('#' +tag, tag2file.get(tag, tag) + '.html#' + tag)
        chunk_out = chunk_out.replace(match, fixed_tag)
    # markdown links
    pattern = r'\[' + pattern_tag + '+\]\(#(' + pattern_tag + '+)\)'
    for m in re.finditer(pattern, chunk):
        match = m.group()
        tag = m.group(1)
        fixed_tag = match.replace('#' + tag, tag2file.get(tag, tag) + '.html#' + tag)
        chunk_out = chunk_out.replace(match, fixed_tag)
    return chunk_out