r"""Mutation runs for the PSquare 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\PSquare, compiles TestPSquare.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.
With --wait, the script waits before each start until no terminal64.exe is running.

usage:
  python mutate.py --data "<terminal data folder>" [--terminal "<terminal64.exe>"] [--metaeditor "<MetaEditor64.exe>"]
                   [--out summary.txt] [--wait]
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
import time

MUTANTS = [
    ("A", "PSquare.mqh", "parabolic height accepted when it equals a neighbor",
     "if(m_q[i-1]<q && q<m_q[i+1])", "if(m_q[i-1]<=q && q<=m_q[i+1])"),
    ("B", "PSquare.mqh", "marker allowed to move onto the position of its neighbor",
     "if((d>=1.0 && m_n[i+1]-m_n[i]>1) || (d<=-1.0 && m_n[i-1]-m_n[i]<-1))", "if(d>=1.0 || d<=-1.0)"),
    ("C", "PSquare.mqh", "linear formula moves away from the neighbor",
     "return(m_q[i]+d*(m_q[i+d]-m_q[i])/(double)(m_n[i+d]-m_n[i]));",
     "return(m_q[i]-d*(m_q[i+d]-m_q[i])/(double)(m_n[i+d]-m_n[i]));"),
    ("D", "PSquare.mqh", "a value equal to a marker height falls into the lower cell",
     "   while(k<3 && x>=m_q[k+1])", "   while(k<3 && x>m_q[k+1])"),
    ("E", "CountQuantile.mqh", "counter returns the value one rank too low",
     "      if(seen>rank)\n         return(v);", "      if(seen>=rank)\n         return(v);"),
    ("F", "LogQuantile.mqh", "bucket stands for its upper bound instead of its center",
     "   return(2.0*MathPow(m_gamma,b+m_offset)/(m_gamma+1.0));", "   return(MathPow(m_gamma,b+m_offset));"),
]


def wait_free(minutes=60):
    end = time.time() + minutes * 60
    while time.time() < end:
        out = subprocess.run('tasklist /FI "IMAGENAME eq terminal64.exe"', capture_output=True, text=True).stdout
        if "terminal64.exe" not in out:
            return
        time.sleep(5)
    sys.exit("terminal64.exe still running after %d minutes, nothing was started" % minutes)


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, wait):
    if wait:
        wait_free()
    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(), "psq_mutate.ini")
    io.open(ini, "w", encoding="ascii", newline="").write(
        "[StartUp]\r\nScript=PSquare\\TestPSquare\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 "TestPSquare" in l]
    fails = [l for l in lines if l.startswith("FAIL ")]
    total = [l for l in lines if l.startswith("TestPSquare:")]
    return fails, (total[-1] if total else "no summary 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="")
    ap.add_argument("--wait", action="store_true")
    a = ap.parse_args()
    inc = os.path.join(a.data, "MQL5", "Include", "PSquare")
    mq5 = os.path.join(a.data, "MQL5", "Scripts", "PSquare", "TestPSquare.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, a.wait)
        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, a.wait)
    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()
