"""Prepare a visual proposal-matching page using an independent reference field."""
import argparse
import html
import json
import math
from pathlib import Path
from PIL import Image,ImageDraw,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('--predictions',type=Path,required=True)
    p.add_argument('--reference',type=Path,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());pred=json.loads(a.predictions.read_text());ref=json.loads(a.reference.read_text());bundle_file=a.bundle/'bundle.json';bundle=json.loads(bundle_file.read_text())
    if (protocol.get('format')!='diatom-frozen-field-protocol-v1' or pred.get('format')!='diatom-frozen-field-predictions-v1'
        or pred.get('protocol_sha256')!=digest(a.protocol) or pred.get('bundle_sha256')!=digest(bundle_file)
        or pred.get('bundle_id')!=bundle.get('bundle_id') or pred.get('candidate_policy')!=protocol.get('candidate_policy')):raise ValueError('Prediction, protocol or bundle mismatch')
    mask_rule=protocol.get('mask_rule_id')
    if mask_rule is not None and (not isinstance(mask_rule,str) or not mask_rule or mask_rule!=mask_rule.strip()):raise ValueError('Invalid frozen mask rule')
    fields=[f for f in protocol.get('fields',[]) if f.get('id')==pred.get('field_id')]
    if (len(fields)!=1 or pred.get('sample_id')!=fields[0].get('sample_id') or ref.get('format')!='diatom-independent-field-reference-v1'
        or ref.get('protocol_sha256')!=digest(a.protocol) or ref.get('field_id')!=pred.get('field_id') or ref.get('sample_id')!=pred.get('sample_id')
        or ref.get('reference_status')!='expert_adjudicated' or ref.get('reviewer_role')!='expert'
        or not isinstance(ref.get('reviewer_id'),str) or not ref['reviewer_id'].strip() or ref.get('exhaustive') is not True):raise ValueError('Reference declarations do not match frozen field')
    image_path=inside(a.bundle,bundle['field_image'])
    if digest(image_path)!=pred.get('field_image_sha256') or ref.get('field_image_sha256')!=pred.get('field_image_sha256'):raise ValueError('Field image hash mismatch')
    with Image.open(image_path) as im:field=im.convert('RGB')
    size=bundle['size']
    if field.size!=(size,size):raise ValueError('Invalid field dimensions')
    focus_file=a.bundle/'focus-planes.json';focus=json.loads(focus_file.read_text());planes={};plane_hashes={}
    if focus.get('format')!='diatom-focus-planes-v1' or focus.get('bundle_id')!=bundle['bundle_id'] or not isinstance(focus.get('planes'),list):raise ValueError('Invalid focal-plane manifest')
    display=ref.get('display_provenance')
    if display is not None:
        if (not isinstance(display,dict) or display.get('format')!='diatom-reference-page-v1' or display.get('field_image_sha256')!=pred['field_image_sha256']
            or display.get('protocol_sha256')!=digest(a.protocol) or display.get('field_id')!=pred['field_id'] or display.get('sample_id')!=pred['sample_id']
            or display.get('size')!=bundle['size'] or display.get('model_z')!=bundle['z']):
            raise ValueError('Reference focal-plane provenance mismatch')
        if display.get('source_kind')=='unscored_scan':
            reference_planes=display.get('planes')
            if (display.get('slide')!=bundle['slide'] or display.get('slide_size_bytes')!=bundle.get('slide_size_bytes')
                or display.get('origin_xy')!=bundle['origin_xy'] or display.get('size')!=bundle['size'] or display.get('model_z')!=bundle['z']
                or not isinstance(reference_planes,list)
                or [{'z':x.get('z'),'sha256':x.get('sha256')} for x in reference_planes]!=
                   [{'z':x.get('z'),'sha256':x.get('sha256')} for x in sorted(focus['planes'],key=lambda p:p['z'])]):
                raise ValueError('Reference scan planes differ from prediction field')
        elif display.get('source_kind') is None:
            if display.get('focus_manifest_sha256')!=digest(focus_file) or display.get('bundle_id')!=bundle['bundle_id']:
                raise ValueError('Reference focal-plane provenance mismatch')
        else:raise ValueError('Unknown reference source type')
    for plane in focus['planes']:
        z=plane.get('z')
        if type(z) is not int or z<0 or z in planes:raise ValueError('Invalid focal plane')
        path=inside(a.bundle,plane['image'])
        if digest(path)!=plane.get('sha256'):raise ValueError('Focal plane hash mismatch')
        with Image.open(path) as im:
            frame=im.convert('RGB')
            if frame.size!=field.size or (z==bundle['z'] and ImageChops.difference(frame,field).getbbox()):raise ValueError('Focal plane pixels or dimensions mismatch')
            planes[z]=frame
            plane_hashes[z]=digest(path)
    if bundle['z'] not in planes:raise ValueError('Detector plane missing from focal stack')
    manifests=pred.get('source_manifest_sha256');policy=pred.get('candidate_policy','')
    expected_names=({'tile-proposals.json'} if '_plus_tile' in policy else set())|({'stack-proposals.json','focus-planes.json'} if '_plus_stack' in policy else set())|({'split-alternatives.json'} if '_plus_split' in policy else set())
    if not isinstance(manifests,dict) or set(manifests)!=expected_names:raise ValueError('Invalid source manifest provenance')
    for name,expected_hash in manifests.items():
        if name not in {'tile-proposals.json','stack-proposals.json','focus-planes.json','split-alternatives.json'} or digest(a.bundle/name)!=expected_hash:
            raise ValueError('Prediction source manifest hash mismatch')
    references=ref.get('references');predictions=pred.get('predictions')
    if not isinstance(references,list) or not isinstance(predictions,list):raise ValueError('Invalid references or predictions')
    ref_ids=set()
    for r in references:
        ident=r.get('id') if isinstance(r,dict) else None;point=r.get('field_xy') if isinstance(r,dict) else None;z=r.get('z') if isinstance(r,dict) else None
        if (not isinstance(ident,str) or not ident or ident!=ident.strip() or ident in ref_ids or not isinstance(point,list) or len(point)!=2
            or any(type(x) not in (int,float) or not math.isfinite(x) or not 0<=x<size for x in point) or type(z) is not int or z not in planes):raise ValueError('Invalid reference ID, position or plane')
        ref_ids.add(ident)
    ids=set();assets=[]
    for i,item in enumerate(predictions,1):
        ident=item.get('id') if isinstance(item,dict) else None;box=item.get('box') if isinstance(item,dict) else None
        if (not isinstance(ident,str) or not ident or ident!=ident.strip() or ident in ids or not isinstance(box,list) or len(box)!=4
            or any(type(x) not in (int,float) or not math.isfinite(x) for x in box)):raise ValueError('Invalid prediction ID or box')
        plane_z=item.get('plane_z',bundle['z'])
        if type(plane_z) is not int or plane_z not in planes:raise ValueError('Invalid proposal source plane')
        source_hash=item.get('source_plane_sha256')
        if source_hash!=plane_hashes[plane_z] and not (plane_z==bundle['z'] and source_hash==pred['field_image_sha256']):
            raise ValueError('Proposal source plane hash mismatch')
        ids.add(ident);x0,y0,x1,y1=box
        x0=max(0,math.floor(x0));y0=max(0,math.floor(y0));x1=min(size,math.ceil(x1));y1=min(size,math.ceil(y1))
        if x0>=x1 or y0>=y1:raise ValueError('Invalid proposal bounds')
        crop_path=inside(a.bundle,item.get('crop'))
        if digest(crop_path)!=item.get('source_crop_sha256'):raise ValueError('Proposal crop hash mismatch')
        with Image.open(crop_path) as im:crop=im.convert('RGB')
        expected=planes[plane_z].crop((x0,y0,x1,y1))
        if crop.size!=expected.size or ImageChops.difference(crop,expected).getbbox():raise ValueError('Proposal crop does not match source plane')
        mask_path=inside(a.bundle,item['mask']) if item.get('mask') else None
        if mask_path is None and item.get('source_mask_sha256') is not None:raise ValueError('Missing proposal mask')
        if mask_path and digest(mask_path)!=item.get('source_mask_sha256'):raise ValueError('Proposal mask hash mismatch')
        mask_status='missing'
        if mask_path:
            with Image.open(mask_path) as mask:
                if mask.size!=(size,size):raise ValueError('Invalid mask dimensions')
                mask_status='nonempty' if mask.convert('L').getbbox() else 'empty'
        if item.get('mask_status','unknown') not in ('unknown',mask_status):raise ValueError('Prediction mask status mismatch')
        assets.append((ident,(x0,y0,x1,y1),mask_path,plane_z,mask_status))
    if a.output.exists() and any(a.output.iterdir()):raise FileExistsError('Output directory must be empty')
    a.output.mkdir(parents=True,exist_ok=True);cards=[];asset_hashes={}
    for z,frame in sorted(planes.items()):
        full=frame.copy();draw=ImageDraw.Draw(full)
        for ident,box,_,_,_ in assets:draw.rectangle(box,outline='#00a7ff',width=2);draw.text((box[0]+2,box[1]+2),ident,fill='#00a7ff',stroke_width=1,stroke_fill='black')
        for r in references:
            if r['z']!=z:continue
            x,y=r['field_xy'];draw.line((x-5,y,x+5,y),fill='#ffcc00',width=2);draw.line((x,y-5,x,y+5),fill='#ffcc00',width=2);draw.text((x+6,y+2),r['id'],fill='#ffcc00',stroke_width=1,stroke_fill='black')
        filename=f'field-overview-z{z:03d}.png';full.save(a.output/filename);asset_hashes[filename]=digest(a.output/filename)
    for i,(ident,box,mask_path,plane_z,mask_status) in enumerate(assets,1):
        x0,y0,x1,y1=box;pad=48;region=(max(0,x0-pad),max(0,y0-pad),min(size,x1+pad),min(size,y1+pad));mask=None
        if mask_path:
            with Image.open(mask_path) as m:mask=m.convert('L')
            if mask.size!=(size,size):raise ValueError('Invalid mask dimensions')
        for z,frame in sorted(planes.items()):
            crop=frame.crop(region).convert('RGBA')
            if mask is not None and z==plane_z:
                alpha=mask.crop(region).point(lambda x:round(x*.28));overlay=Image.new('RGBA',crop.size,(255,64,100,0));overlay.putalpha(alpha);crop=Image.alpha_composite(crop,overlay)
            draw=ImageDraw.Draw(crop);draw.rectangle((x0-region[0],y0-region[1],x1-region[0],y1-region[1]),outline='#00a7ff',width=2)
            for r in references:
                if r['z']!=z:continue
                x,y=r['field_xy'];x-=region[0];y-=region[1]
                if 0<=x<crop.width and 0<=y<crop.height:
                    draw.line((x-5,y,x+5,y),fill='#ffcc00',width=2);draw.line((x,y-5,x,y+5),fill='#ffcc00',width=2);draw.text((x+6,y+2),r['id'],fill='#ffcc00',stroke_width=1,stroke_fill='black')
            filename=f'proposal-{i:04d}-z{z:03d}.png';crop.convert('RGB').save(a.output/filename);asset_hashes[filename]=digest(a.output/filename)
        cards.append(f'<section><h2>{html.escape(ident)}</h2><p>Proposal source plane: Z {plane_z}; mask: {mask_status}.</p><img class="plane-image" data-prefix="proposal-{i:04d}" src="proposal-{i:04d}-z{bundle["z"]:03d}.png" alt="Proposal and nearby reference points"><div class="match" data-index="{i-1}"></div></section>')
    payload={'format':'diatom-field-match-display-v1','protocol_sha256':digest(a.protocol),'predictions_sha256':digest(a.predictions),'reference_sha256':digest(a.reference),
             'field_id':pred['field_id'],'sample_id':pred['sample_id'],'prediction_ids':[x[0] for x in assets],
             'references':[{'id':r['id'],'z':r['z']} for r in references],'display_plane_z':bundle['z'],
             'focus_manifest_sha256':digest(focus_file),'planes':sorted(planes),'asset_sha256':asset_hashes,
             'mask_rule_id':mask_rule,'mask_status_by_prediction':{x[0]:x[4] for x in assets},
             'proposal_plane_by_prediction':{x[0]:x[3] for x in assets}}
    embedded=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>Match field proposals</title><style>body{font:16px/1.5 system-ui;color:#1c3835;max-width:1000px;margin:2em auto;padding:0 1em}section{border-top:1px solid #aaa;padding:1em 0}img{max-width:100%;height:auto}label{display:block;margin:.7em 0}select,input,button{font:inherit;padding:.3em}</style><h1>Match field proposals</h1><p>Reference points are yellow and appear only on their recorded plane; proposal boxes are blue and are approximate guides on other planes. Available masks are pink and appear only on their proposal source plane. The planes are not registered; consult the original stack when needed. Taxon predictions and reference names are hidden. Independent exhaustive reference annotation and a predetermined matching rule are required.</p><label>Focal plane <select id="focus"></select></label><img class="plane-image" data-prefix="field-overview" src="field-overview-zINITIALPLANE.png" alt="Full field, proposed boxes and independent reference points"><label>Matching 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><button id="recovery" hidden>Download browser recovery backup</button> <button id="download">Download matching decisions</button> <button id="download-progress">Download unfinished work</button> <button id="open">Open saved matches</button><input id="open-file" type="file" accept=".json,application/json" hidden> <span id="status" role="status">Ready.</span><p>Match every proposal or explicitly mark it unmatched. Reference specimens with no matched proposal remain misses. Decisions remain in this browser until downloaded. Download unfinished work to continue on another computer. Opening saved matches replaces this browser’s current work for this field.</p>'''+''.join(cards)
    page=page.replace('INITIALPLANE',f'{bundle["z"]:03d}')
    page=page.replace('<p>Match every proposal', '<p>Mask assessment rule: '+html.escape(mask_rule or 'not configured')+'. A nonempty mask is not automatically acceptable.</p><p>Match every proposal')
    js='''<script>"use strict";const payload=PAYLOAD,$=id=>document.getElementById(id),key='diatom-field-matching:'+payload.predictions_sha256+':'+payload.reference_sha256;let state,recoveryRaw=null,raw=null;function validStored(x){if(!x||typeof x.reviewer_id!=='string'||!['unknown','nonexpert','expert'].includes(x.reviewer_role)||!x.choices||typeof x.choices!=='object'||Array.isArray(x.choices)||canonical(x.display)!==canonical(payload))throw Error('Incompatible stored work');if(x.assessments===undefined)x.assessments={};if(x.merge_refs===undefined)x.merge_refs={};if(!validMergeMap(x.merge_refs))throw Error('Invalid stored merged references');if(!x.assessments||typeof x.assessments!=='object'||Array.isArray(x.assessments)||Object.entries(x.assessments).some(([id,v])=>!payload.prediction_ids.includes(id)||!['','acceptable','unacceptable','merged','unsure'].includes(v)))throw Error('Invalid stored mask assessments');for(const [id,v] of Object.entries(x.choices)){if(!payload.prediction_ids.includes(id)||typeof v!=='string'||(v&&!['u:duplicate','u:other','u:unknown'].includes(v)&&!payload.references.some((r,i)=>v==='r:'+i)))throw Error('Invalid stored choice')}return x}try{raw=localStorage.getItem(key)}catch(e){}if(raw!==null){try{state=validStored(JSON.parse(raw))}catch(e){recoveryRaw=raw}}if(!state)state={reviewer_id:'',reviewer_role:'unknown',choices:{},assessments:{},merge_refs:{},display:payload};function save(){if(recoveryRaw!==null)return;try{localStorage.setItem(key,JSON.stringify(state));$('status').textContent='Saved in this browser.'}catch(e){$('status').textContent='Browser storage unavailable; download decisions.'}}for(const z of payload.planes){const o=document.createElement('option');o.value=String(z);o.textContent='Z '+z+(z===payload.display_plane_z?' · detector plane':'');$('focus').append(o)}$('focus').value=String(payload.display_plane_z);$('focus').onchange=()=>{const z=Number($('focus').value);if(!payload.planes.includes(z))return;for(const image of document.querySelectorAll('.plane-image'))image.src=image.dataset.prefix+'-z'+String(z).padStart(3,'0')+'.png'};for(const [id,field] of [['reviewer','reviewer_id'],['role','reviewer_role']]){$(id).value=state[field]||(id==='role'?'unknown':'');$(id).oninput=$(id).onchange=()=>{state[field]=$(id).value;save()}}for(const c of document.querySelectorAll('.match')){const i=Number(c.dataset.index),id=payload.prediction_ids[i],label=document.createElement('label'),select=document.createElement('select');label.textContent='Match ';const options=[['','Not reviewed'],...payload.references.map((r,j)=>['r:'+j,'Reference '+r.id+' (Z '+r.z+')']),['u:duplicate','Unmatched: duplicate'],['u:other','Unmatched: other'],['u:unknown','Unmatched: unsure']];for(const [value,text] of options){const o=document.createElement('option');o.value=value;o.textContent=text;select.append(o)}select.value=state.choices[id]||'';const planeHint=document.createElement('p');function updatePlaneHint(){const ref=select.value.startsWith('r:')?payload.references[Number(select.value.slice(2))]:null,source=(payload.proposal_plane_by_prediction||{})[id]??payload.display_plane_z;planeHint.textContent=!ref?'':ref.z===source?'Reference and proposal were recorded on Z '+source+'. Mask quality still needs review.':'Reference was marked on Z '+ref.z+'; the proposal mask is from Z '+source+'. Planes are not registered; inspect the stack.'}select.onchange=()=>{state.choices[id]=select.value;updatePlaneHint();save()};label.append(select);c.append(label,planeHint);updatePlaneHint();const maskLabel=document.createElement('label'),maskSelect=document.createElement('select');maskLabel.textContent='Mask assessment under the frozen rule ';for(const [v,t] of [['','Not assessed'],['acceptable','Acceptable'],['unacceptable','Unacceptable'],['merged','Merged with another specimen'],['unsure','Unsure']]){const o=document.createElement('option');o.value=v;o.textContent=t;maskSelect.append(o)}maskSelect.value=state.assessments[id]||'';maskSelect.disabled=!payload.mask_rule_id||payload.mask_status_by_prediction[id]!=='nonempty';const extraLabel=document.createElement('label'),extra=document.createElement('select');extraLabel.textContent='Other reference specimens inside this merged mask (optional; use Ctrl/Command to select more than one) ';extra.multiple=true;extra.size=Math.min(5,Math.max(2,payload.references.length));for(const r of payload.references){const o=document.createElement('option');o.value=r.id;o.textContent=r.id+' (Z '+r.z+')';o.selected=(state.merge_refs[id]||[]).includes(r.id);extra.append(o)}extra.disabled=maskSelect.disabled||maskSelect.value!=='merged';extra.onchange=()=>{state.merge_refs[id]=Array.from(extra.selectedOptions,o=>o.value);save()};maskSelect.onchange=()=>{state.assessments[id]=maskSelect.value;extra.disabled=maskSelect.disabled||maskSelect.value!=='merged';save()};maskLabel.append(maskSelect);c.append(maskLabel);extraLabel.append(extra);c.append(extraLabel)}if(recoveryRaw!==null){for(const id of ['reviewer','role','download','download-progress'])$(id).disabled=true;for(const select of document.querySelectorAll('.match select'))select.disabled=true;$('recovery').hidden=false;$('status').textContent='Saved browser data is incompatible or damaged. Download a recovery backup, then open a valid saved match file to resume.'}$('recovery').onclick=()=>{if(recoveryRaw===null)return;const url=URL.createObjectURL(new Blob([recoveryRaw],{type:'application/json'})),link=document.createElement('a');link.href=url;link.download='matching-browser-recovery.json';link.click();setTimeout(()=>URL.revokeObjectURL(url),1000)};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 validMergeMap(map){return !!map&&typeof map==='object'&&!Array.isArray(map)&&Object.entries(map).every(([id,list])=>payload.prediction_ids.includes(id)&&Array.isArray(list)&&new Set(list).size===list.length&&list.every(ref=>payload.references.some(r=>r.id===ref)))}function knownMaskAssessment(id,v){return payload.prediction_ids.includes(id)&&['','acceptable','unacceptable','merged','unsure'].includes(v)}function validateMatchFile(file){if(!file||!['diatom-field-matches-v1','diatom-field-match-progress-v1'].includes(file.format)||canonical(file.display)!==canonical(payload))throw Error('The field, references, predictions, or displayed images do not match');if(typeof file.reviewer_id!=='string'||!['unknown','nonexpert','expert'].includes(file.reviewer_role))throw Error('Invalid reviewer');if(file.format==='diatom-field-match-progress-v1'){if(!file.choices||typeof file.choices!=='object'||Array.isArray(file.choices))throw Error('Invalid unfinished work');const choices={};for(const [id,value] of Object.entries(file.choices)){if(!payload.prediction_ids.includes(id)||typeof value!=='string')throw Error('Unknown proposal or invalid choice');if(value&&!['u:duplicate','u:other','u:unknown'].includes(value)&&!payload.references.some((r,i)=>value==='r:'+i))throw Error('Invalid match choice');choices[id]=value}const merge_refs=file.merge_refs??{};if(!validMergeMap(merge_refs))throw Error('Invalid unfinished merged references');const assessments=file.assessments??{};if(!assessments||typeof assessments!=='object'||Array.isArray(assessments)||Object.entries(assessments).some(([id,v])=>!knownMaskAssessment(id,v)))throw Error('Invalid unfinished mask assessments');return {reviewer_id:file.reviewer_id,reviewer_role:file.reviewer_role,choices,assessments,merge_refs}}if(!Array.isArray(file.matches))throw Error('Invalid matching decisions');const choices={},assessments={},merge_refs={},used=new Set(),known=new Set(payload.prediction_ids);for(const m of file.matches){if(!m||typeof m.prediction_id!=='string'||!known.has(m.prediction_id)||Object.hasOwn(choices,m.prediction_id))throw Error('Unknown or duplicate proposal');let value;if(m.reference_id===null){if(!['duplicate','other','unknown'].includes(m.unmatched_type))throw Error('Invalid unmatched type');value='u:'+m.unmatched_type}else{const i=payload.references.findIndex(r=>r.id===m.reference_id);if(i<0||used.has(m.reference_id)||m.unmatched_type!=null)throw Error('Unknown or repeated reference match');used.add(m.reference_id);value='r:'+i}choices[m.prediction_id]=value;const assessment=m.mask_assessment??'not_reviewed';if(!['not_reviewed','acceptable','unacceptable','merged','unsure','unavailable','not_applicable'].includes(assessment))throw Error('Invalid mask assessment');if(['acceptable','unacceptable','merged','unsure'].includes(assessment)){if(!payload.mask_rule_id||payload.mask_status_by_prediction[m.prediction_id]!=='nonempty'||m.reference_id===null)throw Error('Mask assessment does not match the proposal');assessments[m.prediction_id]=assessment}const extra=m.merged_reference_ids??[];if(!validMergeMap({[m.prediction_id]:extra})||(extra.length&&(assessment!=='merged'||m.reference_id===null||extra.includes(m.reference_id))))throw Error('Invalid merged reference IDs');merge_refs[m.prediction_id]=extra}if(Object.keys(choices).length!==payload.prediction_ids.length)throw Error('Missing proposal matches');return {reviewer_id:file.reviewer_id,reviewer_role:file.reviewer_role,choices,assessments,merge_refs}}$('open').onclick=()=>$('open-file').click();$('open-file').onchange=async e=>{const file=e.target.files[0];e.target.value='';if(!file)return;try{const next=validateMatchFile(JSON.parse(await file.text()));if(!confirm('Replace this browser’s current field matches? Download them first if you want to keep them.'))return;next.display=payload;localStorage.setItem(key,JSON.stringify(next));location.reload()}catch(err){$('status').textContent='Matches not opened: '+err.message}};$('download-progress').onclick=()=>{const result={format:'diatom-field-match-progress-v1',display:payload,reviewer_id:state.reviewer_id,reviewer_role:state.reviewer_role,choices:state.choices,assessments:state.assessments,merge_refs:state.merge_refs};const url=URL.createObjectURL(new Blob([JSON.stringify(result,null,2)],{type:'application/json'})),link=document.createElement('a');link.href=url;link.download='field-matching-progress.json';link.click();setTimeout(()=>URL.revokeObjectURL(url),1000)};$('download').onclick=()=>{const matches=[],used=new Set();for(const id of payload.prediction_ids){const v=state.choices[id]||'';if(!v){$('status').textContent='Match every proposal before downloading.';return}if(v.startsWith('r:')){const ref=payload.references[Number(v.slice(2))];if(!ref||used.has(ref.id)){$('status').textContent='A reference cannot be matched to multiple proposals; mark extra proposals as duplicates.';return}used.add(ref.id);const assessment=payload.mask_status_by_prediction[id]==='nonempty'?(payload.mask_rule_id?(state.assessments[id]||'not_reviewed'):'not_reviewed'):'unavailable',extra=assessment==='merged'?(state.merge_refs[id]||[]):[];if(extra.includes(ref.id)){$('status').textContent='Other references cannot include the primary matched reference.';return}matches.push({prediction_id:id,reference_id:ref.id,mask_assessment:assessment,merged_reference_ids:extra})}else if(['u:duplicate','u:other','u:unknown'].includes(v))matches.push({prediction_id:id,reference_id:null,unmatched_type:v.slice(2),mask_assessment:'not_applicable'});else{$('status').textContent='Invalid match.';return}}const result={format:'diatom-field-matches-v1',display:payload,reviewer_id:state.reviewer_id,reviewer_role:state.reviewer_role,matches};const url=URL.createObjectURL(new Blob([JSON.stringify(result,null,2)],{type:'application/json'})),link=document.createElement('a');link.href=url;link.download='field-matches.json';link.click();setTimeout(()=>URL.revokeObjectURL(url),1000)};</script></html>'''
    (a.output/'index.html').write_text(page+js.replace('PAYLOAD',embedded));print(f'Prepared matching page for {len(predictions)} predictions and {len(references)} declared independent references.')


if __name__=='__main__':main()
