"""Replay retained #307 timing evidence through the live rig's actual predicates.
Never launches a rig or changes an input receipt. Cleanup overrides stay visible.
"""
import argparse
import hashlib
import importlib.util
import json
from pathlib import Path
import sys

sys.dont_write_bytecode = True
ROOT = Path(__file__).resolve().parents[4]
CASES = [
    ("golden", ".spt/preserved/307/golden-35299506382/deployah-refresh-receipt.json", "PASS"),
    ("positive-rig-1", ".spt/preserved/307/gate-228/rig-1/observation/receipt.json", "PASS"),
    ("positive-rig-2", ".spt/preserved/307/gate-228/rig-2/observation/receipt.json", "PASS"),
    ("positive-candidate-1", ".spt/preserved/49-267-refresh-discriminator/windows/candidate-1/rig/observation/receipt.json", "PASS"),
    ("positive-candidate-2", ".spt/preserved/49-267-refresh-discriminator/windows/candidate-2/rig/observation/receipt.json", "PASS"),
    ("negative-startup-1", ".spt/preserved/307/hertz-w2-regression/negative-289e3cdf-1/observation/receipt.json", None),
    ("negative-2", ".spt/preserved/307/hertz-w2-regression/negative-289e3cdf-2/observation/receipt.json", "REGRESSION"),
    ("negative-3", ".spt/preserved/307/hertz-w2-regression/negative-289e3cdf-3/observation/receipt.json", "REGRESSION"),
    ("negative-4", ".spt/preserved/307/hertz-w2-regression/negative-289e3cdf-4/observation/receipt.json", "REGRESSION"),
    ("negative-discriminator-1", ".spt/preserved/49-267-refresh-discriminator/windows/discriminator-1/rig/observation/receipt.json", "REGRESSION"),
    ("negative-discriminator-2", ".spt/preserved/49-267-refresh-discriminator/windows/discriminator-2/rig/observation/receipt.json", "REGRESSION"),
]
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--tree", type=Path, required=True)
parser.add_argument("--out", type=Path, required=True)
args = parser.parse_args()
source = args.tree.resolve() / "crates/spt-daemon/tests/support/refresh_freeze/rig.py"
source_hash = hashlib.sha256(source.read_bytes()).hexdigest()
spec = importlib.util.spec_from_file_location("refresh_rig_replay", source)
rig = importlib.util.module_from_spec(spec)
spec.loader.exec_module(rig)
results = []
for name, relative, expected in CASES:
    path = ROOT / relative
    raw = path.read_bytes()
    old = json.loads(raw)
    row = {"case": name, "path": str(path), "sha256": hashlib.sha256(raw).hexdigest(),
           "original_status": old["status"], "original_predicate_status": old.get("predicate_status"),
           "cleanup": old["cleanup"]}
    if expected is None:
        assert "result" not in old and old["predicate_status"] == "PRECONDITION"
        row.update(replay_status="NOT_EVALUABLE_STARTUP_PRECONDITION", expected=None)
    else:
        result = old["result"]
        assert old["config"]["ack_bound_ms"] == 2000
        assert old["config"]["recovery_bound_ms"] == 15000
        recovery = rig.ack_recovery(result["post_refresh"], result["refresh"]["started_mono"],
                                    old["config"]["recovery_bound_ms"])
        checks = {**result["checks"], **recovery["checks"]}
        verdict = "PASS" if all(checks.values()) else "REGRESSION"
        row.update(original_checks=result["checks"], checks=checks, recovery=recovery,
                   replay_status=verdict, expected=expected)
        assert verdict == expected, (name, checks)
    assert path.read_bytes() == raw, "receipt changed: " + name
    results.append(row)
assert hashlib.sha256(source.read_bytes()).hexdigest() == source_hash
report = {"status": "PASS", "source": str(source), "source_sha256": source_hash,
          "golden_pass": 1, "prior_passes_preserved": 4, "negative_regressions_preserved": 5,
          "startup_preconditions_separately_preserved": 1, "results": results}
with args.out.open("x", encoding="utf-8", newline="\n") as stream:
    stream.write(json.dumps(report, indent=2, sort_keys=True) + "\n")
print(json.dumps({k: v for k, v in report.items() if k != "results"}, indent=2))
