#!/usr/bin/env python3
"""v31 — stdlib-only verifier for the Universal Closure Certificate (zero trust in the original tooling).

Two independent checks, both pure Python stdlib:
  (1) INTERNAL: recompute the Merkle root from the certificate's published leaves; it must equal `root`.
  (2) FULL PROVENANCE: re-derive the leaves DIRECTLY from the live evidence files (the same volatile-stripped
      hashing the manifest uses) and rebuild the root; it must equal `root`. This proves the certificate
      commits to exactly the bytes on disk — a single tamper anywhere flips the root.

Exit 0 iff both checks pass. A skeptic can read this file end-to-end and trust nothing but `hashlib`.
"""
import json
import os
import sys

import build_closure_cert as bc

ROOT = bc.ROOT
CERT = os.path.join(ROOT, "artifacts", "closure_certificate.json")


def main():
    if not os.path.exists(CERT):
        print("verify_closure: no closure_certificate.json (run scripts/build_closure_cert.py)")
        return 1
    cert = json.load(open(CERT))
    published_root = cert.get("root")
    leaves = cert.get("leaves", [])

    internal_root = bc.merkle_root(leaves)
    internal_ok = (internal_root == published_root)

    live_leaves = bc.leaves_from_files(bc.current_files())
    live_root = bc.merkle_root(live_leaves)
    provenance_ok = (live_root == published_root) and (live_leaves == leaves)

    print(f"verify_closure: internal_root_ok={internal_ok}  full_provenance_ok={provenance_ok}  "
          f"n_leaves={len(leaves)}  root={(published_root or '')[:16]}...")
    if not internal_ok:
        print("  FAIL: published leaves do not fold to the published root")
    if not provenance_ok:
        print("  FAIL: live evidence files do not reproduce the certificate (tamper or drift)")
    ok = internal_ok and provenance_ok
    print("VERIFY OK — the asset re-verifies byte-for-byte under one Merkle root" if ok else "VERIFY FAILED")
    return 0 if ok else 1


if __name__ == "__main__":
    sys.exit(main())
