#!/usr/bin/env python3
"""E398-M standalone verifier: rebuilds every session and the derived alignment table."""
from __future__ import annotations
import hashlib, json, sys
from pathlib import Path

S="AGI: NOT ESTABLISHED · RSI: EXPERIMENTAL"
EX={"E398-M_MANIFEST.json","E398-M_SIGNED_BODY.json","E398-M_VERIFICATION_RESULTS.json","MANIFEST.json","MERKLE_ROOT.txt","PUBLICATION.json","E398-M_OMEGA_SEAL.json","E398-M_TAMPER_RESULTS.json"}
USES=30; REVOKE_AT=10; SESSIONS=40
POLICIES={"CHECK_EVERY_USE":1,"CACHE_ONCE":USES+1,"CACHE_TTL_5":5,"CACHE_TTL_10":10}
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 session(policy,ttl):
    revoked=known=False; last=-10**9; acc=[]; chk=[]
    for use in range(1,USES+1):
        if use==REVOKE_AT: revoked=True
        if use-last>=ttl:
            last=use; chk.append(use); known=revoked
        acc.append(not known)
    post=[a for u,a in zip(range(1,USES+1),acc) if u>REVOKE_AT]
    return {"policy":policy,"ttl":ttl,"post_revocation_accepted":sum(1 for a in post if a),
            "post_revocation_uses":len(post),
            "pre_revocation_accepted":sum(1 for u,a in zip(range(1,USES+1),acc) if u<REVOKE_AT and a),
            "pre_revocation_uses":REVOKE_AT-1}
def exposure(ttl,r):
    if ttl>=USES+1: return USES-r
    nxt=((r+ttl-1)//ttl)*ttl
    return max(0,min(nxt,USES)-r)
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/"E398-M_MANIFEST.json").read_text()); pre=json.loads((d/"E398-M_PREREGISTRATION.json").read_text())
    frz=json.loads((d/"E398-M_PREREGISTRATION_FREEZE.json").read_text()); rep=json.loads((d/"E398-M_RUN_REPORT.json").read_text())
    salt=json.loads((d/"E398-M_SALT_REVEALED.json").read_text()); acc=json.loads((d/"E398-M_ACCEPTANCE_REGISTRY.json").read_text())
    dev=json.loads((d/"E398-M_DEVIATIONS.json").read_text()); der=json.loads((d/"E398-M_DERIVED_ALIGNMENT.json").read_text())
    ck("schema",man.get("schema")=="cain42.e398m.manifest.v1" and rep.get("evolution")=="E398-M")
    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))
    def pm(paths):
        lv=sorted(sha(p.read_bytes()) for p in paths)
        if not lv: return sha(b"")
        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)]
        return lv[0]
    ck("merkle",man["merkle_root"]==pm(files)); ck("merkle file",(d/"MERKLE_ROOT.txt").read_text().strip()==man["merkle_root"])
    from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey
    Ed25519PublicKey.from_public_bytes(bytes.fromhex(man["pubkey_ed25519"])).verify(bytes.fromhex(man["signature"]),canon(json.loads((d/"E398-M_SIGNED_BODY.json").read_text())))
    ck("signature",True)
    ck("freeze",sha((d/"E398-M_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()))
    rows={(r["policy"],r["session"]):r for r in rep["rows"]}
    ck("rows",len(rows)==len(POLICIES)*SESSIONS)
    redo={p:[] for p in POLICIES}
    for p,ttl in POLICIES.items():
        for s in range(SESSIONS):
            x=session(p,ttl); redo[p].append(x)
            r=rows[(p,s)]
            if any(r[k]!=x[k] for k in ("post_revocation_accepted","pre_revocation_accepted")):
                checks.append((f"row {p}/{s}",False))
    a={p:{"post_total":sum(x["post_revocation_accepted"] for x in redo[p]),
          "post_max":max(x["post_revocation_accepted"] for x in redo[p]),
          "post_mean":round(sum(x["post_revocation_accepted"] for x in redo[p])/SESSIONS,3)} for p in POLICIES}
    H={
      "H1_check_every_use_is_safe":{"verdict":"SUPPORTED" if a["CHECK_EVERY_USE"]["post_total"]==0 else "NOT_SUPPORTED","detail":"checking revocation at every use accepts zero uses after revocation"},
      "H2_cache_once_exposes_everything":{"verdict":"SUPPORTED" if a["CACHE_ONCE"]["post_total"]==SESSIONS*(USES-REVOKE_AT) else "NOT_SUPPORTED","detail":"verifying once accepts every post-revocation use"},
      "H3_ttl_is_the_exposure_bound":{"verdict":"SUPPORTED" if (a["CACHE_TTL_5"]["post_max"]<=4 and a["CACHE_TTL_10"]["post_max"]<=9) else "NOT_SUPPORTED","detail":"a TTL of T exposes at most T-1 post-revocation uses"},
      "H4_no_accept_after_a_post_revocation_check":{"verdict":"SUPPORTED" if all(x["post_revocation_accepted"]<=max(0,x["ttl"]-1) for p in POLICIES for x in redo[p]) else "NOT_SUPPORTED","detail":"every accepted post-revocation use lies inside the client's cache window"},
      "H5_no_false_denials":{"verdict":"SUPPORTED" if all(x["pre_revocation_accepted"]==x["pre_revocation_uses"] for p in POLICIES for x in redo[p]) else "NOT_SUPPORTED","detail":"no pre-revocation use is denied by any policy"},
      "H6_external_review":{"verdict":"BLOCKED","detail":"external review NOT OBTAINED"}}
    verdict="REVOCATION_FRESHNESS_LAW_SUPPORTED" if all(H[k]["verdict"]=="SUPPORTED" for k in H if k!="H6_external_review") else "NOT_SUPPORTED"
    ck("verdict",verdict==rep["verdict"] and all(H[k]["verdict"]==rep["hypotheses"][k]["verdict"] for k in H))
    ck("headline",rep["finding"]["headline"]["cache_once_post_accepted"]==a["CACHE_ONCE"]["post_total"]
       and rep["finding"]["headline"]["check_every_use_post_accepted"]==0)
    # derived alignment table (descriptive, recomputed)
    der_ok=True
    for row in der["table"]:
        t=row["ttl"]
        for r in range(1,31):
            if row["post_revocation_accepted_by_offset"][str(r)]!=exposure(t,r): der_ok=False
    ck("derived alignment",der_ok and der.get("label")=="DERIVED_EXPLORATORY_NOT_PREREGISTERED")
    ch=[json.loads(l) for l in (d/"checkpoints/sessions_chain.jsonl").read_text().splitlines()]
    hh=sha(("0"*64+sha(canon(rep["probe"]))).encode())
    ck("chain",len(ch)==1 and ch[0]["prev"]=="0"*64 and ch[0]["hash"]==hh==rep["checkpoint"]["head"])
    cp=json.loads((d/"checkpoints/sessions_chain.json").read_text())
    ck("chain file",cp["count"]==1 and cp["head"]==hh)
    ck("finding",rep["finding"]["headline"]["sessions"]==160 and rep["finding"]["law"].startswith("a grant's cache lifetime"))
    ck("report verdict",f"**Preregistered verdict: {rep['verdict']}.**" in (d/"E398-M_FINAL_REPORT.md").read_text())
    ck("public summary",rep["verdict"] in (d/"E398-M_PUBLIC_SUMMARY.md").read_text())
    ck("acceptance",acc["verdict"]==rep["verdict"])
    ck("deviations",any(x.get("id")=="D1" for x in dev.get("deviations",[])))
    ck("resources",rep["resources"]["model_calls"]==0)
    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())
