"""Check a Mokili evidence bundle: every record and file unchanged, and each
record naming the next. No Mokili needed.   python check_bundle.py bundle.json"""
import base64, hashlib, json, sys

bundle = json.load(open(sys.argv[1]))
named = bundle["digests"]

def digest(record):
    text = json.dumps(record, sort_keys=True, separators=(",", ":"), ensure_ascii=False)
    return "sha256:" + hashlib.sha256(text.encode("utf-8")).hexdigest()

def check(what, ok):
    print(f"{what:30} {'ok' if ok else 'DOES NOT MATCH'}")

for kind in ("model", "scenario", "run", "result"):
    check(f"{kind} is unchanged", digest(bundle[kind]) == named[kind])
for record, name in zip(bundle.get("decisions", []), named.get("decisions", [])):
    check(f"{record['schema']} is unchanged", digest(record) == name)
check("scenario names the model", bundle["scenario"]["model"] == named["model"])
check("run names the scenario", bundle["run"]["scenario"] == named["scenario"])
check("run names the result", bundle["run"]["result"] == named["result"])
for name, content in bundle["artifacts"].items():
    check(f"file {name[7:19]} is unchanged", "sha256:" + hashlib.sha256(base64.b64decode(content)).hexdigest() == name)
