#!/usr/bin/env python3
"""E446-N standalone verifier (record level; imports no CAIN code)."""
from __future__ import annotations
import hashlib, json, sys
from pathlib import Path
from cryptography.exceptions import InvalidSignature
from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey
S="AGI: NOT ESTABLISHED · RSI: EXPERIMENTAL"; OK=FAIL=0
def check(n,c,d=""):
    global OK,FAIL
    if c: OK+=1; print(f"PASS {n}"+(f" · {d}" if d else ""))
    else: FAIL+=1; print(f"FAIL {n}"+(f" · {d}" if d else ""))
def sha(b): return hashlib.sha256(b).hexdigest()
def canon(o): return json.dumps(o,sort_keys=True,separators=(",",":"),ensure_ascii=False).encode()
def merkle(hs):
    l=sorted(hs)
    if not l: return sha(b"")
    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]
def main(d):
    d=Path(d); man=json.loads((d/"E446N_MANIFEST.json").read_text()); rep=json.loads((d/"E446N_RUN_REPORT.json").read_text())
    pre=json.loads((d/"E446N_PREREGISTRATION.json").read_text()); dev=json.loads((d/"E446N_DEVIATIONS.json").read_text())
    salts=json.loads((d/"SALTS.json").read_text()); recs=rep["records"]
    check("schema",rep["schema"]=="cain42.e446n.run.v1")
    check("status line",rep["status"]==S and S in (d/"E446N_FINAL_REPORT.md").read_text())
    check("manifest",man["schema"]=="cain42.e446n.manifest.v1" and man["evolution"]=="E446-N")
    check("manifest label",man["label"]==rep["verdict"])
    check("salt commitment",sha(json.dumps(salts,sort_keys=True).encode())==pre["salt_commitment_sha256"])
    check("deviation recorded",len(dev["deviations"])==1)
    body={k:v for k,v in man.items() if k!="signature"}
    pub=Ed25519PublicKey.from_public_bytes(bytes.fromhex(man["pubkey_ed25519"]))
    try: pub.verify(bytes.fromhex(man["signature"]),canon(body)); ok=True
    except InvalidSignature: ok=False
    check("manifest signature",ok)
    bad=[n for n,h in man["files"].items() if not (d/n).exists() or sha((d/n).read_bytes())!=h]
    check("file hashes",not bad,f"{len(man['files'])} files")
    check("merkle root",merkle(list(man["files"].values()))==man["merkle_root"])
    check("no model calls",rep["headline"]["model_calls"]==0)
    check("six records",len(recs)==6,str(len(recs)))
    check("distinct decisions",len({r["decision_id"] for r in recs})==6)
    check("distinct digests",len({r["digest"] for r in recs})==6)
    check("seals valid",sum(1 for r in recs if r["seal_verify"]=="VALID")==6)
    check("seals bound",all(r["seal_decision_matches"] for r in recs))
    check("authority never granted",all(r["authorizes"] is False for r in recs))
    # recompute the declared attack
    ids=[r["decision_id"] for r in recs]; true={r["decision_id"]:r["digest"] for r in recs}
    omit={0,1}
    union=[i for k,i in enumerate(ids) if not (k in omit and False)]  # i0 omits, i1/i2 full -> union all
    recovered=0; false=0
    for k,rid in enumerate(ids):
        okr=False
        for rep_i in range(3):
            dg=true[rid]
            if rep_i==0 and k in (2,3):
                dg=sha(("forged|"+rid).encode())
            if dg==true[rid]:
                okr=True; break
        if okr: recovered+=1
        else: false+=1
    check("recovery recomputed",recovered==6,str(recovered))
    check("no false accept recomputed",false==0,str(false))
    core=[rep["hypotheses"][k]["verdict"]=="SUPPORTED" for k in ("H1_live_sealed","H2_recovery","H3_no_false_accept","H4_authority","H5_denial")]
    verdict=("LIVE_SEALED_RETRIEVAL_SUPPORTED" if all(core) else ("PARTIAL" if sum(core)>=3 else "NOT_SUPPORTED"))
    check("verdict recompute",verdict==rep["verdict"],verdict)
    check("external review blocked",rep["hypotheses"]["H6_external_review"]["verdict"]=="BLOCKED")
    src=[p.name for p in d.rglob("*") if p.is_file() and p.suffix==".py" and "verify" not in p.name]
    check("engine source withheld",not src,str(src))
    print(f"\n{OK}/{OK+FAIL} checks passed"); print("Record-level verification: the live fetch is not re-executed (the records are the evidence)."); print(S)
    return 0 if FAIL==0 else 1
if __name__=="__main__": sys.exit(main(sys.argv[1] if len(sys.argv)>1 else "."))
