"""Inventory local synthetic source candidates; do not assign scientific train/test splits."""
import collections,hashlib,json,zipfile
from pathlib import Path
R=Path(__file__).resolve().parents[1];D=R/'datasets/r84-khanom';O=R/'results/r112/design'
def sha(path):
 h=hashlib.sha256()
 with open(path,'rb') as f:
  for b in iter(lambda:f.read(1024*1024),b''):h.update(b)
 return h.hexdigest()
sets=[('Gomphonema','train','Gomphonema_train_160_coco.json'),('Gomphonema','val','Gomphonema_val_53_coco.json'),('Gomphonema','test','Gomphonema_test_53_coco.json'),('Pinnularia','train','Pinnularia_train_100_coco.json'),('Pinnularia','val','Pinnularia_val_33_coco.json'),('Pinnularia','test','pinnularia_test_33_coco.json')]
archive=D/'source.zip';rows=[];missing=[];co=[]
with zipfile.ZipFile(archive) as z:
 names=set(z.namelist())
 for genus,split,fn in sets:
  path=D/fn;data=json.loads(path.read_text());counts=collections.Counter(a['image_id'] for a in data['annotations']);counts_poly=collections.Counter(a['image_id'] for a in data['annotations'] if isinstance(a.get('segmentation'),list) and a['segmentation']);co.append({'path':str(path.relative_to(R)),'sha256':sha(path),'images':len(data['images']),'annotations':len(data['annotations'])})
  for im in data['images']:
   member=f'Model Images/{genus}_test_train_val/{split}/{im["file_name"]}';ref={'genus':genus,'source_split':split,'filename':im['file_name'],'image_id':im['id'],'annotation_file':str(path.relative_to(R)),'annotation_count':counts[im['id']],'polygon_annotation_count':counts_poly[im['id']],'width':im['width'],'height':im['height'],'archive_member':member}
   if member not in names:missing.append(member);continue
   h=hashlib.sha256()
   with z.open(member) as stream:
    for b in iter(lambda:stream.read(1024*1024),b''):h.update(b)
   info=z.getinfo(member);ref.update({'image_sha256':h.hexdigest(),'bytes':info.file_size,'zip_crc32':f'{info.CRC:08x}'});rows.append(ref)
byhash=collections.defaultdict(list);byname=collections.defaultdict(list)
for x in rows:
 byhash[x['image_sha256']].append(x);byname[x['filename'].casefold()].append(x)
def summarize(groups):
 return [{'key':key,'members':[{'genus':x['genus'],'split':x['source_split'],'filename':x['filename'],'sha256':x['image_sha256']} for x in group]} for key,group in sorted(groups.items()) if len({(x['genus'],x['source_split']) for x in group})>1]
crosshash=summarize(byhash);crossname=summarize(byname);summary={'format':'r112-inventory-v1','source_archive':'datasets/r84-khanom/source.zip','source_archive_sha256':sha(archive),'annotations':co,'resolved_images':len(rows),'resolved_polygon_annotations':sum(x['polygon_annotation_count'] for x in rows),'unresolved_members':missing,'distinct_image_hashes':len(byhash),'cross_split_exact_hash_groups':crosshash,'cross_split_filename_groups':crossname,'limitations':['Metadata-only inventory and byte identity audit, not anatomical annotation validation.','Exact byte equality detects copies; it cannot detect resized, recompressed or visually similar specimens.','Archive split names and filename grouping do not prove biological sample independence.','Taxon names reflect source folder labels, not verified Academy taxonomy.','Unannotated source areas may contain real organisms.'],'source_licenses':'Khanom archive reported CC BY 4.0; verify provenance and downstream model terms before redistribution or deployment.','records':rows}
O.mkdir(parents=True,exist_ok=True);(O/'source-inventory.json').write_text(json.dumps(summary,indent=2)+'\n');print(json.dumps({'resolved_images':len(rows),'polygon_annotations':summary['resolved_polygon_annotations'],'distinct_hashes':len(byhash),'missing':len(missing),'cross_split_exact_hash_groups':len(crosshash),'cross_split_filename_groups':len(crossname),'annotation_sources':co},indent=2))
