"""Select nonoverlapping Menne test tiles from annotation metadata only."""
import collections,hashlib,json,random,re
from pathlib import Path
ROOT=Path(__file__).resolve().parents[1];OUT=ROOT/'results/r44';COCO=Path('/tmp/diatom-r44-menne/test.all.coco.json');INDEX=OUT/'archive-index.json';SEED=20261206

def sha(p):return hashlib.sha256(p.read_bytes()).hexdigest()
def main():
 dest=OUT/'selection.json'
 if dest.exists():raise FileExistsError('Field selection is already frozen')
 coco=json.loads(COCO.read_text());index=json.loads(INDEX.read_text());byname={x['name']:x for x in index['entries']};byimage=collections.Counter(a['image_id'] for a in coco['annotations']);pools=collections.defaultdict(lambda:collections.defaultdict(list))
 for img in coco['images']:
  name=Path(img['file_name']).name;slide=re.search(r'(M[1-6]_Slide1)',name);xy=re.search(r'\.x_(\d+)\.y_(\d+)\.tif$',name)
  if not slide or not xy or (img['width'],img['height'])!=(512,512):continue
  n=byimage[img['id']];category='multi' if n>=2 else 'empty' if n==0 else None
  if category is None:continue
  member='Python scripts and data/data/test/image/'+name
  if member not in byname:raise ValueError('COCO tile missing in archive')
  pools[slide.group(1)][category].append({'id':img['id'],'slide':slide.group(1),'xy':[int(xy.group(1)),int(xy.group(2))],'annotation_count':n,'category':category,'member':member,'archive_crc32':byname[member]['crc32']})
 rng=random.Random(SEED);chosen=[]
 for number in range(1,7):
  slide=f'M{number}_Slide1';existing=[]
  for category,count in [('multi',2),('empty',1)]:
   options=sorted(pools[slide][category],key=lambda x:x['member']);rng.shuffle(options)
   for row in options:
    x,y=row['xy']
    if any(abs(x-a)<512 and abs(y-b)<512 for a,b in existing):continue
    row.update(split='development' if number in (1,3,5) else 'held_out_public',local_file=f'{slide}-{category}-{count}-{row["id"]}.tif');chosen.append(row);existing.append((x,y));count-=1
    if count==0:break
   if count:raise ValueError(f'Insufficient nonoverlapping {category} fields for {slide}')
 result={'format':'r44-menne-selection-v1','seed':SEED,'annotation_sha256':sha(COCO),'archive_index_sha256':sha(INDEX),'selection':chosen,
   'description':'Per slide, select two tiles with >=2 annotated objects and one annotation-empty tile; avoid overlapping selected rectangles within each slide.',
   'split_warning':'Six slide identifiers correspond to source locations per paper; named dataset splits are areas within each slide. Independence across samples and detector training-source overlap are not verified.',
   'eligibility_warning':'Dataset excludes small fragments and dense aggregates; annotation-empty does not mean no diatoms or no valid partial targets.'}
 dest.write_text(json.dumps(result,indent=2)+'\n');print('Frozen',len(chosen),'fields before downloading image pixels.')
if __name__=='__main__':main()
