#!/usr/bin/env python3
"""GMC standalone verifier: the browser verifier's own report, and a live re-run under Node."""
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/"GMC_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 run is 15/15",rep["clean"]["passed"]==15 and rep["clean"]["total"]==15 and not rep["clean"]["failed"])
    check("a tampered row is rejected",rep["tamper_row"]["rejected"] is True and rep["tamper_row"]["failed"])
    check("a tampered scope root is rejected",rep["tamper_scope_root"]["rejected"] is True and rep["tamper_scope_root"]["failed"])
    check("WebCrypto present",rep.get("webcrypto") is True)
    try:
        r=subprocess.run(["node",str(root/"browser_test.mjs"),str(root)],capture_output=True,text=True,timeout=300)
        live=json.loads(r.stdout)
        check("live re-run under Node agrees",live["all_ok"] is True and live["clean"]["passed"]==15)
    except Exception as e:
        check("live re-run under Node 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","GMC_MANIFEST.json","MERKLE_ROOT.txt","GMC_SIGNED_BODY.json","GMC_VERIFICATION_RESULTS.json","GMC_TAMPER_RESULTS.json","GMC_PUBLIC_CHECK.json","PUBLICATION.json","GMC_OMEGA_SEAL.json","GMC_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("no model calls",rep.get("model_calls",0)==0)
    check("status line",rep.get("status")=="AGI: NOT ESTABLISHED · RSI: EXPERIMENTAL")
    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())
