#!/usr/bin/env python3
import hashlib,json,sys
from pathlib import Path
S='AGI: NOT ESTABLISHED · RSI: EXPERIMENTAL'
def canon(o): return json.dumps(o,sort_keys=True,separators=(',',':'),ensure_ascii=False).encode()
def sha(b): return hashlib.sha256(b).hexdigest()
def merkle(paths):
    leaves=sorted(sha(p.read_bytes()) for p in paths)
    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] if leaves else sha(b'')
def main():
    B=Path(sys.argv[1] if len(sys.argv)>1 else '.'); c=[]
    def ck(n,ok,d=''): c.append({'check':n,'ok':bool(ok),'detail':str(d)[:250]})
    man=json.loads((B/'E295_MANIFEST.json').read_text()); ck('status',man.get('status')==S); ck('label',man.get('label')=='CANONICAL_INDEX_V4')
    body={k:v for k,v in man.items() if k!='signature'}
    try:
        from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey
        Ed25519PublicKey.from_public_bytes(bytes.fromhex(man['pubkey_ed25519'])).verify(bytes.fromhex(man['signature']),canon(body)); ck('signature',True)
    except Exception as ex: ck('signature',False,ex)
    files=man.get('files',{}); ck('files',all((B/k).exists() for k in files)); ck('hashes',not [k for k,h in files.items() if (B/k).exists() and sha((B/k).read_bytes())!=h]); ck('merkle',merkle(sorted(B/k for k in files if (B/k).exists()))==man.get('merkle_root'))
    idx=json.loads((B/'E295_CANONICAL_EVIDENCE_INDEX.json').read_text()); T=idx['totals']; rows=idx['evolutions']
    ck('51 rows',len(rows)==51 and T['evolutions']==51); ck('51 seals',T['seals']==51 and T['allowed']==51)
    ck('totals recompute',sum(r['hypotheses_supported'] for r in rows)==T['supported_hypotheses'] and sum(r['hypotheses_total'] for r in rows)==T['hypotheses'])
    ck('0 reviewers',T['external_review_obtained']==0)
    ck('E290/E292 present',any(r['evolution']=='E290' for r in rows) and any(r['evolution']=='E292' for r in rows))
    ck('latest E294 present',any(r['evolution']=='E294' for r in rows))
    ck('reviewer empty',json.loads((B/'E295_REVIEWER_REGISTRY.json').read_text())['status']=='NOT_OBTAINED')
    passed=sum(1 for x in c if x['ok'])
    print(json.dumps({'schema':'cain42.e295.verify.v1','checks':len(c),'passed':passed,'failed':[x for x in c if not x['ok']],'totals':T,'external_review':'NOT_OBTAINED'},ensure_ascii=False))
    return 0 if passed==len(c) else 1
if __name__=='__main__': sys.exit(main())
