import re

## Simple replacement map
_macros = {
  r'\GeV'   : r'\mathrm{Ge\!V}',
  r'\TeV'   : r'\mathrm{Te\!V}',
  r'\pt'    : r'{p_\mathrm{T}}',
  r'\pT'    : r'{p_\mathrm{T}}',
  r'\dfrac' : r'\frac',
  r'\tfrac' : r'\frac',
  r'≤'      : r'$\leq$',
  r'≥'      : r'$\geq$',
}

## Replacement map that triggers on a regex
_regex = {
  r"\$(.+?textrm.+?)\$" : [ r"\textrm", r"\mathrm" ],
  r"\$(.+?text.+?)\$" : [ r"\text", r"\mathrm" ],
  r"\$(.+?'.+?)\$" : [ r"'", r"\prime" ],
}

def preprocess(s):
    """Apply simple and regex-based
       substitutions defined in this file."""
    if not isinstance(s, str):
        return s

    for _from, _to in _macros.items():
        s = s.replace(_from, _to)

    for regex, (_from, _to) in _regex.items():
        if re.search(regex, s):
            s = s.replace(_from, _to)

    return s.replace(r'\newline', r'"+"\n"+r"')


def applyRegexes(s, regexes, regex_subs = {}):
    """Apply user-supplied regular expressions by replacing 'RE[n]'-like substrings
       in string s with the n'th group captured by the supplied regular expressions.
       If a substitution map has been supplied as well, the captured regex group is
       first substituted by the corresponding map value, before replacing it."""

    for idx, item in enumerate(regexes):
        key = f'RE[{idx}]'
        if key in s:
            s = s.replace(key, item)
        key = f'SUBST[{idx}]'
        if key in s and item in regex_subs:
            s = s.replace(key, regex_subs[item])
        elif key in s:
            print(f"No substitution found for key: '{item}'")
            s = s.replace(key, item)
    return s

