from typing import Tuple
import re


def remove_markdown_formatting(preamble: str, remainder: str) -> Tuple[str, str]:
    """
    Remove Markdown formatting from a preamble and remainder pair.

    Parameters
    ----------
    preamble : `str`
        The textual preamble.

    remainder : `str`
        The textual remainder.

    Returns
    -------
    `Tuple[str, str]`
        A pair of the parsed preamble and remainder.
    """

    # Remove bolds.

    preamble = re.sub(r"\*\*(?P<unformatted>.*)\*\*", r"\g<unformatted>", preamble)
    remainder = re.sub(
        r"\*\*(?P<unformatted>.*)\*\*",
        r"\g<unformatted>",
        remainder,
    )

    # Remove italics.

    preamble = re.sub(
        r"(?<!\S)_(?P<unformatted>.*)_(?!\S)", r"\g<unformatted>", preamble
    )

    remainder = re.sub(
        r"(?<!\S)_(?P<unformatted>.*)_(?!\S)", r"\g<unformatted>", remainder
    )

    preamble = re.sub(
        r"(?<!\S)\*(?P<unformatted>.*)\*(?!\S)", r"\g<unformatted>", preamble
    )

    remainder = re.sub(
        r"(?<!\S)\*(?P<unformatted>.*)\*(?!\S)", r"\g<unformatted>", remainder
    )

    # Remove underlines.

    preamble = re.sub(r"__(?P<unformatted>.*)__", r"\g<unformatted>", preamble)
    remainder = re.sub(r"__(?P<unformatted>.*)__", r"\g<unformatted>", remainder)

    # Remove hyperlink escapes.

    preamble = re.sub(r"<(?P<unformatted>http.*)>", r"\g<unformatted>", preamble)
    remainder = re.sub(r"<(?P<unformatted>http.*)>", r"\g<unformatted>", remainder)

    # Add escapes to parentheses surrounding hyperlinks.

    preamble = re.sub(r"\((?P<unformatted>http.*)\)", r"\(\g<unformatted>\)", preamble)
    remainder = re.sub(r"\((?P<unformatted>http.*)\)", r"\(\g<unformatted>\)", remainder)

    return preamble, remainder