"""Prepare a reference-only focal-stack page for independent human annotation."""
import argparse
import hashlib
import json
import shutil
from pathlib import Path
from PIL import Image,ImageChops
from ingest_review import digest,inside


def main():
    p=argparse.ArgumentParser(description=__doc__);p.add_argument('--protocol',type=Path,required=True)
    p.add_argument('--field-id',required=True);p.add_argument('--bundle',type=Path,required=True);p.add_argument('--output',type=Path,required=True);a=p.parse_args()
    protocol=json.loads(a.protocol.read_text());bundle_file=a.bundle/'bundle.json';bundle=json.loads(bundle_file.read_text())
    fields=[x for x in protocol.get('fields',[]) if x.get('id')==a.field_id]
    if protocol.get('format')!='diatom-frozen-field-protocol-v1' or len(fields)!=1:raise ValueError('Field is not uniquely present in the frozen protocol')
    f=fields[0]
    if (bundle.get('format')!='diatom-field-bundle-v1' or bundle.get('slide')!=f.get('slide') or bundle.get('origin_xy')!=f.get('origin_xy')
        or bundle.get('z')!=f.get('z') or bundle.get('size')!=f.get('size')
        or (f.get('slide_size_bytes') is not None and bundle.get('slide_size_bytes')!=f['slide_size_bytes'])):raise ValueError('Bundle does not match frozen field identity')
    unsigned={k:v for k,v in bundle.items() if k!='bundle_id'}
    if hashlib.sha256(json.dumps(unsigned,sort_keys=True).encode()).hexdigest()!=bundle.get('bundle_id'):raise ValueError('Bundle identity mismatch')
    field_path=inside(a.bundle,bundle['field_image']);focus_path=a.bundle/'focus-planes.json';focus=json.loads(focus_path.read_text())
    if (focus.get('format')!='diatom-focus-planes-v1' or focus.get('bundle_id')!=bundle['bundle_id']
        or not isinstance(focus.get('planes'),list) or not focus['planes']):raise ValueError('Invalid focal-plane manifest')
    planes=[];seen=set()
    with Image.open(field_path) as im:field=im.convert('RGB')
    if field.size!=(bundle['size'],bundle['size']):raise ValueError('Invalid field dimensions')
    for item in focus['planes']:
        z=item.get('z')
        if type(z) is not int or z<0 or z in seen:raise ValueError('Invalid focal plane ID')
        seen.add(z);path=inside(a.bundle,item['image'])
        if digest(path)!=item.get('sha256'):raise ValueError('Focal plane hash mismatch')
        with Image.open(path) as im:
            if im.size!=field.size:raise ValueError('Focal plane dimensions do not match')
            if z==bundle['z'] and ImageChops.difference(im.convert('RGB'),field).getbbox():raise ValueError('Detector plane pixels differ from focal stack')
        planes.append((z,path))
    if bundle['z'] not in seen:raise ValueError('Detector plane is absent from focal stack')
    if a.output.exists() and any(a.output.iterdir()):raise FileExistsError('Output directory must be empty')
    a.output.mkdir(parents=True,exist_ok=True);manifest=[]
    for z,path in sorted(planes):
        name=f'plane-{z:03d}.png';shutil.copyfile(path,a.output/name);manifest.append({'z':z,'image':name,'sha256':digest(a.output/name)})
    context={'format':'diatom-reference-page-v1','protocol_sha256':digest(a.protocol),'field_id':a.field_id,'sample_id':f['sample_id'],
             'field_image_sha256':digest(field_path),'bundle_id':bundle['bundle_id'],'size':bundle['size'],'model_z':bundle['z'],
             'focus_manifest_sha256':digest(focus_path),'planes':manifest}
    (a.output/'context.json').write_text(json.dumps(context,indent=2)+'\n');shutil.copyfile(Path(__file__).with_name('reference.html'),a.output/'index.html')
    print(f'Prepared reference-only page with {len(planes)} focal planes; no model proposals or taxon suggestions included.')


if __name__=='__main__':main()
