"""Check paired scores and reconstruct selected seam-repair inputs."""
import json
from pathlib import Path
import numpy as np
from PIL import Image
from diatom_pilot.ude_scaleup_dataset import UDEScaleupDataset
from r112_scaleup_seam_repair import render,augment,sha
R=Path(__file__).resolve().parents[1];D=R/'results/r112/species-scaleup';O=D/'seam-repair-comparison';B=D/'real-crop-baseline';p=json.loads((O/'protocol.json').read_text());r=json.loads((O/'results.json').read_text());base=json.loads((B/'results.json').read_text());old=json.loads((D/'synthetic-crop-comparison/results.json').read_text())['composites']
assert r['protocol_sha256']==sha(O/'protocol.json') and r['script_sha256']==sha(R/'research/r112_scaleup_seam_repair.py')
for f,h in p['inputs_sha256'].items():assert sha(R/f)==h,f
assert r['features_sha256']==sha(O/'features.npz') and r['models_sha256']==sha(O/'models.npz')
train=UDEScaleupDataset('training',include_unverified_masks=True);tune=UDEScaleupDataset('tuning');f=np.load(O/'features.npz');v=np.load(B/'tuning-features.npz');models=np.load(O/'models.npz');assert f['annotation_ids'].tolist()==[x['annotation_id'] for x in train.entries] and len(r['records'])==len(train)
for k in ('synthetic','augmented'):assert f[k].shape==(2830,512) and np.isfinite(f[k]).all()
labels=base['labels'];truth=[x['source_species'] for x in tune.entries];genera=base['genera'];counts={}
for name in ('synthetic','mixed','augmentation'):
 scores=v['features']@models[name+'_weight'].T+models[name+'_bias'];order=np.argsort(-scores,axis=1,kind='stable');pred=[labels[i] for i in order[:,0]];top5=[[labels[i] for i in row[:5]] for row in order];m=r['methods'][name];assert pred==m['predictions'] and top5==m['top5_names'];counts[name]={'top1':sum(a==b for a,b in zip(pred,truth)),'top5':sum(a in b for a,b in zip(truth,top5)),'genus':sum(genera[a]==x['source_genus'] for a,x in zip(pred,tune.entries))};assert all(m[k]==value for k,value in counts[name].items())
for i in range(len(train)):
 a=r['records'][i];b=old[i];assert a['annotation_id']==b['annotation_id']==train.entries[i]['annotation_id'];assert a['background_path']==b['background_path'] and a['background_sha256']==b['background_sha256'] and a['seed']==b['seed'];assert a['render']['opacity']==b['opacity'] and a['render']['contrast']==b['contrast']
for i in (0,19,39,79):
 row=r['records'][i];path=R/row['background_path'];assert sha(path)==row['background_sha256'];img,settings=render(train[i],np.asarray(Image.open(path).convert('L')),row['background_scale_um_px'],row['seed']);aug,ap=augment(train[i],row['augment_seed']);assert settings==row['render'] and ap==row['augment'];
 for key,im in [('composite',img),('augment',aug)]:assert np.array_equal(np.asarray(im),np.asarray(Image.open(R/row[key+'_example']))) and sha(R/row[key+'_example'])==row[key+'_sha256']
report={'format':'r112-seam-repair-verify-v1','results_sha256':sha(O/'results.json'),'counts':counts,'paired_composites':len(train),'reconstructed_indices':[0,19,39,79],'reflected_padded_cases':sum(any(x['render']['reflected_padding_bottom_right']) for x in r['records']),'checks':'Inputs, saved feature arrays, all reported predictions and metrics, same per-source background and blend parameters as prior experiment, and four image pairs reconstructed. Head optimization and all embeddings were not replayed. Check-partition pixels were not read. Mask correctness, taxonomy, realism and Academy performance remain unverified.'};(O/'verify.json').write_text(json.dumps(report,indent=2)+'\n');print(json.dumps(report,indent=2))
