"""Prepare mixed-source training images after frozen cross-source screening."""
import json,hashlib,shutil
from pathlib import Path
import numpy as np
from PIL import Image
R=Path(__file__).resolve().parents[1];O=R/'results/r95/mixed';D=O/'training-data';M=R/'datasets/l78-menne'
def sha(p):
 h=hashlib.sha256()
 with open(p,'rb') as f:
  for b in iter(lambda:f.read(1048576),b''):h.update(b)
 return h.hexdigest()
p=json.loads((O/'protocol.json').read_text())
for f,h in p['inputs'].items():assert sha(R/f)==h
audit=json.loads((O/'menne-source-audit.json').read_text());assert audit['training_fields']==12 and audit['training_polygons']==29 and audit['eval_fields']==11;skip=set(audit['quarantined_training_fields']);(D/'images/train').mkdir(parents=True,exist_ok=True);(D/'labels/train').mkdir(parents=True,exist_ok=True);records=[]
for x in json.loads((R/'results/l82/training-manifest.json').read_text())['records']:
 src=R/x['prepared_image'];label=R/x['prepared_label'];assert sha(src)==x['prepared_image_sha256'] and sha(label)==x['prepared_label_sha256'];im=D/'images/train'/('k'+f"{x['index']:02d}"+'.png');lab=D/'labels/train'/('k'+f"{x['index']:02d}"+'.txt');shutil.copyfile(src,im);shutil.copyfile(label,lab);records.append({'group':'khanom','id':x['index'],'source_image':x['source_image'],'source_sha256':x['source_sha256'],'source_label':x['prepared_label'],'source_label_sha256':x['prepared_label_sha256'],'annotation_ids':x['annotation_ids'],'image':str(im.relative_to(R)),'image_sha256':sha(im),'label':str(lab.relative_to(R)),'label_sha256':sha(lab)})
selection=[x for x in json.loads((R/'results/r44/selection.json').read_text())['selection'] if x['annotation_count']>0 and x['id'] not in skip];download={x['id']:x for x in json.loads((R/'results/r44/download-report.json').read_text())['images']};co=json.loads((M/'test.all.coco.json').read_text())
for i,x in enumerate(selection):
 src=M/'images'/f"{x['id']}.tif";assert sha(src)==download[x['id']]['sha256'];im=Image.open(src).convert('RGB');assert im.size==(512,512);dst=D/'images/train'/f"m{x['id']}.png";im.save(dst);anns=[a for a in co['annotations'] if a['image_id']==x['id']];assert len(anns)==x['annotation_count'];labels=[]
 for a in anns:
  assert len(a['segmentation'])==1;points=np.asarray(a['segmentation'][0],dtype=float).reshape(-1,2)/512.;assert len(points)>=3 and np.isfinite(points).all() and (points>=0).all() and (points<=1).all();labels.append('0 '+' '.join(f'{v:.8f}' for v in points.ravel()))
 lp=D/'labels/train'/f"m{x['id']}.txt";lp.write_text('\n'.join(labels)+'\n');records.append({'group':'menne','id':x['id'],'slide':x['slide'],'xy':x['xy'],'source_image':str(src.relative_to(R)),'source_sha256':sha(src),'annotation_ids':[a['id'] for a in anns],'image':str(dst.relative_to(R)),'image_sha256':sha(dst),'label':str(lp.relative_to(R)),'label_sha256':sha(lp)})
(D/'dataset.yaml').write_text(f'path: {D}\ntrain: images/train\nval: images/train\nnames:\n  0: diatom\n');(O/'training-manifest.json').write_text(json.dumps({'format':'r95-mixed-training-manifest-v1','protocol_sha256':sha(O/'protocol.json'),'source_audit_sha256':sha(O/'menne-source-audit.json'),'records':records,'yaml_sha256':sha(D/'dataset.yaml'),'quarantined_training_fields':sorted(skip),'warning':'Train and val paths are identical; there is no held-out validation or biological-independence proof. The added source labels omit fragments and may omit or merge objects.'},indent=2)+'\n');print('Prepared',len(records),'images;',sum(len(x['annotation_ids']) for x in records),'source polygons; skipped fields',sorted(skip))
