import re, time


init_time = time.time()
ind = len("function ")
name_beg = re.compile(r"function ")
name_end = re.compile(r" takes")
endfunc = re.compile(r"endfunction")

aim_beg = re.compile(r"call RemoveUnit\(")
open_brace = re.compile(r"\(")
closing_brace = re.compile(r"\)")


def FindVarName(s: str):
    i = 0
    all_closed = closing_brace.finditer(s)
    brac = None
    for brac in all_closed:
        i += 1
    return s[:brac.start()], i == 1


def DebugMsg(spaces: int, var: str, isvar: bool):
    out = " " * spaces
    out = out + "//Added by DebugMessagesAdder\n" + out + \
                "call DisplayTimedTextToPlayer(GetLocalPlayer(), 0., 0., 5., \"A unit "
    if isvar:
        return out + "in variable " + var + " of function " + name_of_func + " is removed.\")\n"
    return out + "received from " + var + " call in function " + name_of_func + " is removed.\")\n"


print("Please, enter path to the input file:")
input_path = input()
print("Please, enter path to the output file:")
output_path = input()

with open(input_path, encoding="utf-8") as f:
    inp = f.readlines()

name_of_func = None
for i in range(len(inp)):
    s = inp[i]
    if name_of_func is None:
        result = name_beg.search(s)
        if not (result is None):
            name_of_func = s[result.end():name_end.search(s).start()]
    else:
        result = endfunc.search(s)
        if result is None:
            fromm = aim_beg.search(s)
            if not (fromm is None):
                t = FindVarName(s[fromm.end():])
                inp.insert(i + 1, DebugMsg(fromm.start(), t[0], t[1]))
        else:
            name_of_func = None

with open(output_path, "w", encoding="utf-8") as f:
    f.writelines(inp)

print("Execution end in %.3f seconds" % (time.time() - init_time))
