#!/usr/bin/env python3
"""GBX standalone verifier: the browser report, a live Node re-run, and the signed bundle."""
from __future__ import annotations
import hashlib,json,subprocess,sys
from pathlib import Path
from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey
def canon(o): return json.dumps(o,sort_keys=True,separators=(",",":"),ensure_ascii=False).encode()
def sha(b): return hashlib.sha256(b).hexdigest()
def merkle(fs):
    l=sorted(sha(p.read_bytes()) for p in fs)
    while len(l)>1:
        if len(l)%2: l.append(l[-1])
        l=[sha((l[i]+l[i+1]).encode()) for i in range(0,len(l),2)]
    return l[0] if l else sha(b"")
def main():
    root=Path(sys.argv[1] if len(sys.argv)>1 else ".").resolve(); ck,fail=[],[]
    def check(n,ok,d=""):
        ck.append({"check":n,"ok":bool(ok),"detail":d})
        if not ok: fail.append(n)
    rep=json.loads((root/"GBX_REPORT.json").read_text()); man=json.loads((root/"MANIFEST.json").read_text())
    check("report claims all_ok",rep.get("all_ok") is True)
    check("clean successor is 16/16",rep["clean"]["passed"]==16 and rep["clean"]["total"]==16 and not rep["clean"]["failed"])
    check("four anti-retraction attacks rejected",len(rep["attacks"])==4 and all(v["rejected"] for v in rep["attacks"].values()))
    check("WebCrypto present",rep.get("webcrypto") is True)
    try:
        r=subprocess.run(["node",str(root/"browser_test_gmx.mjs"),str(root)],capture_output=True,text=True,timeout=300)
        live=json.loads(r.stdout); check("live Node re-run agrees",live["all_ok"] is True and live["clean"]["passed"]==16)
    except Exception as e:
        check("live Node re-run agrees",False,str(e))
    fs=sorted(p for p in root.rglob("*") if p.is_file() and "__pycache__" not in p.parts and p.name not in
              ("MANIFEST.json","GBX_MANIFEST.json","MERKLE_ROOT.txt","GBX_SIGNED_BODY.json","GBX_VERIFICATION_RESULTS.json","GBX_TAMPER_RESULTS.json","GBX_PUBLIC_CHECK.json","PUBLICATION.json","GBX_OMEGA_SEAL.json","GBX_PUBKEY.pem"))
    body={k:man[k] for k in ("schema","evolution","status","name","created_at","verifier","pubkey_ed25519","files","merkle_root","engine_withheld","external_review")}
    try:
        Ed25519PublicKey.from_public_bytes(bytes.fromhex(man["pubkey_ed25519"])).verify(bytes.fromhex(man["signature"]),canon(body)); check("manifest signature",True)
    except Exception: check("manifest signature",False)
    check("file hashes match",all(man["files"].get(str(p.relative_to(root)))==sha(p.read_bytes()) for p in fs))
    check("manifest lists exactly the bundle files",sorted(man["files"])==sorted(str(p.relative_to(root)) for p in fs))
    check("merkle root recomputes",man["merkle_root"]==merkle(fs))
    check("status line",rep.get("status")=="AGI: NOT ESTABLISHED · RSI: EXPERIMENTAL")
    check("no model calls",rep.get("model_calls",0)==0)
    print(json.dumps({"checks":len(ck),"passed":sum(1 for c in ck if c["ok"]),"failed":fail},indent=1))
    return 0 if not fail else 1
if __name__=="__main__": sys.exit(main())
