"""Flag spatially overlapping model masks in adjacent review fields for human review."""
import argparse
import html
import json
import re
from pathlib import Path

import numpy as np
from PIL import Image,ImageChops

from ingest_review import digest,inside


def main():
    p=argparse.ArgumentParser(description=__doc__);p.add_argument('--batch',type=Path,required=True)
    p.add_argument('--jobs',type=Path,required=True);p.add_argument('--output',type=Path,required=True)
    p.add_argument('--min-pixels',type=int,default=20);p.add_argument('--iou',type=float,default=.2)
    p.add_argument('--containment',type=float,default=.6);a=p.parse_args()
    if a.min_pixels<1 or not 0<a.iou<=1 or not 0<a.containment<=1:p.error('Invalid overlap thresholds')
    jobs=json.loads(a.jobs.read_text());fields=[]
    if jobs.get('format')!='diatom-field-jobs-v1':raise ValueError('Invalid jobs')
    for job in jobs['fields']:
        if not isinstance(job.get('id'),str) or not re.fullmatch(r'[A-Za-z0-9][A-Za-z0-9_-]{0,63}',job['id']):raise ValueError('Invalid field ID')
        directory=a.batch/job['id'];bundle=json.loads((directory/'bundle.json').read_text())
        if (bundle['slide']!=Path(job['slide']).name or bundle['origin_xy']!=[job['x'],job['y']]
            or bundle['z']!=job['z'] or bundle['size']!=job.get('size',768)):raise ValueError('Bundle does not match job')
        image=inside(directory,bundle['field_image'])
        candidates=[]
        for c in bundle['candidates']:
            if not c.get('mask'):continue
            path=inside(directory,c['mask'])
            crop_path=inside(directory,c['crop'])
            candidates.append({'id':c['id'],'mask_path':path,'mask_sha256':digest(path),'crop_path':crop_path,'crop_sha256':digest(crop_path)})
        fields.append({'id':job['id'],'bundle':bundle,'image':image,'image_sha256':digest(image),'candidates':candidates})
    if a.output.exists() and any(a.output.iterdir()):raise FileExistsError('Output must be empty')
    a.output.mkdir(parents=True,exist_ok=True);records=[];sections=[];compared=0;checked=0
    for i,first in enumerate(fields):
        b=first['bundle'];ax,ay=b['origin_xy'];size=b['size']
        for second in fields[i+1:]:
            c=second['bundle'];bx,by=c['origin_xy'];other_size=c['size']
            if (b['slide'],b['slide_size_bytes'],b['z'])!=(c['slide'],c['slide_size_bytes'],c['z']):continue
            left,top=max(ax,bx),max(ay,by);right,bottom=min(ax+size,bx+other_size),min(ay+size,by+other_size)
            if left>=right or top>=bottom:continue
            ar=(left-ax,top-ay,right-ax,bottom-ay);br=(left-bx,top-by,right-bx,bottom-by)
            with Image.open(first['image']) as ia,Image.open(second['image']) as ib:
                if ia.size!=(size,size) or ib.size!=(other_size,other_size):raise ValueError('Unexpected field image dimensions')
                common=ia.convert('RGB').crop(ar);other_image=ib.convert('RGB').crop(br)
            if ImageChops.difference(common,other_image).getbbox():raise ValueError('Overlapping field pixels differ; cannot compare')
            compared+=1
            for ca in first['candidates']:
                with Image.open(ca['mask_path']) as image:full_a=np.asarray(image.convert('L'))>0
                if full_a.shape!=(size,size):raise ValueError('Unexpected mask dimensions')
                ma=full_a[ar[1]:ar[3],ar[0]:ar[2]];area_a=int(full_a.sum())
                for cb in second['candidates']:
                    with Image.open(cb['mask_path']) as image:full_b=np.asarray(image.convert('L'))>0
                    if full_b.shape!=(other_size,other_size):raise ValueError('Unexpected mask dimensions')
                    checked+=1;mb=full_b[br[1]:br[3],br[0]:br[2]]
                    intersection=int((ma&mb).sum());area_b=int(full_b.sum());union=area_a+area_b-intersection
                    iou=intersection/union if union else 0;smaller=min(area_a,area_b);containment=intersection/smaller if smaller else 0
                    if intersection<a.min_pixels or (iou<a.iou and containment<a.containment):continue
                    display=np.asarray(common).copy().astype(np.float32)
                    display[ma]=.55*display[ma]+.45*np.array([255,50,150]);display[mb]=.55*display[mb]+.45*np.array([255,180,0])
                    filename=f'pair-{len(records)+1:04d}.png';Image.fromarray(display.astype('uint8')).save(a.output/filename)
                    crop_a=f'pair-{len(records)+1:04d}-a.png';crop_b=f'pair-{len(records)+1:04d}-b.png'
                    with Image.open(ca['crop_path']) as im:im.convert('RGB').save(a.output/crop_a)
                    with Image.open(cb['crop_path']) as im:im.convert('RGB').save(a.output/crop_b)
                    item={'a_field':first['id'],'a_id':ca['id'],'a_mask_sha256':ca['mask_sha256'],
                          'b_field':second['id'],'b_id':cb['id'],'b_mask_sha256':cb['mask_sha256'],
                          'a_bundle_id':b['bundle_id'],'b_bundle_id':c['bundle_id'],
                          'a_field_image_sha256':first['image_sha256'],'b_field_image_sha256':second['image_sha256'],
                          'a_source_crop_sha256':ca['crop_sha256'],'b_source_crop_sha256':cb['crop_sha256'],
                          'same_plane_z':b['z'],'common_field_xyxy':[left,top,right,bottom],
                          'intersection_pixels':intersection,'iou':iou,'smaller_mask_containment':containment,'overlay':filename,
                          'a_crop':crop_a,'b_crop':crop_b,'overlay_sha256':digest(a.output/filename),
                          'a_crop_sha256':digest(a.output/crop_a),'b_crop_sha256':digest(a.output/crop_b)}
                    records.append(item);sections.append(f'<section><h2>{html.escape(first["id"])} / {html.escape(ca["id"])} and {html.escape(second["id"])} / {html.escape(cb["id"])}</h2><p>First candidate crop / second candidate crop:</p><img src="{crop_a}" alt="First candidate crop"> <img src="{crop_b}" alt="Second candidate crop"><p>Shared field area and masks:</p><img src="{filename}" alt="Overlapping model masks in the shared field area"><p>Intersection {intersection} pixels; IoU {iou:.3f}; smaller mask covered {containment:.3f}.</p><div class="pair-review" data-index="{len(records)-1}"></div></section>')
    result={'format':'diatom-cross-field-duplicate-candidates-v1','asset_provenance':'sha256-v1','jobs_sha256':digest(a.jobs),'overlapping_field_pairs':compared,
            'mask_pairs_compared':checked,'thresholds':{'min_pixels':a.min_pixels,'iou_or':a.iou,'containment_or':a.containment},
            'warning':'Heuristic candidates only; overlapping masks can be distinct diatoms. No records were merged.', 'pairs':records}
    (a.output/'pairs.json').write_text(json.dumps(result,indent=2)+'\n')
    page='''<!doctype html><html lang="en"><meta charset="utf-8"><meta name="viewport" content="width=device-width"><title>Possible cross-field duplicates</title><style>body{font:16px/1.5 system-ui;color:#1c3835;max-width:960px;margin:2em auto;padding:0 1em}img{max-width:100%}section{border-top:1px solid #aaa}label{display:block;margin:.8em 0}textarea{width:100%;max-width:40em}</style><h1>Possible cross-field duplicates</h1><p>These are review suggestions, not merged specimens. Pink and orange show separate masks in the shared field area. Overlapping masks can belong to different crossing diatoms; a missed pair does not prove uniqueness. Only model masks on the same plane are compared.</p><p>'''+f'{len(records)} potential pairs found among {compared} overlapping field pairs and {checked} mask pairs. '+'''<a href="pairs.json">Details and thresholds</a> · <a href="../">Batch fields</a></p><label>Reviewer ID (optional) <input id="reviewer"></label><label>Experience <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="download" disabled>Download pair review JSON</button> <button id="open-review" disabled>Open saved pair review</button><input id="review-file" type="file" accept=".json,application/json" hidden> <span id="status" role="status">Loading…</span><p>Decisions stay in this browser until downloaded. They are reviewer opinions and do not merge specimens.</p>'''+''.join(sections)
    js='''<script>"use strict";const sourceHash=SOURCE_HASH,key='diatom-duplicate-review:'+sourceHash,$=id=>document.getElementById(id);let source,state;function save(){try{localStorage.setItem(key,JSON.stringify(state));$('status').textContent='Saved in this browser.'}catch(e){$('status').textContent='Browser storage unavailable; download the review.'}}async function init(){try{const r=await fetch('pairs.json',{cache:'no-store'});if(!r.ok)throw Error('HTTP '+r.status);source=await r.json();if(source.format!=='diatom-cross-field-duplicate-candidates-v1'||!Array.isArray(source.pairs))throw Error('Invalid pairs file');try{state=JSON.parse(localStorage.getItem(key))}catch(e){}if(!state||!Array.isArray(state.decisions)||state.decisions.length!==source.pairs.length)state={reviewer:'',role:'unknown',decisions:source.pairs.map(()=>({decision:'unreviewed',note:''}))};$('reviewer').value=state.reviewer||'';$('role').value=state.role||'unknown';$('reviewer').oninput=()=>{state.reviewer=$('reviewer').value;save()};$('role').onchange=()=>{state.role=$('role').value;save()};for(const container of document.querySelectorAll('.pair-review')){const i=Number(container.dataset.index),data=state.decisions[i];const label=document.createElement('label');label.textContent='Do these show the same specimen? ';const select=document.createElement('select');for(const [value,text] of [['unreviewed','Not reviewed'],['same','Likely the same'],['different','Likely different'],['unsure','Unsure']]){const option=document.createElement('option');option.value=value;option.textContent=text;select.append(option)}select.value=data.decision;select.onchange=()=>{data.decision=select.value;save()};label.append(select);const noteLabel=document.createElement('label');noteLabel.textContent='Notes ';const note=document.createElement('textarea');note.value=data.note||'';note.oninput=()=>{data.note=note.value;save()};noteLabel.append(note);container.append(label,noteLabel)}$('download').disabled=false;$('open-review').disabled=false;$('status').textContent='Ready.'}catch(e){$('status').textContent='Could not load pair review: '+e.message}}$('download').onclick=()=>{const result={format:'diatom-cross-field-pair-review-v1',source_sha256:sourceHash,source,review:state,exported_at:new Date().toISOString()};const url=URL.createObjectURL(new Blob([JSON.stringify(result,null,2)],{type:'application/json'})),a=document.createElement('a');a.href=url;a.download='diatom-cross-field-pair-review.json';a.click();setTimeout(()=>URL.revokeObjectURL(url),1000)};function validateImportedReview(file){if(!file||file.format!=='diatom-cross-field-pair-review-v1'||file.source_sha256!==sourceHash||JSON.stringify(file.source)!==JSON.stringify(source))throw Error('The saved review does not match these candidate pairs');const r=file.review;if(!r||typeof r.reviewer!=='string'||!['unknown','nonexpert','expert'].includes(r.role)||!Array.isArray(r.decisions)||r.decisions.length!==source.pairs.length||r.decisions.some(d=>!d||!['unreviewed','same','different','unsure'].includes(d.decision)||typeof d.note!=='string'))throw Error('Invalid pair decisions or reviewer details');return r}$('open-review').onclick=()=>$('review-file').click();$('review-file').onchange=async e=>{const file=e.target.files[0];e.target.value='';if(!file)return;try{const imported=validateImportedReview(JSON.parse(await file.text()));if(!confirm('Replace this browser’s pair review? Download the current review first if you want to keep it.'))return;localStorage.setItem(key,JSON.stringify(imported));location.reload()}catch(err){$('status').textContent='Review not opened: '+err.message}};init();</script></html>'''
    expected=json.dumps(result,ensure_ascii=True,separators=(',',':')).replace('</','<\\/')
    js=js.replace("source=await r.json();if(source.format", "source=await r.json();if(JSON.stringify(source)!==JSON.stringify(EXPECTED_SOURCE))throw Error('Pair data changed; regenerate this page');if(source.format")
    (a.output/'index.html').write_text(page+js.replace('SOURCE_HASH',json.dumps(digest(a.output/'pairs.json'))).replace('EXPECTED_SOURCE',expected))
    print(f'{len(records)} potential pairs from {compared} overlapping field pairs and {checked} mask pairs')


if __name__=='__main__':main()
