import re
import ast
import string


def _substitute_function_template(module: str) -> str:
  """Substitutes all the function templates in the given module."""
  while True:
    pattern = r'^\s*parameters(\[.*?\])\n?(^\s*(?:func\.)+func.*?\{.*?(?:func\.)+return.*?\}\n)'
    func_match = re.search(pattern, module, re.MULTILINE | re.DOTALL)
    if func_match is None:
      break

    try:
      value_list = ast.literal_eval(func_match.group(1))
      func_template = string.Template(func_match.group(2))
    except Exception as e:  # pylint: disable=broad-except
      raise ValueError('The function template is in wrong format') from e

    replacement_text = ''
    for value_dict in value_list:
      replacement_text += '\\n'
      replacement_text += func_template.substitute(value_dict)
    module = re.sub(
        pattern,
        replacement_text,
        module,
        count=1,
        flags=re.MULTILINE | re.DOTALL)
  return module