"""Join Academy source slide metadata to existing native-grid scene recipes."""
import csv,hashlib,json,re
from pathlib import Path
from PIL import Image
R=Path(__file__).resolve().parents[1];O=R/'results/r112/design/native-scenes';INVENTORY=R/'results/scan-inventory.csv'
def sha(p):return hashlib.sha256(Path(p).read_bytes()).hexdigest()
rows=list(csv.DictReader(INVENTORY.open()));by_name={r['filename']:r for r in rows};assert len(by_name)==len(rows);scenes=json.loads((O/'manifest.json').read_text())['scenes'];out=[]
for scene in scenes:
 bg=scene['background'];entry=by_name[bg['slide']];scan=R/'scans'/bg['slide'];size=scan.stat().st_size;assert size>=1_000_000_000 and size==int(entry['bytes'])==bg['slide_bytes'];crop=R/bg['path'];assert sha(crop)==bg['sha256'] and Image.open(crop).size==(768,768);match=re.search(r'_(\d+)x_.*_([0-9]+(?:\.[0-9]+)?)um\.ome\.tiff$',bg['slide']);assert match;out.append({'scene_id':scene['id'],'slide':bg['slide'],'filename_objective_magnification':int(match.group(1)),'filename_nominal_z_step_um':float(match.group(2)),'scale_source':'results/scan-inventory.csv, extracted from OME PhysicalSizeX/Y','background_um_per_pixel_x':float(entry['um_per_pixel_x']),'background_um_per_pixel_y':float(entry['um_per_pixel_y']),'crop_size_px':[768,768],'crop_size_um':[768*float(entry['um_per_pixel_x']),768*float(entry['um_per_pixel_y'])],'source_cutout_physical_scales':'unknown','inserted_cutouts_scale_matched':False})
p={'format':'r112-background-calibration-v1','native_scene_manifest_sha256':sha(O/'manifest.json'),'scan_inventory_sha256':sha(INVENTORY),'calibration_warning':'Filename magnification and Z step are not lateral micrometres per pixel; lateral values are inventory-reported OME metadata. Source cutout scales remain unknown. No source-to-background scaling was applied.','scenes':out};(O/'background-calibration.json').write_text(json.dumps(p,indent=2)+'\n');print('Calibrated',len(out),'background records; source scales remain unknown.');print('first',out[0]['slide'],out[0]['background_um_per_pixel_x'],out[0]['background_um_per_pixel_y'])
