#!/usr/bin/env python3
"""Mutation experiment on Premier's 'an unknown outcome blocks every later transfer' guards.
Run it in a scratch checkout only. Usage: mutate-premier.py <example_dir> <out_dir>.
Each mutation edits premier_demo/host.py and/or premier_demo/rasa_adapter.py, runs the whole
suite, records the failing tests, and the files are restored byte for byte at the end."""
import hashlib, json, os, re, subprocess, sys, time
ex, out = sys.argv[1], sys.argv[2]
os.makedirs(out, exist_ok=True)
paths = {"host": os.path.join(ex, "premier_demo", "host.py"), "adapter": os.path.join(ex, "premier_demo", "rasa_adapter.py")}
orig = {k: open(p).read() for k, p in paths.items()}
sha = lambda s: hashlib.sha256(s.encode()).hexdigest()

H1 = ('            if self.journal.held(context.principal):\n                raise Refused("outcome_unresolved")\n            cleaned = _money(amount)\n',
      '            cleaned = _money(amount)\n')
H2 = ('            if self.held(principal):\n                raise Refused("outcome_unresolved")\n            self._db.execute("INSERT INTO marker VALUES(?,?,\'pending\',?)", (principal, review, epoch))\n',
      '            self._db.execute("INSERT INTO marker VALUES(?,?,\'pending\',?)", (principal, review, epoch))\n')
H3 = ("SELECT 1 FROM marker WHERE principal=? AND state IN ('pending','unknown')", "SELECT 1 FROM marker WHERE principal=? AND state IN ('pending')")
A1 = ('        if reason != "outcome_unresolved" and await _unresolved(host):\n            text = UNKNOWN_OUTCOME_TEXT\n', '')
A2 = ('    return data.get("state") not in {"none", "accepted", "refused", "rejected"}\n', '    return False\n')
for key, (a, b) in (("host", H1), ("host", H2), ("host", H3), ("adapter", A1), ("adapter", A2)):
    assert orig[key].count(a) == 1, (key, a[:60], orig[key].count(a))

def mut(*parts):
    files = dict(orig)
    for key, (a, b) in parts:
        files[key] = files[key].replace(a, b)
    return files
MUTATIONS = [
    ("baseline", dict(orig)),
    ("H1 drop the review-time hold in the host", mut(("host", H1))),
    ("H2 drop the send-time hold in the journal", mut(("host", H2))),
    ("H3 the journal stops holding after an unknown", mut(("host", H3))),
    ("H12 drop both host holds", mut(("host", H1), ("host", H2))),
    ("A1 drop the unknown-first wording rule", mut(("adapter", A1))),
    ("A2 forget the journal status after a restart", mut(("adapter", A2))),
    ("ALL drop every hold and both wording rules", mut(("host", H1), ("host", H2), ("host", H3), ("adapter", A1), ("adapter", A2))),
]
results = []
try:
    for name, files in MUTATIONS:
        for key, p in paths.items():
            open(p, "w").write(files[key])
        t0 = time.time()
        p = subprocess.run(["uv", "run", "--locked", "--group", "models", "python", "-m", "unittest", "discover", "-s", "tests", "-v"],
                           cwd=ex, capture_output=True, text=True, timeout=900)
        text = p.stdout + p.stderr
        failing = sorted(set(re.findall(r"^(?:FAIL|ERROR): (\S+) \(([^)]+)\)", text, re.M)))
        ran = re.search(r"^Ran (\d+) tests? in ([0-9.]+)s", text, re.M)
        skipped = re.search(r"skipped=(\d+)", text)
        label = re.sub(r"[^A-Za-z0-9]+", "_", name)[:40]
        open(os.path.join(out, label + ".log"), "w").write(text)
        results.append({"mutation": name, "files_sha256": {k: sha(v) for k, v in files.items()}, "exit": p.returncode,
                        "ran": int(ran.group(1)) if ran else None, "skipped": int(skipped.group(1)) if skipped else 0,
                        "failing": [f"{c}.{m}" if "." not in m else m for m, c in failing], "log": label + ".log",
                        "seconds": round(time.time() - t0, 1)})
        print(results[-1]["mutation"], "| exit", p.returncode, "| failing", len(failing), flush=True)
finally:
    for key, p in paths.items():
        open(p, "w").write(orig[key])
restored = all(open(p).read() == orig[k] for k, p in paths.items())
json.dump({"original_sha256": {k: sha(v) for k, v in orig.items()}, "restored_identical": restored, "results": results},
          open(os.path.join(out, "RESULTS.json"), "w"), indent=1)
print("restored identical:", restored)
