#!/usr/bin/env python3
"""Verify the E409-V independent E408-R verifier-run record (stdlib + cryptography)."""
import base64, hashlib, json, sys
from pathlib import Path
from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey
H=Path(__file__).resolve().parent
sha=lambda b: hashlib.sha256(b if isinstance(b,bytes) else b.encode()).hexdigest()
canon=lambda o: json.dumps(o,sort_keys=True,separators=(',',':'),ensure_ascii=False).encode()
ev=json.loads((H/'E409V_VERIFICATION.json').read_text()); out=(H/'VERIFY_OUTPUT.txt').read_bytes()
body={k:v for k,v in ev.items() if k not in ('signature_b64','public_key_b64','key_fingerprint')}
ok=[]
def c(n,v):
    ok.append(bool(v)); print(('PASS' if v else 'FAIL'),n)
try:
    Ed25519PublicKey.from_public_bytes(base64.b64decode(ev['public_key_b64'])).verify(bytes.fromhex(ev['signature_b64']),canon(body)); c('signature',True)
except Exception as e: c('signature',False)
c('output hash',sha(out)==ev['verifier_output_sha256'])
c('21/21',b'21/21 checks passed' in out and ev['checks_passed']==21)
c('28,800 AST re-executions',b'ast_evals=28800' in out and ev['sealed_ast_reexecutions']==28800)
c('status',ev['status']=='AGI: NOT ESTABLISHED · RSI: EXPERIMENTAL')
print(f'{sum(ok)}/{len(ok)} checks passed'); print(ev['status'])
sys.exit(0 if all(ok) else 1)
