"""Prepare a static specimen adjudication page without showing prior taxon labels."""
import argparse
import html
import json
import shutil
from pathlib import Path
from PIL import Image,ImageChops,ImageDraw
import math

from ingest_review import digest,inside


def main():
    p=argparse.ArgumentParser(description=__doc__);p.add_argument('--package',type=Path,required=True);p.add_argument('--output',type=Path,required=True)
    p.add_argument('--bundle',type=Path,help='Matching field bundle to show the same crop across focal planes');a=p.parse_args()
    manifest=a.package/'specimens.json';source=json.loads(manifest.read_text())
    if source.get('format')!='diatom-reviewed-specimens-v1' or source.get('adjudicated') is not False or not isinstance(source.get('specimens'),list):raise ValueError('Expected unadjudicated specimen package')
    if a.output.exists() and any(a.output.iterdir()):raise FileExistsError('Output directory must be empty')
    ids=[s['id'] for s in source['specimens']]
    if len(ids)!=len(set(ids)):raise ValueError('Duplicate specimen IDs')
    plane_images={};display_provenance=None
    if a.bundle:
        bundle=json.loads((a.bundle/'bundle.json').read_text());focus_file=a.bundle/'focus-planes.json';focus=json.loads(focus_file.read_text())
        if (bundle.get('bundle_id')!=source.get('bundle_id') or bundle.get('slide')!=source.get('slide')
            or bundle.get('origin_xy')!=source.get('origin_xy') or focus.get('format')!='diatom-focus-planes-v1'
            or focus.get('bundle_id')!=bundle['bundle_id'] or not isinstance(focus.get('planes'),list)):
            raise ValueError('Field bundle or focus manifest mismatch')
        for plane in focus['planes']:
            z=plane.get('z')
            if type(z) is not int or z in plane_images:raise ValueError('Invalid or duplicate focal plane')
            path=inside(a.bundle,plane['image'])
            if digest(path)!=plane.get('sha256'):raise ValueError('Focal-plane image hash mismatch')
            with Image.open(path) as im:
                if im.size!=(bundle['size'],bundle['size']):raise ValueError('Invalid focal-plane image dimensions')
                plane_images[z]=im.convert('RGB')
        display_provenance={'bundle_id':bundle['bundle_id'],'focus_manifest_sha256':digest(focus_file),
                            'planes':[{'z':x['z'],'sha256':x['sha256']} for x in focus['planes']]}
    assets=[]
    for i,s in enumerate(source['specimens'],1):
        crop=s.get('crop');asset=None
        if crop:
            image=inside(a.package,crop['image'])
            if digest(image)!=crop.get('image_sha256'):raise ValueError('Specimen image hash mismatch')
            asset=(image,f'specimen-{i:04d}.png')
        assets.append((s,asset))
    a.output.mkdir(parents=True,exist_ok=True);sections=[]
    for index,(s,asset) in enumerate(assets,1):
        if asset:
            shutil.copyfile(asset[0],a.output/asset[1]);image=f'<img id="specimen-image-{index}" src="{asset[1]}" alt="Specimen context crop">'
            if a.bundle:
                crop=s['crop'];box=crop.get('field_bbox_xyxy');z=crop.get('z')
                if (not isinstance(box,list) or len(box)!=4 or any(type(x) is not int for x in box)
                    or not 0<=box[0]<box[2]<=bundle['size'] or not 0<=box[1]<box[3]<=bundle['size'] or z not in plane_images):
                    raise ValueError('Invalid specimen crop bounds or focal plane')
                plane=next(x for x in focus['planes'] if x['z']==z)
                if crop.get('source_field_sha256')!=plane['sha256']:raise ValueError('Specimen source plane hash mismatch')
                with Image.open(asset[0]) as im:
                    if im.size!=(box[2]-box[0],box[3]-box[1]) or ImageChops.difference(im.convert('RGB'),plane_images[z].crop(tuple(box))).getbbox():
                        raise ValueError('Specimen crop differs from source plane')
                options=[]
                for plane_z,frame in sorted(plane_images.items()):
                    name=f'specimen-{index:04d}-z{plane_z:03d}.png';frame.crop(tuple(box)).save(a.output/name)
                    options.append(f'<option value="{name}"'+(' selected' if plane_z==z else '')+f'>Z {plane_z}'+(' · source plane' if plane_z==z else '')+'</option>')
                image+=f'<label>Focal plane <select class="focus-select" data-image="specimen-image-{index}">{"".join(options)}</select></label>'
        else:image='<p>No crop available for this record.</p>'
        sections.append(f'<section><h2>{html.escape(s["id"])}</h2>{image}<div class="adjudication" data-id="{html.escape(s["id"],quote=True)}"></div></section>')
    relationships=source.get('candidate_relationships',[])
    if not isinstance(relationships,list):raise ValueError('Invalid candidate relationships')
    pair_ids=[];pair_sections=[];seen_pairs=set();asset_by_id={s['id']:asset for s,asset in assets}
    for relation in relationships:
        if not isinstance(relation,dict):raise ValueError('Invalid candidate relationship')
        left,right,assessment=relation.get('a'),relation.get('b'),relation.get('relation')
        if (not isinstance(left,str) or not isinstance(right,str) or left>=right or not isinstance(assessment,str)
            or assessment not in {'same','different','unsure'} or (left,right) in seen_pairs):
            raise ValueError('Invalid or duplicate candidate relationship')
        seen_pairs.add((left,right));pair_ids.append([left,right]);images=[]
        for ident in (left,right):
            asset=asset_by_id.get(ident)
            images.append('<div><strong>'+html.escape(ident)+'</strong><br>'+
                          (f'<img src="{asset[1]}" alt="Candidate crop">' if asset else '<span>No specimen crop in this package; consult the original field.</span>')+'</div>')
        field_context=''
        if a.bundle:
            boxes=[]
            for key,ident in [('a_proposal',left),('b_proposal',right)]:
                proposal=relation.get(key)
                if not isinstance(proposal,dict) or proposal.get('id')!=ident:raise ValueError('Missing pair proposal provenance')
                box=proposal.get('box')
                if (not isinstance(box,list) or len(box)!=4 or any(type(v) not in (int,float) or not math.isfinite(v) for v in box)
                    or not (0<=box[0]<box[2]<=bundle['size'] and 0<=box[1]<box[3]<=bundle['size'])):
                    raise ValueError('Invalid pair proposal box')
                boxes.append(box)
            x0=max(0,math.floor(min(x[0] for x in boxes))-48);y0=max(0,math.floor(min(x[1] for x in boxes))-48)
            x1=min(bundle['size'],math.ceil(max(x[2] for x in boxes))+48);y1=min(bundle['size'],math.ceil(max(x[3] for x in boxes))+48)
            options=[];image_id=f'pair-image-{len(pair_ids)}'
            for z,frame in sorted(plane_images.items()):
                view=frame.crop((x0,y0,x1,y1));draw=ImageDraw.Draw(view)
                for label,box,color in zip(('A','B'),boxes,('#00d7ff','#ff9b22')):
                    rect=(box[0]-x0,box[1]-y0,box[2]-x0,box[3]-y0)
                    draw.rectangle(rect,outline=color,width=3)
                    tx=rect[0]+3;ty=rect[1]+3 if label=='A' else max(rect[1]+3,rect[3]-16)
                    draw.rectangle((tx-1,ty-1,tx+10,ty+12),fill=color);draw.text((tx,ty),label,fill='black')
                name=f'pair-{len(pair_ids):04d}-z{z:03d}.png';view.save(a.output/name)
                options.append(f'<option value="{name}"'+(' selected' if z==bundle['z'] else '')+f'>Z {z}</option>')
            initial=f'pair-{len(pair_ids):04d}-z{bundle["z"]:03d}.png'
            if bundle['z'] not in plane_images:raise ValueError('Pair source focal plane unavailable')
            field_context=(f'<p>Shared field context: A = {html.escape(left)}, B = {html.escape(right)}. '
                'Boxes are approximate guides copied across planes, not outlines or proof of alignment.</p>'
                f'<img id="{image_id}" src="{initial}" alt="Shared field context for candidate pair">'
                f'<label>Focal plane <select class="focus-select" data-image="{image_id}">{"".join(options)}</select></label>')
        pair_sections.append(f'<section><h3>Pair {len(pair_ids)}</h3>{field_context}<div class="pair-images">{"".join(images)}</div><div class="pair-adjudication" data-index="{len(pair_ids)-1}"></div></section>')
    payload={'source_package_sha256':digest(manifest),'ids':ids,'pair_ids':pair_ids,'display_provenance':display_provenance};expected=json.dumps(payload,ensure_ascii=True,separators=(',',':')).replace('</','<\\/')
    page='''<!doctype html><html lang="en"><meta charset="utf-8"><meta name="viewport" content="width=device-width"><title>Specimen adjudication</title><style>body{font:16px/1.5 system-ui;color:#1c3835;max-width:900px;margin:2em auto;padding:0 1em}section{border-top:1px solid #aaa;padding:1em 0}img{max-width:360px;max-height:300px;object-fit:contain}label{display:block;margin:.7em 0}input,select,textarea{font:inherit}.pair-images{display:flex;gap:1em;flex-wrap:wrap}</style><h1>Specimen adjudication</h1><p>Prior taxon labels are not displayed. Focal-plane crops use the same pixel coordinates; alignment across planes is not verified. Crops and model-derived boundaries may be incomplete or contain other objects; consult the original field and focal planes as needed. This page alone does not guarantee blinded or independent review. An expert and a scientist-approved protocol are needed for adjudication.</p><label>Reviewer ID <input id="reviewer"></label><label>Reviewer role <select id="role"><option value="unknown">Not specified</option><option value="nonexpert">Nonexpert / practice</option><option value="expert">Diatom expert</option></select></label><label>Protocol ID <input id="protocol"></label><button id="download">Download decisions</button> <button id="open">Open saved decisions</button><input id="open-file" type="file" accept=".json,application/json" hidden> <span id="status" role="status">Ready.</span><p>Decisions stay in this browser until downloaded. Open a saved file on another computer to continue; opening replaces this browser’s decisions for this package. Unreviewed records are omitted; an unsure decision does not create an adjudicated label.</p>'''+''.join(sections)+('<h2>Candidate pairs</h2><p>Earlier opinions are hidden. Decide whether each pair shows one specimen or two; use the original field and focal planes as needed. Crops alone may not resolve the pair.</p>'+''.join(pair_sections) if pair_sections else '')
    js='''<script>"use strict";const payload=PAYLOAD,key='diatom-specimen-adjudication:'+payload.source_package_sha256,$=id=>document.getElementById(id);let state;try{state=JSON.parse(localStorage.getItem(key))}catch(e){}if(!state||!state.choices)state={reviewer_id:'',reviewer_role:'unknown',protocol_id:'',choices:{}};state.pairs=state.pairs||{};function save(){try{localStorage.setItem(key,JSON.stringify(state));$('status').textContent='Saved in this browser.'}catch(e){$('status').textContent='Browser storage unavailable; download decisions.'}}for(const id of ['reviewer','protocol','role']){const field={reviewer:'reviewer_id',protocol:'protocol_id',role:'reviewer_role'}[id];$(id).value=state[field]|| (id==='role'?'unknown':'');$(id).oninput=$(id).onchange=()=>{state[field]=$(id).value;save()}}function select(label,values,value,update){const l=document.createElement('label');l.textContent=label+' ';const s=document.createElement('select');for(const [v,t] of values){const o=document.createElement('option');o.value=v;o.textContent=t;s.append(o)}s.value=value;s.onchange=()=>{update(s.value);save()};l.append(s);return l}for(const container of document.querySelectorAll('.adjudication')){const id=container.dataset.id,c=state.choices[id]||{verdict:'unreviewed',taxon_rank:'unknown',taxon_text:'',certainty:'unknown',note:''};state.choices[id]=c;container.append(select('Verdict',[['unreviewed','Not reviewed'],['confirmed','Confirmed specimen'],['rejected','Not an eligible specimen'],['unsure','Unsure']],c.verdict,v=>c.verdict=v),select('Taxon rank',[['unknown','Unknown'],['genus','Genus'],['species','Species'],['other','Other']],c.taxon_rank,v=>c.taxon_rank=v));for(const [key,title] of [['taxon_text','Taxon name'],['note','Notes']]){const l=document.createElement('label');l.textContent=title+' ';const input=document.createElement(key==='note'?'textarea':'input');input.value=c[key];input.oninput=()=>{c[key]=input.value;save()};l.append(input);container.append(l)}container.append(select('Identification certainty',[['unknown','Not specified'],['tentative','Tentative'],['confident','Confident'],['unresolved','Unresolved']],c.certainty,v=>c.certainty=v))}for(const container of document.querySelectorAll('.pair-adjudication')){const index=container.dataset.index,c=state.pairs[index]||{relation:'unreviewed',note:''};state.pairs[index]=c;container.append(select('Pair assessment',[['unreviewed','Not reviewed'],['same','Likely the same specimen'],['different','Likely different specimens'],['unsure','Unsure']],c.relation,v=>c.relation=v));const l=document.createElement('label'),input=document.createElement('textarea');l.textContent='Pair notes ';input.value=c.note;input.oninput=()=>{c.note=input.value;save()};l.append(input);container.append(l)}for(const control of document.querySelectorAll('.focus-select'))control.onchange=()=>{document.getElementById(control.dataset.image).src=control.value};function canonical(x){if(Array.isArray(x))return '['+x.map(canonical).join(',')+']';if(x&&typeof x==='object')return '{'+Object.keys(x).sort().map(k=>JSON.stringify(k)+':'+canonical(x[k])).join(',')+'}';return JSON.stringify(x)}
function validateDecisions(file){if(!file||file.format!=='diatom-specimen-adjudication-v1'||file.source_package_sha256!==payload.source_package_sha256||canonical(file.display_provenance??null)!==canonical(payload.display_provenance??null))throw Error('The source package or displayed focal planes do not match this page');if(typeof file.reviewer_id!=='string'||typeof file.protocol_id!=='string'||!['unknown','nonexpert','expert'].includes(file.reviewer_role)||!Array.isArray(file.decisions)||!Array.isArray(file.pair_decisions??[]))throw Error('Invalid reviewer or decision list');const choices={},pairs={},known=new Set(payload.ids),pairIds=payload.pair_ids||[];for(const item of file.decisions){if(!item||typeof item.specimen_id!=='string'||!known.has(item.specimen_id)||Object.hasOwn(choices,item.specimen_id)||!['confirmed','rejected','unsure'].includes(item.verdict)||!['unknown','genus','species','other'].includes(item.taxon_rank)||typeof item.taxon_text!=='string'||!['unknown','tentative','confident','unresolved'].includes(item.certainty)||typeof item.note!=='string')throw Error('Invalid or duplicate specimen decision');choices[item.specimen_id]={verdict:item.verdict,taxon_rank:item.taxon_rank,taxon_text:item.taxon_text,certainty:item.certainty,note:item.note}}for(const item of file.pair_decisions??[]){if(!item||typeof item.a!=='string'||typeof item.b!=='string'||!['same','different','unsure'].includes(item.relation)||typeof item.note!=='string')throw Error('Invalid pair decision');const i=pairIds.findIndex(pair=>pair[0]===item.a&&pair[1]===item.b);if(i<0||Object.hasOwn(pairs,i))throw Error('Unknown or duplicate candidate pair');pairs[i]={relation:item.relation,note:item.note}}return {reviewer_id:file.reviewer_id,reviewer_role:file.reviewer_role,protocol_id:file.protocol_id,choices,pairs}}
$('open').onclick=()=>$('open-file').click();$('open-file').onchange=async e=>{const file=e.target.files[0];e.target.value='';if(!file)return;try{const imported=validateDecisions(JSON.parse(await file.text()));if(!confirm('Replace this browser’s decisions for this package? Download the current decisions first if you want to keep them.'))return;localStorage.setItem(key,JSON.stringify(imported));location.reload()}catch(err){$('status').textContent='Decisions not opened: '+err.message}};
$('download').onclick=()=>{const decisions=Object.entries(state.choices).filter(([id,c])=>c.verdict!=='unreviewed').map(([specimen_id,c])=>({specimen_id,...c}));const pair_decisions=Object.entries(state.pairs).filter(([i,c])=>c.relation!=='unreviewed').map(([i,c])=>({a:payload.pair_ids[i][0],b:payload.pair_ids[i][1],relation:c.relation,note:c.note}));const result={format:'diatom-specimen-adjudication-v1',source_package_sha256:payload.source_package_sha256,display_provenance:payload.display_provenance,reviewer_id:state.reviewer_id,reviewer_role:state.reviewer_role,protocol_id:state.protocol_id,decisions,pair_decisions};const url=URL.createObjectURL(new Blob([JSON.stringify(result,null,2)],{type:'application/json'})),a=document.createElement('a');a.href=url;a.download='diatom-specimen-decisions.json';a.click();setTimeout(()=>URL.revokeObjectURL(url),1000)};</script></html>'''
    (a.output/'index.html').write_text(page+js.replace('PAYLOAD',expected))
    print(f'Prepared {len(ids)} specimen records; no prior taxon labels displayed.')


if __name__=='__main__':main()
