"""Independently verify L63 graph masks and browser preview pixels."""
import hashlib,json
from pathlib import Path
import numpy as np
from PIL import Image
from diatom_pilot.proposal_graph import unpack_candidates,mask_digest
R=Path(__file__).resolve().parents[1];O=R/'results/l63'
def sha(p):return hashlib.sha256(p.read_bytes()).hexdigest()
def main():
 manifest=json.loads((O/'results.json').read_text());protocol=json.loads((O/'protocol.json').read_text());assert manifest['protocol_sha256']==sha(O/'protocol.json')
 for x in protocol['inputs']:assert sha(R/x['path'])==x['sha256']
 checked=0;edges=0
 for idx,record in enumerate(manifest['fields'],1):
  graphpath=O/record['graph'];archive=O/record['archive'];assert sha(graphpath)==record['graph_sha256'] and sha(archive)==record['archive_sha256'];g=json.loads(graphpath.read_text());masks=unpack_candidates(np.load(archive,allow_pickle=False));assert len(masks)==record['candidates']==len(g['candidates']);assert len(g['relations'])==record['relations'];ids=set()
  for node in g['candidates']:
   ident=node['id'];assert ident not in ids;ids.add(ident);m=masks[ident];assert mask_digest(m)==node['mask_sha256'] and int(m.sum())==node['area'];rgba=np.asarray(Image.open(O/node['metadata']['preview']).convert('RGBA'));assert np.array_equal(rgba[:,:,3],m.astype('uint8')*120);checked+=1
  for e in g['relations']:
   a,b=masks[e['candidate']],masks[e['kept']];inter=int((a&b).sum());union=int((a|b).sum());assert union and abs(e['mask_iou']-inter/union)<1e-12 and e['mask_iou']>=.8-1e-12;edges+=1
 print(f'Verified {checked} archived masks, preview alpha pixels and digests; {edges} suppression-link IoUs; all input and output hashes.')
if __name__=='__main__':main()
