from pathlib import Path
from typing import Dict
import re


def _rewrite_links(file: Path, replacement_files: Dict[str, str]) -> None:
    """
    Rewrites Markdown links based on the new directory structure created by running the conversion
    :param file: source markdown file
    :param replacement_files: a dictionary of file name (flat) to file name (relative to new root)
    """
    class Fixup:
        def __init__(self):
            self.changed = False

        def fixup(self, match) -> str:
            link_target = match.group(1)
            if link_target in replacement_files:
                self.changed = True
                return f'](/{replacement_files[link_target]})'
            return f']({link_target})'

    with open(file, mode='r+') as input_file:
        data = input_file.read()

    fixup = Fixup()
    flags = re.IGNORECASE | re.DOTALL | re.MULTILINE
    new = re.sub(']\((.*?)\)', fixup.fixup, data, 0, flags)

    if fixup.changed:
        with open(file, mode='w') as output_file:
            output_file.write(new)