r"""Mutation runs for the GoldenFile classes (Python 3, standard library only, Windows).

For each mutant the script puts one defect into the terminal's copy of an include file in
MQL5\Include\GoldenFile, compiles TestGoldenFile.mq5 with MetaEditor, runs it through the terminal,
and prints which checks failed. The include file is restored after every mutant, also after an error.
A mutant counts as caught when at least one check fails.

Close the terminal before you start: the script starts it with /config for every run.

usage:
  python mutate.py --data "<terminal data folder>" [--terminal "<terminal64.exe>"] [--metaeditor "<MetaEditor64.exe>"]
                   [--out summary.txt]
The data folder is the one that File > Open Data Folder opens (it holds MQL5\).
"""
import argparse
import glob
import io
import os
import subprocess
import sys
import tempfile

MUTANTS = [
    ("A", "GoldenCompare.mqh", "tolerance compared without the small relative margin",
     "return(MathAbs(a-b)<=tol*(1.0+1e-9)+1e-12);", "return(MathAbs(a-b)<=tol);"),
    ("B", "GoldenCompare.mqh", "rows paired by time and symbol only, the kind ignored",
     "{ return(g.kind==n.kind && g.symbol==n.symbol); }", "{ return(g.symbol==n.symbol); }"),
    ("C", "GoldenCompare.mqh", "tick count and data hash not compared",
     "bool same_data=(m_golden.Ticks()==m_new.Ticks() && m_golden.DataHash()==m_new.DataHash());",
     "bool same_data=true;"),
    ("D", "DecisionFile.mqh", "a file without the #end line accepted",
     "   if(state==2)\n      return(Fail(0,\"the file has no #end line, so the run did not finish or the file was cut\"));\n"
     "   if(end_rows!=nrows)",
     "   if(state==3 && end_rows!=nrows)"),
    ("E", "GoldenCompare.mqh", "no first pass for equal rows, pairing in file order only",
     "if(!used[b-j] && m_new.Row(b,n) && Pairable(g,n) && Fields(g,n)==\"\")",
     "if(!used[b-j] && m_new.Row(b,n) && Pairable(g,n) && false)"),
    ("F", "GoldenCompare.mqh", "order of kinds inside a second not checked",
     "if(m_order && gorder!=norder)", "if(false)"),
    ("G", "DecisionRecorder.mqh", "numbers written without the check that the reader applies",
     "if(!GfIsNumber(num[k]))", "if(false)"),
]


def compile_tests(metaeditor, mq5):
    subprocess.run('"%s" /compile:"%s" /log' % (metaeditor, mq5))
    log = mq5[:-4] + ".log"
    text = io.open(log, encoding="utf-16", errors="replace").read()
    result = [l for l in text.splitlines() if "Result" in l]
    return result[-1] if result else "no result line"


def run_tests(terminal, data):
    logs = os.path.join(data, "MQL5", "Logs")
    sizes = {p: os.path.getsize(p) for p in glob.glob(os.path.join(logs, "*.log"))}
    ini = os.path.join(tempfile.gettempdir(), "gf_mutate.ini")
    io.open(ini, "w", encoding="ascii", newline="").write(
        "[StartUp]\r\nScript=GoldenFile\\TestGoldenFile\r\nSymbol=EURUSD\r\nPeriod=H1\r\nShutdownTerminal=1\r\n")
    subprocess.run('"%s" /config:"%s"' % (terminal, ini), timeout=1200)
    lines = []
    for p in sorted(glob.glob(os.path.join(logs, "*.log")), key=os.path.getmtime)[-2:]:
        with open(p, "rb") as fh:
            fh.seek(sizes.get(p, 0))
            raw = fh.read()
        if raw[:2] == b"\xff\xfe":
            raw = raw[2:]
        lines += [l.split("\t")[-1] for l in raw.decode("utf-16-le", errors="replace").splitlines()
                  if "TestGoldenFile" in l]
    fails = [l for l in lines if l.startswith("FAIL ")]
    total = [l for l in lines if l.startswith("TEST ")]
    return fails, (total[-1] if total else "no TEST line, the script did not finish")


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--data", required=True)
    ap.add_argument("--terminal", default=r"C:\Program Files\MetaTrader 5\terminal64.exe")
    ap.add_argument("--metaeditor", default=r"C:\Program Files\MetaTrader 5\MetaEditor64.exe")
    ap.add_argument("--out", default="")
    a = ap.parse_args()
    inc = os.path.join(a.data, "MQL5", "Include", "GoldenFile")
    mq5 = os.path.join(a.data, "MQL5", "Scripts", "GoldenFile", "TestGoldenFile.mq5")
    summary = []
    for mid, fname, what, old, new in MUTANTS:
        path = os.path.join(inc, fname)
        orig = io.open(path, encoding="utf-8").read()
        if orig.count(old) != 1:
            sys.exit("mutant %s: the pattern is not found exactly once in %s" % (mid, fname))
        try:
            io.open(path, "w", encoding="utf-8", newline="").write(orig.replace(old, new))
            res = compile_tests(a.metaeditor, mq5)
            fails, total = run_tests(a.terminal, a.data)
        finally:
            io.open(path, "w", encoding="utf-8", newline="").write(orig)
        summary.append("MUTANT %s (%s, %s): %s | compile %s" % (mid, fname, what, total,
                                                               "clean" if "0 errors" in res else res))
        summary += ["   " + f for f in fails]
    compile_tests(a.metaeditor, mq5)
    fails, total = run_tests(a.terminal, a.data)
    summary.append("RESTORED: %s" % total)
    text = "\n".join(summary) + "\n"
    print(text)
    if a.out:
        io.open(a.out, "w", encoding="utf-8").write(text)


if __name__ == "__main__":
    main()
