#!/usr/bin/env python3
from __future__ import annotations
import hashlib,json,sys
from pathlib import Path
STATUS='AGI: NOT ESTABLISHED · RSI: EXPERIMENTAL'
def canon(o): return json.dumps(o,sort_keys=True,separators=(',',':')).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 '.'); checks=[]
    def ck(n,ok,d=''): checks.append({'check':n,'ok':bool(ok),'detail':str(d)[:300]})
    man=json.loads((B/'E204_MANIFEST.json').read_text()); ck('status',man.get('status')==STATUS); ck('label',man.get('label')=='SOURCE_SECRET_EVIDENCE_PUBLIC')
    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 exist',all((B/k).exists() for k in files)); bad=[k for k,h in files.items() if (B/k).exists() and sha((B/k).read_bytes())!=h]; ck('hashes',not bad,bad[:3]); ck('merkle',merkle(sorted(B/k for k in files if (B/k).exists()))==man.get('merkle_root'))
    present={str(x.relative_to(B)) for x in B.rglob('*') if x.is_file() and '__pycache__' not in x.parts and x.suffix!='.pyc'}
    unlisted=sorted(present-set(files)-{'E204_MANIFEST.json','E204_SIGNED_BODY.json','E204_VERIFICATION_RESULTS.json','PUBLICATION.json','E204_OMEGA_SEAL.json'}); ck('no unlisted',not unlisted,unlisted[:5])
    ip=json.loads((B/'IP_MANIFEST.json').read_text())
    ck('source public false',ip.get('source_public') is False); ck('9 bundles',len(ip.get('bundles',[]))==9)
    ck('no engine source public',all(b.get('engine_source_public') is False for b in ip['bundles']))
    ck('zero IP exposure',ip.get('guard',{}).get('zero') is True and ip['guard'].get('flagged_in_our_bundles')==[],ip.get('guard'))
    ck('all seals ALLOWED',all(b.get('seal_verdict')=='ALLOWED' for b in ip['bundles']))
    ck('no AGI',man.get('status')==STATUS)
    pub=B/'PUBLICATION.json'
    if pub.exists():
        pj=json.loads(pub.read_text()); ck('publication merkle',pj.get('merkle_root')==man.get('merkle_root')); ck('four surfaces',len(pj.get('surfaces',{}))==4)
    else: ck('pre-publication',True)
    ok=all(x['ok'] for x in checks); print(json.dumps({'checks':len(checks),'passed':sum(x['ok'] for x in checks),'ok':ok,'verification':'E204 source-secret evidence fabric'}))
    for x in checks:
        if not x['ok']: print('FAIL',x['check'],x['detail'])
    return 0 if ok else 1
if __name__=='__main__': sys.exit(main())
