#!/usr/bin/env python3
"""E422-C standalone offline verifier (stdlib + cryptography; imports no CAIN code)."""
from __future__ import annotations
import hashlib, json, sys
from collections import Counter
from pathlib import Path
from cryptography.exceptions import InvalidSignature
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey, Ed25519PublicKey

STATUS = "AGI: NOT ESTABLISHED · RSI: EXPERIMENTAL"
POISON = "single|random|10|20"
ARMS = ("isolated", "trust", "score8", "consensus8", "consensus16")
SHARED = ("trust", "score8", "consensus8", "consensus16")
SALTS = ("primary", "replication")
COMPOUND, BEAT_SCORE, BEAT_ISO = 0.04, 0.08, 0.10

def sha(b): return hashlib.sha256(b).hexdigest()
def canon(o): return json.dumps(o, sort_keys=True, separators=(",", ":"), ensure_ascii=False).encode()
def load(p): return json.loads(Path(p).read_text())
def derive_pub(a): return Ed25519PrivateKey.from_private_bytes(hashlib.sha256(("e380m|"+a).encode()).digest()).public_key().public_bytes(serialization.Encoding.Raw, serialization.PublicFormat.Raw)

class C:
    def __init__(self): self.r=[]
    def add(self,n,ok,d=""): self.r.append({"check":n,"ok":bool(ok),"detail":d})
    def finish(self):
        ok=sum(1 for x in self.r if x["ok"]); n=len(self.r)
        for x in self.r: print(f'{"PASS" if x["ok"] else "FAIL"}  {x["check"]}  {x["detail"]}')
        print(f"\n{ok}/{n} checks passed · {STATUS}")
        return 0 if ok==n else 1

def cons(cands,minv=4):
    if not cands: return {"worlds":[],"per_world":[]}
    n=len(cands[0]["per_world"]); per=[]
    for i in range(n):
        ms=[c["per_world"][i]["mask"] for c in cands if c["per_world"][i]["mask"] is not None]
        cc=Counter(ms)
        if cc:
            m,v=cc.most_common(1)[0]
            if v>=minv: per.append({"index":i,"mask":m,"votes":v}); continue
        per.append({"index":i,"mask":None,"votes":0})
    return {"worlds":[w["index"] for w in per if w["mask"]],"per_world":per}

def agr(c,co):
    u=[w for w in co["per_world"] if w["mask"]]
    return 0.0 if not u else sum(1 for w in u if c["per_world"][w["index"]]["mask"]==w["mask"])/len(u)

def champ(gen):
    cs=gen["candidates"]; co=cons(cs); rk=[]
    for c in cs:
        a=agr(c,co); ident=sum(1 for w in c["per_world"] if w["claimed"])/max(1,len(c["per_world"]))
        rk.append((a,ident,-float(c["labels_mean"]),c["procedure"],c["agent"]))
    rk.sort(reverse=True); a,ident,_,proc,agent=rk[0]
    if co["worlds"]:
        return {"procedure":proc,"source":f"consensus:{agent}","agreement":round(a,6),"consensus_worlds":len(co["worlds"])}
    best=max(cs,key=lambda x:(float(x["score"]),-float(x["labels_mean"]),x["procedure"]))
    return {"procedure":best["procedure"],"source":"fallback","agreement":0.0,"consensus_worlds":0}

def sacc(g):
    r=g["sealed"]["per_world"]; return round(sum(1 for x in r if x.get("accepted_true"))/len(r),6)

def A(rep,s,n): return rep["raw"][f"{s}|{n}"]

def blk(rep,s):
    d={a:A(rep,s,a) for a in ARMS}
    ac=lambda r,g: r["generations"][g]["sealed"]["accepted_correct"]
    c8,c16,sc,iso,tru=d["consensus8"],d["consensus16"],d["score8"],d["isolated"],d["trust"]
    h1=ac(c8,2)-ac(c8,0)>=COMPOUND
    h2=ac(c8,2)-ac(sc,2)>=BEAT_SCORE
    h3=ac(c16,2)>=ac(c8,2)-0.02 and ac(c16,2)>ac(sc,2)
    adopted=tru["generations"][1]["champion"]["procedure"]==POISON
    h4=adopted and ac(tru,1)<=ac(c8,1)-0.05 and all(
        d[x]["generations"][g]["champion"].get("source","").split(":")[0] in ("consensus","verification","own","fallback","empty")
        for x in ("score8","consensus8","consensus16") for g in range(3))
    h5=ac(c8,2)-ac(iso,2)>=BEAT_ISO
    h6=all(d[x]["memory"].get("all_pass") for x in SHARED)
    return {"H1":h1,"H2":h2,"H3":h3,"H4":h4,"H5":h5,"H6":h6}

def main(argv):
    B=Path(argv[1] if len(argv)>1 else ".").resolve(); ch=C()
    man=load(B/"MANIFEST.json"); body=load(B/"E422-M_SIGNED_BODY.json")
    try:
        Ed25519PublicKey.from_public_bytes(bytes.fromhex(man["pubkey_ed25519"])).verify(bytes.fromhex(man.get("signature","")),canon(body))
        ch.add("manifest_signature",True,man["pubkey_fingerprint"])
    except Exception as e: ch.add("manifest_signature",False,repr(e)[:80])
    decl=man.get("files",{}); bad=[n for n,h in decl.items() if not (B/n).exists() or sha((B/n).read_bytes())!=h]
    ch.add("file_hashes",not bad,f"{len(decl)} files"+ (f", bad={bad[:3]}" if bad else ""))
    lv=sorted(decl.values())
    while len(lv)>1:
        if len(lv)%2: lv.append(lv[-1])
        lv=[sha((lv[i]+lv[i+1]).encode()) for i in range(0,len(lv),2)]
    ch.add("merkle_root",(lv[0] if lv else sha(b""))==man.get("merkle_root"),str(man.get("merkle_root"))[:16])
    pre=load(B/"E422-M_PREREGISTRATION.json"); frz=load(B/"E422-M_PREREGISTRATION_FREEZE.json")
    ch.add("preregistration_frozen",sha((B/"E422-M_PREREGISTRATION.json").read_bytes())==frz["preregistration_sha256"],frz["preregistration_sha256"][:16])
    sal=load(B/"E422-M_SALT_REVEALED.json")["salts"]
    ch.add("salt_commitments",all(sha(bytes.fromhex(sal[k]))==pre["salt_commitment_sha256"][k] for k in SALTS),", ".join(SALTS))
    rep=load(B/"E422-M_RUN_REPORT.json")
    ch.add("status_line",rep.get("status")==STATUS,rep.get("status",""))
    ch.add("no_model_no_spend",rep["design"]["model_calls"]==0 and rep["design"]["api_spend_usd"]==0.0,"0 calls, $0")
    p=blk(rep,"primary"); r=blk(rep,"replication"); head=man.get("headline",{})
    pv=[g["sealed"]["accepted_correct"] for g in A(rep,"primary","consensus8")["generations"]]
    ch.add("headline_matches_report",head.get("verdict")==rep["verdict"] and head.get("primary_consensus8")==pv,f'{head.get("verdict")} {head.get("primary_consensus8")}')
    prev,cp="0"*64,True
    for c in rep.get("checkpoints",[]):
        if c["prev"]!=prev: cp=False; break
        prev=c["hash"]
    ch.add("checkpoint_chain",cp and len(rep.get("checkpoints",[]))==10,f'{len(rep.get("checkpoints",[]))} checkpoints')
    ok1,ok2=True,True; det=[]
    for s in SALTS:
        for n in ARMS:
            for g in A(rep,s,n)["generations"]:
                if abs(sacc(g)-g["sealed"]["accepted_correct"])>1e-9: ok1=False; det.append(f"{s}|{n}|{g['gen']}")
                if n in ("consensus8","consensus16") and champ(g)["procedure"]!=g["champion"]["procedure"]: ok2=False; det.append(f"c:{s}|{n}|{g['gen']}")
    ch.add("recompute_sealed_counts",ok1,f"{len(det)} mismatches")
    ch.add("recompute_consensus_champions",ok2,"every consensus champion rebuilt from masks")
    for k in ("H1","H2","H3","H4","H5","H6"):
        ch.add(f"recompute:{k}",p[k]==(rep["hypotheses"][k]["verdict"]=="SUPPORTED"),f'primary={"PASS" if p[k] else "FAIL"}')
    h7=all(r[k] for k in ("H1","H2","H4","H5"))
    ch.add("recompute:H7",h7==(rep["hypotheses"]["H7"]["verdict"]=="SUPPORTED"),f'replication={"PASS" if h7 else "FAIL"}')
    ch.add("external_review_blocked",rep["hypotheses"]["H8"]["verdict"]=="BLOCKED",rep["hypotheses"]["H8"]["verdict"])
    def rows(s,n):
        doc=load(B/"memory"/f"{s}-{n}.json"); recs=doc.get("records") or []
        if recs and "rows" in recs[0]: return [(f'{s}-{n}-{x.get("agent","?")}',x.get("rows") or []) for x in recs]
        return [(f"{s}-{n}",recs)]
    chains=True
    for s in SALTS:
        for n in SHARED:
            for label,rr in rows(s,n):
                prev="0"*64
                for rec in rr:
                    b={"tenant":rec["tenant"],"seq":rec["seq"],"agent":rec["agent"],"kind":rec["kind"],"payload":rec["payload"],"uncertainty":rec["uncertainty"],"verification":rec["verification"],"prev":rec["prev"]}
                    if rec["prev"]!=prev or sha(canon(b)+bytes.fromhex(rec["sig"]))!=rec["hash"]: chains=False; break
                    try: Ed25519PublicKey.from_public_bytes(derive_pub(rec["agent"])).verify(bytes.fromhex(rec["sig"]),canon(b))
                    except InvalidSignature: chains=False; break
                    prev=rec["hash"]
                if not chains: break
    ch.add("memory_chains_and_signatures",chains,"every shared-arm row re-verified")
    pc=0
    for s in SALTS:
        for label,rr in rows(s,"trust"):
            pc+=sum(1 for x in rr if x["payload"].get("type")=="claim" and x["payload"].get("procedure")==POISON and x["payload"].get("fabricated") is True)
        ch.add(f"poison_adopted:trust:{s}",A(rep,s,"trust")["generations"][1]["champion"]["procedure"]==POISON,str(A(rep,s,"trust")["generations"][1]["champion"]))
    ch.add("poison_signed_claims",pc==4,f"{pc} fabricated signed claims")
    passed=sum(1 for k in ("H1","H2","H3","H4","H5","H6") if rep["hypotheses"][k]["verdict"]=="SUPPORTED")
    exp=("RULE_CONSENSUS_RSI_SUPPORTED" if passed==6 and h7 and p["H2"] else "PARTIAL" if passed>=4 and (p["H2"] or p["H1"]) else "NOT_SUPPORTED")
    ch.add("verdict_rule",rep["verdict"]==exp,f'{rep["verdict"]} (expected {exp})')
    return ch.finish()

if __name__=="__main__": raise SystemExit(main(sys.argv))
