#!/usr/bin/env python3
"""Standalone verifier for the E86 bundle. No CAIN imports."""
import base64, hashlib, json, sys
from pathlib import Path
from cryptography.exceptions import InvalidSignature
from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey

def canon(o): return json.dumps(o, sort_keys=True, separators=(",", ":"), default=str).encode()
def merkle(leaves):
    def mth(xs):
        if not xs: return hashlib.sha256(b"").digest()
        if len(xs)==1: return hashlib.sha256(b"\x00"+xs[0]).digest()
        k=1
        while k*2<len(xs): k*=2
        return hashlib.sha256(b"\x01"+mth(xs[:k])+mth(xs[k:])).digest()
    return mth(list(leaves)).hex()

def main():
    B=Path(sys.argv[1]).resolve(); C=[]
    def check(n,ok,d=""): C.append((n,bool(ok),d))
    man=json.loads((B/"manifest.json").read_text()); body=man["body"]
    try:
        Ed25519PublicKey.from_public_bytes(base64.b64decode(man["public_key_b64"])).verify(
            base64.b64decode(man["signature_b64"]), canon(body)); check("manifest_signature_valid",True)
    except Exception: check("manifest_signature_valid",False)
    bad=[f["path"] for f in body["files"] if not (B/f["path"]).is_file() or
         hashlib.sha256((B/f["path"]).read_bytes()).hexdigest()!=f["sha256"]]
    check("every_file_matches_digest",not bad,str(bad[:3]))
    leaves=[f"{f['path']}:{f['sha256']}".encode() for f in sorted(body["files"],key=lambda x:x["path"])]
    check("merkle_root_recomputed",merkle(leaves)==body["merkle_root"])
    check("no_private_key_material",not any(b"PRIVATE KEY" in (B/f["path"]).read_bytes() or b"sk-ant-" in (B/f["path"]).read_bytes()
          for f in body["files"] if not f["path"].endswith(".py")))
    ext=json.loads((B/"external-agent/result.json").read_text())
    check("external_agent_flow_ok", ext.get("ok") is True and ext.get("receipt_valid") is True
          and ext.get("mission_state")=="COMPLETED_VERIFIED" and ext.get("effects")==1,
          str({k:ext.get(k) for k in ("ok","receipt_valid","mission_state","effects")}))
    kf=json.loads((B/"killfence/lab.json").read_text())
    check("kill_fence_zero_after_effective", kf["effects_after_engage"]==0 and kf["committed"]>0 and kf["denied"]>0,
          f"committed={kf['committed']} denied={kf['denied']} after={kf['effects_after_engage']}")
    check("e85_500_baseline_disclosed", (kf.get("e85_500_baseline") or {}).get("commits_after_engage",0)>0,
          str(kf.get("e85_500_baseline")))
    v=json.loads((B/"foundation/verticals.json").read_text())
    check("three_verticals_objectively_verified", v.get("passed")==3 and v.get("total")==3, f"{v.get('passed')}/{v.get('total')}")
    t=json.loads((B/"tests.json").read_text())
    check("regression_tests_pass", t.get("failed")==0 and t.get("passed",0)>=40, t.get("summary",""))
    f=json.loads((B/"frontier-reference.json").read_text())
    check("frontier_reference_present", f["A_single"]["correct"]==36 and f["B_learned"]["correct"]==65
          and f["model"]=="claude-sonnet-5-5" and f["estimated_cost_usd"]<=8.0,
          f"A={f['A_single']['correct']} B={f['B_learned']['correct']}")
    a=json.loads((B/"acceptance.json").read_text())
    cnt={}
    for x in a["gates"]: cnt[x["status"]]=cnt.get(x["status"],0)+1
    check("acceptance_counts_recomputed", cnt==a["counts"], str(cnt))
    check("release_not_claimed", a["decision"]=="NOT RELEASED")
    rep=(B/"docs/E86_FINAL_REPORT.md").read_text()
    check("final_report_no_agi_claim", "does not claim that AGI" in rep and "NOT RELEASED" in rep)
    for n,ok,d in C: print(("PASS " if ok else "FAIL ")+n+(f"  ({d})" if d else ""))
    print(f"\n{sum(1 for _,o,_ in C if o)}/{len(C)} checks passed")
    return 0 if all(o for _,o,_ in C) else 1
if __name__=="__main__": sys.exit(main())
