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

Checks the manifest signature, file hashes and Merkle root; the recorded summary recomputed
from the rows; every row's hash chain; that the five records and four hosts are present;
the no-model record. Live HTTP is not re-fetched: the record is the artifact.
"""
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"
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/"SURFSEL_MANIFEST.json"); sig=man.pop("signature","")
    try:
        Ed25519PublicKey.from_public_bytes(bytes.fromhex(man["pubkey_ed25519"])).verify(
            bytes.fromhex(sig),(b/"SURFSEL_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={"SURFSEL_MANIFEST.json","SURFSEL_SIGNED_BODY.json","SURFSEL_VERIFICATION_RESULTS.json","MANIFEST.json",
        "MERKLE_ROOT.txt","PUBLICATION.json","SURFSEL_OMEGA_SEAL.json","SURFSEL_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/"SURF_RECORD.json")
    ch.add("label",rec.get("label")=="SURF-SEL",rec.get("label",""))
    rows=[r["row"] for r in rec["rows"]]
    passed=sum(1 for r in rows if r["ok"]); total=len(rows); failed=total-passed
    s=rec["summary"]
    ch.add("summary_recomputed", s["checks"]==total and s["passed"]==passed and s["failed"]==failed
           and s["converged"]==(failed==0), f"{passed}/{total}, converged={failed==0}")
    ch.add("coverage", len({r["record"] for r in rows})==5 and len({r["site"] for r in rows})==4,
           f'{len({r["record"] for r in rows})} records, {len({r["site"] for r in rows})} sites')
    ch.add("checks_present", {r["check"] for r in rows} >= {"page","snapshot","tamper","bundle_manifest",
           "snapshot_convergence","homepage_block","claim_present","changelog_present"},
           "all eight check classes present")
    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")
    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())
