#!/usr/bin/env python3
"""Mutation experiment on SilverLake's two confirmation guards. Run it in a scratch checkout, never in a working copy you care about.

Usage: mutate.py <example_dir> <out_dir>. Each mutation edits silverlake_demo/rasa_adapter.py,
runs the guard-related unit tests, records pass/fail names, then restores the file byte for byte.
"""
import hashlib, json, os, re, subprocess, sys, time
ex, out = sys.argv[1], sys.argv[2]
os.makedirs(out, exist_ok=True)
path = os.path.join(ex, "silverlake_demo", "rasa_adapter.py")
orig = open(path).read()
sha = lambda s: hashlib.sha256(s.encode()).hexdigest()
A = "        if len(users) != conversation.pending_turn + 1 or not _is_confirmation(text):\n"
B = ("        if (not host.pending or context.is_cancelled or turn != host.pending_turn + 1\n"
     "                or not _is_confirmation(native.turn.text)):\n")
REGEX = 'return re.fullmatch(r"confirm\\s+transfer[.!]?", text.strip().casefold()) is not None\n'
assert A in orig and B in orig and REGEX in orig
def mut(a=None, b=None, regex=None):
    s = orig
    if a is not None: s = s.replace(A, a)
    if b is not None: s = s.replace(B, b)
    if regex is not None: s = s.replace(REGEX, regex)
    assert s != orig
    return s
A_PHRASE = "        if len(users) != conversation.pending_turn + 1:\n"
A_ADJ = "        if not _is_confirmation(text):\n"
A_BOTH = "        if False:\n"
B_PHRASE = ("        if (not host.pending or context.is_cancelled or turn != host.pending_turn + 1):\n")
B_ADJ = ("        if (not host.pending or context.is_cancelled\n"
         "                or not _is_confirmation(native.turn.text)):\n")
B_BOTH = "        if (not host.pending or context.is_cancelled):\n"
YES = 'return re.fullmatch(r"(confirm\\s+transfer|yes)[.!]?", text.strip().casefold()) is not None\n'
MUTATIONS = [
    ("baseline", orig),
    ("A1 drop phrase check in _host only", mut(a=A_PHRASE)),
    ("A2 drop adjacency check in _host only", mut(a=A_ADJ)),
    ("A3 drop both checks in _host only", mut(a=A_BOTH)),
    ("B1 drop phrase check in submit only", mut(b=B_PHRASE)),
    ("B2 drop adjacency check in submit only", mut(b=B_ADJ)),
    ("B3 drop both checks in submit only", mut(b=B_BOTH)),
    ("C1 drop phrase check at both sites", mut(a=A_PHRASE, b=B_PHRASE)),
    ("C2 drop adjacency check at both sites", mut(a=A_ADJ, b=B_ADJ)),
    ("C3 drop both checks at both sites", mut(a=A_BOTH, b=B_BOTH)),
    ("L loosen the phrase to accept 'yes'", mut(regex=YES)),
]
MODULES = []  # whole suite: unittest discover, the same command as make test
results = []
try:
    for name, source in MUTATIONS:
        open(path, "w").write(source)
        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)
        label = re.sub(r"[^A-Za-z0-9]+", "_", name)[:40]
        open(os.path.join(out, label + ".log"), "w").write(text)
        results.append({"mutation": name, "source_sha256": sha(source), "exit": p.returncode,
                        "ran": int(ran.group(1)) if ran else None,
                        "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:
    open(path, "w").write(orig)
restored = open(path).read() == orig
json.dump({"original_sha256": sha(orig), "restored_identical": restored, "results": results},
          open(os.path.join(out, "RESULTS.json"), "w"), indent=1)
print("restored identical:", restored)
