"""Inspect all range-fetched source COCO files without reading image pixels."""
import json,glob,os,collections,hashlib,itertools
from pathlib import Path
R=Path(__file__).resolve().parents[1];D=R/'datasets/r84-khanom';O=R/'results/r84';records=[];sets={};union=collections.defaultdict(set)
for p in sorted(D.glob('*coco.json')):
 d=json.loads(p.read_text());parts=p.name.lower().split('_');species=parts[0];split=parts[1];names={x['file_name'] for x in d['images']};sets[p.name]=names;union[(species,split)]|=names;ann=collections.Counter(x['image_id'] for x in d['annotations']);records.append({'file':p.name,'sha256':hashlib.sha256(p.read_bytes()).hexdigest(),'species':species,'split':split,'images':len(names),'annotations':len(d['annotations']),'multi_annotation_images':sum(v>1 for v in ann.values()),'max_annotations_per_image':max(ann.values(),default=0),'image_size_counts':dict(collections.Counter(str((x['width'],x['height'])) for x in d['images'])),'category_names':[c['name'] for c in d['categories']]})
inter=[]
for sp in ('gomphonema','pinnularia'):
 for a,b in itertools.combinations(('train','val','test'),2):
  shared=sorted(union[sp,a]&union[sp,b]);inter.append({'species':sp,'first':a,'second':b,'shared_filenames':shared,'count':len(shared)})
out={'note':'Filename equality is neither proof nor disproof of pixel or specimen independence. Same-split COCO files may be nested and must not be added together. Image pixels have not been read. Category names are empty in source COCO; species attribution is from archive folder/record, not an independent taxonomic review.','records':records,'cross_split_filename_overlap':inter,'union_counts':{f'{a}:{b}':len(v) for (a,b),v in union.items()}};(O/'annotation-audit.json').write_text(json.dumps(out,indent=2)+'\n');print('union counts',out['union_counts']);print('cross-split shared',[(v['species'],v['first'],v['second'],v['count']) for v in inter]);print('multi per file',[(v['file'],v['multi_annotation_images'],v['max_annotations_per_image']) for v in records if v['split']=='test'])
