#!/usr/bin/env python3
"""Standalone E168 verifier. Imports NO CAIN application code (stdlib + cryptography only)."""
from __future__ import annotations
import hashlib, json, random, sys
from pathlib import Path
STATUS="AGI: NOT ESTABLISHED · RSI: EXPERIMENTAL"
BLIND=("G|canonical|clean","H|canonical|clean","I|canonical|clean")

def canon(o): return json.dumps(o,sort_keys=True,separators=(",",":")).encode()
def merkle(paths):
    leaves=sorted(hashlib.sha256(p.read_bytes()).hexdigest() for p in paths)
    if not leaves: return hashlib.sha256(b"").hexdigest()
    while len(leaves)>1:
        if len(leaves)%2: leaves.append(leaves[-1])
        leaves=[hashlib.sha256((leaves[i]+leaves[i+1]).encode()).hexdigest() for i in range(0,len(leaves),2)]
    return leaves[0]
def mean(x): return sum(x)/len(x) if x else 0.0
def sd(x):
    if len(x)<2: return 0.0
    m=mean(x); return (sum((v-m)**2 for v in x)/(len(x)-1))**0.5
def perm_p(d,n=4000,seed=17):
    rng=random.Random(seed); obs=mean(d)
    if obs<=0: return 1.0
    hits=0
    for _ in range(n):
        s=sum(abs(v) if rng.random()<0.5 else -abs(v) for v in d)
        if s/len(d)>=obs: hits+=1
    return (hits+1)/(n+1)
def paired(a,b):
    d=[x-y for x,y in zip(a,b)]; m,s=mean(d),sd(d); se=s/(len(d)**0.5) if d else 0.0
    return {"n":len(d),"mean_diff":m,"ci95":[m-1.96*se,m+1.96*se],"p":perm_p(d),"wins":sum(1 for x in d if x>1e-12),"losses":sum(1 for x in d if x<-1e-12)}
def jl(p): return [json.loads(l) for l in Path(p).read_text().splitlines() if l.strip()] if Path(p).exists() else []
def tasks(rows,arm,reps):
    acc={}
    for r in rows:
        if r["arm"]==arm and r["rep"] in reps: acc.setdefault((r["campaign"],r["uid"]),[]).append(r["quality"])
    return {k:mean(v) for k,v in acc.items()}
def cmp(rows,a,b,reps):
    x,y=tasks(rows,a,reps),tasks(rows,b,reps); ks=sorted(set(x)&set(y))
    return paired([x[k] for k in ks],[y[k] for k in ks])

def main():
    B=Path(sys.argv[1] if len(sys.argv)>1 else ".")
    checks=[]
    def check(n,ok,d=""): checks.append({"check":n,"ok":bool(ok),"detail":str(d)[:300]})
    man=json.loads((B/"E168_MANIFEST.json").read_text())
    check("status line",man.get("status")==STATUS,man.get("status"))
    body={k:v for k,v in man.items() if k!="signature"}
    try:
        from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey
        Ed25519PublicKey.from_public_bytes(bytes.fromhex(man["pubkey_ed25519"])).verify(bytes.fromhex(man["signature"]),canon(body))
        check("Ed25519 signature",True)
    except Exception as e: check("Ed25519 signature",False,e)
    files=man.get("files",{})
    check("listed files exist",all((B/k).exists() for k in files),[k for k in files if not (B/k).exists()][:5])
    bad=[k for k,h in files.items() if (B/k).exists() and hashlib.sha256((B/k).read_bytes()).hexdigest()!=h]
    check("listed file hashes",not bad,bad[:5])
    listed=sorted(B/k for k in files if (B/k).exists())
    check("Merkle root",merkle(listed)==man.get("merkle_root"),man.get("merkle_root"))
    present={str(p.relative_to(B)) for p in B.rglob("*") if p.is_file()}
    unlisted=sorted(present-set(files)-{"E168_MANIFEST.json","E168_VERIFICATION_RESULTS.json","PUBLICATION.json"})
    check("no unlisted file",not unlisted,unlisted[:5])
    pre=B/"E168_PREREGISTRATION.json"
    check("preregistration commitment",pre.exists() and hashlib.sha256(pre.read_bytes()).hexdigest()==man.get("preregistration_sha256"))
    h=json.loads((B/"E168_HYPOTHESIS_RESULTS.json").read_text())["hypotheses"]
    confirm=jl(B/"raw/campaign_00/sealed.jsonl"); repl=jl(B/"raw/replication_sealed.jsonl"); rows=confirm+repl
    check("raw sealed rows",len(confirm)>0 and len(repl)>0,f"{len(confirm)}+{len(repl)}")
    h1=cmp(rows,"R_rsi","R0",BLIND)
    check("H1 RSI reader = frozen reader",abs(h1["mean_diff"])<1e-9,f"{h1['mean_diff']}")
    check("H1 declared NOT_ESTABLISHED",h["H1"].get("verdict")=="NOT_ESTABLISHED",h["H1"].get("verdict"))
    h2=cmp(rows,"R_rsi","P_search",BLIND)
    check("H2 recomputes",abs(h2["mean_diff"]-h["H2"].get("mean_diff",1e9))<2e-5,f"{round(h2['mean_diff'],6)} vs {h['H2'].get('mean_diff')}")
    check("H2 attributed to the reader, not the RSI","reader" in str(h["H2"].get("attribution","")).lower())
    r0=cmp(rows,"R0","P_search",BLIND)
    check("reader beats 2x budget",r0["mean_diff"]>0 and r0["ci95"][0]>0,f"{round(r0['mean_diff'],4)} p {r0['p']:.1e}")
    fam={f:cmp(rows,"R0","P_search",(f+"|canonical|clean",)) for f in ("G","H","I")}
    check("reader positive on G/H/I",all(v["mean_diff"]>0 for v in fam.values()),{k:round(v["mean_diff"],4) for k,v in fam.items()})
    docs=mean([r.get("doc_correct",0) for r in rows if r["arm"]=="R0" and r["rep"] in BLIND])
    check("reader doc_correct > 0.7",docs>0.7,round(docs,4))
    rep=json.loads((B/"E168_REPLICATION.json").read_text())
    check("fresh-salt reader replication positive",rep["R0_vs_P_search"]["mean_diff"]>0 and rep["R0_vs_P_search"]["ci95"][0]>0,round(rep["R0_vs_P_search"]["mean_diff"],4))
    check("fresh-salt RSI null",abs(rep["R_rsi_vs_R0"]["mean_diff"])<1e-9,rep["R_rsi_vs_R0"]["mean_diff"])
    # H11 best component
    by={}
    for r in rows:
        if r["rep"] in BLIND: by.setdefault((r["campaign"],r["uid"],r["arm"]),[]).append(r["quality"])
    dif=[]
    for k in {(c,u) for (c,u,a) in by if (c,u,"R_rsi") in by}:
        best=max(mean(by[(k[0],k[1],a)]) for a in ("R0","P2_lib","P_search") if (k[0],k[1],a) in by)
        dif.append(mean(by[(k[0],k[1],"R_rsi")])-best)
    check("H11 RSI does not beat the best component",mean(dif)<=0,round(mean(dif),4))
    rec=json.loads((B/"raw/campaign_00/record.json").read_text())
    q1=[c for c in rec["gen2"]["candidates"] if c["proposer"]=="Q1"]
    check("Q1 higher dev gain but not accepted",max([c.get("dev_gain") or -9 for c in q1] or [-9])>max([c.get("dev_gain") or -9 for c in rec["gen2"]["candidates"] if c["proposer"]=="Q0"] or [-9]) and not any(c.get("dev_ok") for c in q1))
    g=json.loads((B/"E168_GOVERNANCE_REPORT.json").read_text())
    check("governance passed",g.get("passed")==g.get("total"),f"{g.get('passed')}/{g.get('total')}")
    check("gate log chain",g.get("gate_log",{}).get("chain_ok") is True,g.get("gate_log"))
    check("no AGI/RSI establishment claim","NOT ESTABLISHED" in json.loads((B/"E168_EXPERIMENT_SUMMARY.json").read_text()).get("status","") if (B/"E168_EXPERIMENT_SUMMARY.json").exists() else True)
    check("blind families present",all((B/"blind_families"/f"{c}.json").exists() for c in "GHI"))
    pub=B/"PUBLICATION.json"
    if pub.exists():
        pj=json.loads(pub.read_text()); check("publication merkle",pj.get("merkle_root")==man.get("merkle_root")); check("four surfaces",len(pj.get("surfaces",{}))==4)
    else: check("publication (pre-publication)",True)
    ok=all(c["ok"] for c in checks)
    print(json.dumps({"checks":len(checks),"passed":sum(c["ok"] for c in checks),"ok":ok}))
    for c in checks:
        if not c["ok"]: print("FAIL",c["check"],c["detail"])
    return 0 if ok else 1

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