"""r_freeze.py: assert the Phase 3 freeze before any Phase 4 computation.

Every Phase 4 script imports this module first. It recomputes the sha256 of the four files frozen at the
Phase 3 stop and compares them with the digests registered in values3.json (freeze_sha256_*). Any mismatch
stops the script before it reads the data.
"""
import hashlib, json

P3 = "/home/claude/mill/phase3"
FROZEN = {
    "freeze_sha256_plan": f"{P3}/inputs/plan.json",
    "freeze_sha256_q_common": f"{P3}/code/q_common.py",
    "freeze_sha256_q_confirm": f"{P3}/code/q_confirm.py",
    "freeze_sha256_q_rules": f"{P3}/code/q_rules.py",
}


def sha256(path):
    return hashlib.sha256(open(path, "rb").read()).hexdigest()


def assert_freeze():
    v3 = json.load(open(f"{P3}/outputs/values3.json"))
    for name, path in FROZEN.items():
        want = v3[name]["value"]
        got = sha256(path)
        if got != want:
            raise SystemExit(f"FREEZE BROKEN: {path} has sha256 {got}, registered {want}")
    return {name: v3[name]["value"] for name in FROZEN}


if __name__ == "__main__":
    for k, v in assert_freeze().items():
        print("ok", k, v)
