"""Verify stored simulated planes, original masks, and suppression aliases."""
import hashlib,json
from pathlib import Path
import numpy as np
ROOT=Path(__file__).resolve().parents[1];OUT=ROOT/'results/l46'
def sha(p):return hashlib.sha256(p.read_bytes()).hexdigest()
def main():
 records=json.loads((OUT/'results.json').read_text())['records'];info=json.loads((OUT/'backgrounds.json').read_text());manifest=json.loads((OUT/'source-objects/manifest.json').read_text());raw_count=0
 if sha(OUT/'backgrounds.npz')!=info['npz_sha256']:raise ValueError('Background crop archive changed')
 for row in manifest['records']:
  for kind in ('image','mask'):
   if sha(OUT/'source-objects'/f"{row['id']}-{kind}.png")!=row[kind+'_sha256']:raise ValueError('Source object changed')
 for r in records:
  with np.load(OUT/r['archive'],allow_pickle=False) as f:
   n,h,w=map(int,f['candidate_shape']);ids=f['candidate_ids'].tolist();zs=f['candidate_z'].tolist()
   if (h,w)!=(512,512) or f['planes'].shape!=(5,512,512) or f['full_masks'].shape!=(2,512,512) or len(ids)!=n or len(set(ids))!=n or len(zs)!=n or len(f['candidate_bits'])*8<n*h*w or any(z not in range(5) for z in zs):raise ValueError('Malformed scene archive')
   if n!=sum(x['candidate_count'] for x in r['automatic_per_plane']):raise ValueError('Raw candidate count differs')
   shared=int(np.count_nonzero(f['full_masks'][0]&f['full_masks'][1]))
   if shared!=r['overlap_pixels'] or (r['kind']=='crossing' and shared==0) or (r['kind']=='separated' and shared!=0):raise ValueError('Scene conditions wrong')
   if any(x['candidate'] not in ids or x['kept'] not in ids for x in r['suppression_aliases']):raise ValueError('Broken suppression alias')
   raw_count+=n
 print(f'Verified {len(records)} scenes, {raw_count} preserved automatic masks, background and source-image hashes.')
if __name__=='__main__':main()
