#!/usr/bin/env python3
"""E384-F standalone verifier (stdlib + cryptography; imports no CAIN code)."""
from __future__ import annotations
import hashlib, json, sys
from pathlib import Path
from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey
S="AGI: NOT ESTABLISHED · RSI: EXPERIMENTAL"; NOW=1_800_000_000
EX={"E384F_MANIFEST.json","E384F_SIGNED_BODY.json","E384F_VERIFICATION_RESULTS.json","MANIFEST.json","MERKLE_ROOT.txt","PUBLICATION.json","E384F_OMEGA_SEAL.json","E384F_TAMPER_RESULTS.json"}
def canon(o): return json.dumps(o,sort_keys=True,separators=(",",":"),ensure_ascii=False).encode()
def sha(b): return hashlib.sha256(b if isinstance(b,bytes) else b.encode()).hexdigest()
def merkle(paths):
    leaves=sorted(sha(p.read_bytes()) for p in paths)
    if not leaves: return sha(b"")
    while len(leaves)>1:
        if len(leaves)%2: leaves.append(leaves[-1])
        leaves=[sha((leaves[i]+leaves[i+1]).encode()) for i in range(0,len(leaves),2)]
    return leaves[0]
def verify_record(rec,pubs):
    body={k:rec[k] for k in ("domain","seq","kind","mission","key","value","writer","nonce","ts")}
    try: Ed25519PublicKey.from_public_bytes(bytes.fromhex(pubs[rec["writer"]])).verify(bytes.fromhex(rec["sig"]),canon(body))
    except Exception: return False
    return sha((rec["prev"]+sha(canon(body)+rec["sig"].encode())).encode())==rec["hash"]
def chain_ok(records,domain,pubs):
    prev="0"*64
    for rec in sorted([r for r in records if r["domain"]==domain],key=lambda r:r["seq"]):
        if rec["prev"]!=prev or not verify_record(rec,pubs): return False
        prev=rec["hash"]
    return True
def grant_ok(g,pubs):
    try: Ed25519PublicKey.from_public_bytes(bytes.fromhex(pubs[g["grantor"]])).verify(bytes.fromhex(g["sig"]),canon({k:g[k] for k in ("grantor","grantee","kinds","mission","issued","expires","nonce")})); return True
    except Exception: return False
def access(records,grants,reader,pubs):
    out=[]
    for rec in records:
        if rec["domain"]==reader: out.append(rec); continue
        for g in grants:
            if g["revoked"] or not (g["issued"]<=NOW<=g["expires"]) or g["grantor"]!=rec["domain"] or g["grantee"]!=reader: continue
            if grant_ok(g,pubs) and rec["kind"] in g["kinds"] and rec["mission"]==g["mission"]: out.append(rec); break
    return out
def main():
    d=Path(sys.argv[1] if len(sys.argv)>1 else "."); checks=[]
    def ck(n,c): checks.append((n,bool(c)))
    man=json.loads((d/"E384F_MANIFEST.json").read_text()); pre=json.loads((d/"E384F_PREREGISTRATION.json").read_text()); frz=json.loads((d/"E384F_PREREGISTRATION_FREEZE.json").read_text()); rep=json.loads((d/"E384F_RUN_REPORT.json").read_text()); salt=json.loads((d/"E384F_SALT_REVEALED.json").read_text()); acc=json.loads((d/"E384F_ACCEPTANCE_REGISTRY.json").read_text()); dev=json.loads((d/"E384F_DEVIATIONS.json").read_text()); led=rep["ledger"]
    ck("schema",man.get("schema")=="cain42.e384f.manifest.v1" and rep.get("evolution")=="E384-F")
    files=sorted(p for p in d.rglob("*") if p.is_file() and str(p.relative_to(d)) not in EX and "__pycache__" not in p.parts)
    ck("files",set(man["files"])=={str(p.relative_to(d)) for p in files}); ck("hashes",all(sha(p.read_bytes())==man["files"][str(p.relative_to(d))] for p in files)); ck("merkle",man["merkle_root"]==merkle(files)); ck("merkle file",(d/"MERKLE_ROOT.txt").read_text().strip()==man["merkle_root"])
    body=json.loads((d/"E384F_SIGNED_BODY.json").read_text()); pub=Ed25519PublicKey.from_public_bytes(bytes.fromhex(man["pubkey_ed25519"])); pub.verify(bytes.fromhex(man["signature"]),canon(body)); ck("signature",True)
    ck("freeze",sha((d/"E384F_PREREGISTRATION.json").read_bytes())==frz["preregistration_sha256"]==rep["preregistration_sha256"]); ck("salts",all(sha(bytes.fromhex(v))==pre["salt_commitment_sha256"][k] for k,v in salt["salts"].items())); ck("source withheld",not any(q.name in ("run.py","verify.py") for q in d.rglob("*") if q.is_file()))
    records,grants,pubs=led["records"],led["grants"],led["pubs"]; ck("record count",len(records)==16 and rep["design"]["records"]=={"A":10,"B":6}); ck("record signatures",all(verify_record(r,pubs) for r in records)); ck("chain A",chain_ok(records,"A",pubs)); ck("chain B",chain_ok(records,"B",pubs)); ck("grant signatures",all(grant_ok(g,pubs) for g in grants)); ck("nonces",len(led["nonces"])==16)
    ck("intra A",len(access(records,grants,"A",pubs))==10); ck("intra B",len([r for r in access(records,grants,"B",pubs) if r["domain"]=="B"])==6); ck("cross deny",len([r for r in access(records,grants,"B",pubs) if r["domain"]=="A"])==0)
    c=runs=rep["runs"]; ck("reported checks",all(rep["checks"].values())); ck("runs checks",all(all(v["checks"].values()) for v in runs.values())); ck("counts",rep["finding"]["counts"]["records"]==[16,16,16,16] and rep["finding"]["counts"]["before"]==10 and rep["finding"]["counts"]["after_restart"]==10 and rep["finding"]["counts"]["after_revoke"]==0)
    expected={"H1_records_survive_restart":"SUPPORTED","H2_grant_survives_restart":"SUPPORTED","H3_revocation_survives_restart":"SUPPORTED","H4_replay_refused_after_restart":"SUPPORTED","H5_cross_write_refused":"SUPPORTED","H6_grant_failures_and_tamper":"SUPPORTED","H7_no_authority":"SUPPORTED","H8_external_review":"BLOCKED"}
    ck("hypotheses",{k:v["verdict"] for k,v in rep["hypotheses"].items()}==expected); ck("verdict",rep["verdict"]=="DURABLE_FEDERATED_MEMORY_SUPPORTED"); ck("report verdict",f"**Preregistered verdict: {rep['verdict']}.**" in (d/"E384F_FINAL_REPORT.md").read_text()); ck("public summary",rep["verdict"] in (d/"E384F_PUBLIC_SUMMARY.md").read_text()); ck("acceptance",acc["verdict"]==rep["verdict"]); ck("deviations",isinstance(dev.get("deviations"),list) and len(dev["deviations"])==0); ck("resources",rep["resources"]["model_calls"]==0 and rep["resources"]["api_spend_usd"]==0.0); ck("status",rep["status"]==S and man["status"]==S)
    bad=[n for n,ok in checks if not ok]
    for n,ok in checks: print(("PASS " if ok else "FAIL ")+n)
    print(f"{len(checks)-len(bad)}/{len(checks)} checks passed"); return 0 if not bad else 1
if __name__=="__main__": sys.exit(main())
