#!/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)
    if not leaves: return sha(b'')
    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]
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/'E267_MANIFEST.json').read_text()); ck('status',man.get('status')==S); ck('label',man.get('label')=='CANONICAL_INDEX_V3')
    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/'E267_CANONICAL_EVIDENCE_INDEX.json').read_text()); T=idx['totals']; rows=idx['evolutions']
    ck('26 evolutions',len(rows)==26 and T['evolutions']==26); ck('seals',T['seals']==24 and T['allowed']==24)
    ck('hypothesis totals',sum(r['hypotheses_supported'] for r in rows)==T['supported_hypotheses'] and sum(r['hypotheses_total'] for r in rows)==T['hypotheses'])
    ck('no external reviewer',T['external_review_obtained']==0 and json.loads((B/'E267_REVIEWER_REGISTRY.json').read_text()).get('status')=='NOT_OBTAINED')
    ck('index adds no claim',idx.get('scope','').startswith('published') and idx.get('external_review',{}).get('status')=='NOT_OBTAINED')
    ck('positive chain recorded','24/24' in idx['highlight']['positive_chain'] and '5/24' in idx['highlight']['ceiling'] and '47/48' in idx['highlight']['exact_structure'])
    passed=sum(1 for x in c if x['ok']); print(json.dumps({'schema':'cain42.e267.verify.v1','checks':len(c),'passed':passed,'failed':[x for x in c if not x['ok']],'totals':T},ensure_ascii=False)); return 0 if passed==len(c) else 1
if __name__=='__main__': sys.exit(main())
