#!/usr/bin/env python3
"""SEL-1 standalone verifier (stdlib + cryptography; imports no CAIN code).

Checks: the record manifest signature, every file hash and the Merkle root; each cited
study's copied manifest signature and Merkle root against the record; the cited verifier
SHA-256; the recorded clean-copy replication result; every row's hash chain; the gaps and
the law recomputed from the recorded numbers; the falsifier's presence; the no-model record.
It does not re-execute the four studies.
"""
from __future__ import annotations
import hashlib, json, sys
from pathlib import Path
from cryptography.exceptions import InvalidSignature
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey

S = "AGI: NOT ESTABLISHED · RSI: EXPERIMENTAL"
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())

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

def merkle(paths):
    lv=sorted(sha(p.read_bytes()) for p in paths)
    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] if lv else sha(b"")

def main():
    b=Path(sys.argv[1] if len(sys.argv)>1 else ".")
    ch=C(); man=load(b/"SEL1_MANIFEST.json"); sig=man.pop("signature","")
    pub=Ed25519PublicKey.from_public_bytes(bytes.fromhex(man["pubkey_ed25519"]))
    try:
        pub.verify(bytes.fromhex(sig),(b/"SEL1_SIGNED_BODY.json").read_bytes())
        ch.add("manifest_signature",True,man["pubkey_fingerprint"]+" (self-generated)")
    except (InvalidSignature,ValueError): ch.add("manifest_signature",False,"invalid")
    ex={"SEL1_MANIFEST.json","SEL1_SIGNED_BODY.json","SEL1_VERIFICATION_RESULTS.json","MANIFEST.json",
        "MERKLE_ROOT.txt","PUBLICATION.json","SEL1_OMEGA_SEAL.json","SEL1_TAMPER_RESULTS.json"}
    files=sorted(x for x in b.rglob("*") if x.is_file() and str(x.relative_to(b)) not in ex and "__pycache__" not in x.parts)
    dec=man.get("files") or {}
    ch.add("file_hashes",all(dec.get(str(x.relative_to(b)))==sha(x.read_bytes()) for x in files) and len(dec)==len(files),f"{len(files)} files")
    ch.add("merkle_root",merkle(files)==man.get("merkle_root"),str(man.get("merkle_root"))[:16])

    rec=load(b/"SEL1_RECORD.json")
    ch.add("record_label",rec.get("label")=="SEL-1",rec.get("label",""))
    # cited studies: manifest signature + merkle + verifier hash
    ok_cited=True; details=[]
    for short in rec["studies"]:
        d=b/"cited"/short
        cm=load(d/"MANIFEST.json"); s=cm.pop("signature","")
        try:
            Ed25519PublicKey.from_public_bytes(bytes.fromhex(cm["pubkey_ed25519"])).verify(
                bytes.fromhex(s), canon(cm))
            sigok=True
        except (InvalidSignature,ValueError): sigok=False
        vr=[r["row"] for r in rec["rows"] if r["row"]["study"]==short][0]["replication"]
        mok = (d/"MERKLE_ROOT.txt").read_text().strip()==vr["merkle_root"]==cm.get("merkle_root")
        vok = sha((d/Path(vr.get("verifier_name", "x")).name).read_bytes()) if False else True
        ok_cited = ok_cited and sigok and mok and vr["returncode"]==0
        details.append(f"{short}: sig={sigok} merkle={mok} rc={vr['returncode']}")
    ch.add("cited_manifests",ok_cited,"; ".join(details))

    # gaps + law recomputed
    ok=True; max_p=max_r=-9
    for ch_row in rec["rows"]:
        r=ch_row["row"]
        gp=round(r["best_primary"]-r["tested_primary"],6); gr=round(r["best_replication"]-r["tested_replication"],6)
        ok = ok and abs(gp-r["gap_primary"])<1e-9 and abs(gr-r["gap_replication"])<1e-9
        max_p=max(max_p, r["tested_primary"]-r["best_primary"]); max_r=max(max_r, r["tested_replication"]-r["best_replication"])
    ch.add("gaps_recomputed",ok,f"{len(rec['rows'])} rows")
    law=rec["law"]
    ch.add("law_recomputed", law["violations"]==0 and max_p<0.10 and max_r<0.10
           and abs(law["max_improvement_primary"]-round(max_p,6))<1e-9
           and abs(law["max_improvement_replication"]-round(max_r,6))<1e-9,
           f"max improvement {max_p:+.3f} / {max_r:+.3f}; violations {law['violations']}")
    ch.add("falsifier_present", isinstance(law.get("falsifier"),str) and "+0.10" in law["falsifier"], law["falsifier"][:80])
    hl=man.get("headline") or {}
    ch.add("law_statement_bound", hl.get("law_statement_sha256")==sha(law["statement"].encode()),
           "the law statement hash is bound in the manifest headline")
    ch.add("headline_matches_record",
           hl.get("violations")==law["violations"]
           and hl.get("max_improvement_primary")==law["max_improvement_primary"]
           and hl.get("max_improvement_replication")==law["max_improvement_replication"]
           and hl.get("bundles_replicated")==rec["replication_summary"]["bundles"]
           and hl.get("verifiers_passed")==rec["replication_summary"]["verifiers_passed"],
           "the manifest headline is the record's")

    prev="0"*64; ok=True
    for row in rec["rows"]:
        body=row["row"]
        h=sha(prev.encode()+canon(body))
        if h!=row["hash"] or row["prev"]!=prev: ok=False; break
        prev=h
    ch.add("row_chain",ok,f"{len(rec['rows'])} rows")

    # verifier hashes recorded
    ok=True
    for ch_row in rec["rows"]:
        r=ch_row["row"]; short=r["study"]; d=b/"cited"/short
        ver=f"verify_{short.lower().replace('-','')}_offline.py"
        # find any verify*.py in the cited dir and compare to the recorded sha
        cands=list(d.glob("verify*.py"))
        ok = ok and bool(cands) and sha(cands[0].read_bytes())==r["replication"]["verifier_sha256"]
    ch.add("cited_verifier_hashes",ok,"each recorded verifier SHA-256 matches the cited copy")
    ch.add("no_models_no_spend", rec.get("model_calls")==0 and rec.get("api_spend_usd")==0.0,"0 model calls, $0")
    return ch.finish()

if __name__=="__main__":
    raise SystemExit(main())
