"""Run a declared target-list mutation in a disposable offline source copy."""
from pathlib import Path
import hashlib
import json
import os
import subprocess
import sys
import tempfile

scripts = Path(sys.argv[1]).resolve()
original = (scripts / "banking_contract_scope.py").read_text()
old = "PROJECTS=('jack-henry-symitar','jack-henry-silverlake','fiserv-premier')"
changed = "PROJECTS=('jack-henry-banking','fiserv-banking')"
assert original.count(old) == 1
mutant = original.replace(old, changed)
with tempfile.TemporaryDirectory(prefix="selector-target-mutation-") as directory:
    root = Path(directory)
    (root / "banking_contract_scope.py").write_text(mutant)
    (root / "test_banking_contract_scope.py").write_bytes((scripts / "test_banking_contract_scope.py").read_bytes())
    print(json.dumps({"kind": "declared-target-list-mutation", "sourceRevision": "0285d2b86cc3d1fde13881ad68c5288429bce8e4",
        "originalSha256": hashlib.sha256(original.encode()).hexdigest(), "mutatedSha256": hashlib.sha256(mutant.encode()).hexdigest(),
        "change": {"from": old, "to": changed}, "runtimeOrContainerExecuted": False}), flush=True)
    environment = dict(os.environ)
    environment.pop("PYTHONPATH", None)
    proc = subprocess.run([sys.executable, "-I", "-B", "-m", "unittest", "discover", "-s", str(root), "-p", "test_banking_contract_scope.py", "-v"],
        cwd=root, env=environment, capture_output=True, text=True, timeout=30)
    print(proc.stdout + proc.stderr, end="", flush=True)
    print(json.dumps({"exitCode": proc.returncode, "expectedFailure": proc.returncode != 0}), flush=True)
    assert proc.returncode != 0, "Mutation survived the controls"
