import re


def process_for_latex(text: str):
    """Process text message for latex, adapt bold, italic, code and underline delimiters"""
    # telegram formating documentation: https://core.telegram.org/api/entities
    regexs = [
        (r"\*\*\*(:?.*?(?<!\*))\*\*\*",
         r"\\textbf{\\textit{\g<1>}}")  # bold & italic
        # bold & italic
        # bold
        # bold
        # bold
        , (r"___(:?.*?(?<!_))___", r"\\textbf{\\textit{\g<1>}}"), (r"\*\*(:?.*?(?<!\*))\*\*", r"\\textbf{\g<1>}"), (r"__(:?.*?(?<!_))__", r"\\textbf{\g<1>}"), (r"<b>(:?.*?)<\\b>", r"\\textbf{\g<1>}"), (r"<strong>(:?.*?)<\\strong>", r"\\textbf{\g<1>}")  # bold
        , (r"\*(:?.*?(?<!\*))\*", r"\\textit{\g<1>}")  # italic
        , (r"_(:?.*?(?<!_))_", r"\\textit{\g<1>}")  # italic
        , (r"<i>(:?.*?)<\\i>", r"\\textit{\g<1>}")  # italic
        , (r"<em>(:?.*?)<\\em>", r"\\textit{\g<1>}")  # italic
        , (r"<u>(:?.*?)<\\u>", r"\\underline{\g<1>}")  # underline
        , (r"<code>(:?.*?)<\\code>", r"\\texttt{\g<1>}")  # code
    ]  # Beware, regex sustitution order is important

    for regex, subst in regexs:
        text = re.sub(regex, subst, text, 0, re.MULTILINE)

    return text