"""Propose review-only masks for manual points in an exported field review."""
import argparse
import html
import json
import math
from pathlib import Path

import cv2
import numpy as np
import torch
from PIL import Image, ImageDraw
from ultralytics import SAM

from ingest_review import digest, inside


def main():
    p=argparse.ArgumentParser(description=__doc__)
    p.add_argument('--review',type=Path,required=True)
    p.add_argument('--bundle',type=Path,required=True)
    p.add_argument('--segmenter',type=Path,required=True)
    p.add_argument('--output',type=Path,required=True)
    p.add_argument('--local-radius',type=int,help='Also propose masks on a square crop around each point, in pixels')
    p.add_argument('--candidate-boxes',action='store_true',help='Also prompt with the smallest same-plane detector box containing each point')
    a=p.parse_args()
    if a.local_radius is not None and a.local_radius<1:p.error('local-radius must be positive')
    review=json.loads(a.review.read_text());b=json.loads((a.bundle/'bundle.json').read_text())
    if review.get('format')!='diatom-field-review-v1' or review.get('bundle')!=b:
        raise ValueError('Review does not match bundle')
    focus=review.get('focus_planes')
    if focus is not None:
        if focus!=json.loads((a.bundle/'focus-planes.json').read_text()) or focus.get('bundle_id')!=b['bundle_id']:
            raise ValueError('Focus manifest mismatch')
    if digest(a.segmenter)!=b['models']['segmenter_sha256']:raise ValueError('Segmenter mismatch')
    boxes=[];box_sources={}
    if a.candidate_boxes:
        boxes=[{'id':c['id'],'box':c['box'],'z':b['z']} for c in b['candidates']]
        for key,filename,fmt,items in [('tile_proposals','tile-proposals.json','diatom-tile-proposals-v1','proposals'),
                                       ('stack_proposals','stack-proposals.json','diatom-stack-proposals-v1','proposals')]:
            manifest=review.get(key)
            if manifest is None:continue
            path=a.bundle/filename
            if manifest!=json.loads(path.read_text()) or manifest.get('format')!=fmt or manifest.get('bundle_id')!=b['bundle_id']:
                raise ValueError('Candidate manifest mismatch')
            box_sources[filename]=digest(path)
            boxes.extend({'id':c['id'],'box':c['box'],'z':c.get('plane_z',b['z'])} for c in manifest[items])
        if len({x['id'] for x in boxes})!=len(boxes):raise ValueError('Duplicate box candidate ID')
    marks=review.get('review',{}).get('manual',[])
    if not isinstance(marks,list):raise ValueError('Invalid manual records')
    size=b['size'];planes={} if focus is None else {x['z']:x for x in focus['planes']}
    eligible=[]
    for i,m in enumerate(marks,1):
        if not isinstance(m,dict):raise ValueError('Invalid manual record')
        if m.get('decision','unreviewed') not in {'possible','countable'}:continue
        x,y=m.get('x'),m.get('y');z=m.get('z',b['z']);group=m.get('overlap_group','')
        if (not isinstance(x,(int,float)) or isinstance(x,bool) or not math.isfinite(x) or not 0<=x<size
            or not isinstance(y,(int,float)) or isinstance(y,bool) or not math.isfinite(y) or not 0<=y<size
            or not isinstance(z,int) or isinstance(z,bool) or (z not in planes and z!=b['z'])
            or not isinstance(group,str)):raise ValueError('Invalid eligible manual point')
        eligible.append({'id':f'manual-{i:04d}','x':x,'y':y,'z':z,'overlap_group':group.strip()})
    if not eligible:raise ValueError('No manual marks with possible or countable decisions')
    if a.output.exists() and any(a.output.iterdir()):raise FileExistsError('Output must be empty')
    a.output.mkdir(parents=True,exist_ok=True)
    torch.set_num_threads(4);model=SAM(str(a.segmenter));records=[]
    for item in eligible:
        z=item['z'];plane=planes.get(z);path=inside(a.bundle,plane['image'] if plane else b['field_image'])
        if plane and digest(path)!=plane['sha256']:raise ValueError('Focus image hash mismatch')
        with Image.open(path) as im:source=im.convert('RGB')
        if source.size!=(size,size):raise ValueError('Unexpected plane dimensions')
        array=cv2.cvtColor(np.asarray(source),cv2.COLOR_RGB2BGR)
        negatives=[other for other in eligible if item['overlap_group'] and other['overlap_group']==item['overlap_group']
                   and other['z']==z and other['id']!=item['id']]
        if any(other['x']==item['x'] and other['y']==item['y'] for other in negatives):
            raise ValueError('Conflicting positive and negative points')
        variants=[('positive',[],False)]+([('group_contrast',negatives,False)] if negatives else [])
        candidate_box=None
        if a.candidate_boxes:
            compatible=[]
            for c in boxes:
                box=c['box']
                if (not isinstance(box,list) or len(box)!=4 or any(not isinstance(v,(int,float)) or not math.isfinite(v) for v in box)
                    or box[0]>=box[2] or box[1]>=box[3]):raise ValueError('Invalid detector box')
                if c['z']==z and box[0]<=item['x']<box[2] and box[1]<=item['y']<box[3]:compatible.append(c)
            if compatible:
                candidate_box=min(compatible,key=lambda c:((c['box'][2]-c['box'][0])*(c['box'][3]-c['box'][1]),c['id']))
                variants.append(('candidate_box',[],False))
                x0,y0,x1,y1=candidate_box['box'];box_negatives=[n for n in negatives if x0<=n['x']<x1 and y0<=n['y']<y1]
                if box_negatives:variants.append(('candidate_box_group_contrast',box_negatives,False))
        if a.local_radius is not None:
            variants.append(('local_positive',[],True))
            if negatives:variants.append(('local_group_contrast',negatives,True))
        row={**item,'source_field_sha256':digest(path),'variants':[]}
        for name,other,local in variants:
            if local:
                radius=a.local_radius;cx=math.floor(item['x']);cy=math.floor(item['y'])
                left,top=max(0,cx-radius),max(0,cy-radius)
                right,bottom=min(size,cx+radius+1),min(size,cy+radius+1)
                other=[x for x in other if left<=x['x']<right and top<=x['y']<bottom]
            else:left,top,right,bottom=0,0,size,size
            if name=='local_group_contrast' and not other:continue
            points=[[item['x'],item['y']]]+[[x['x'],x['y']] for x in other];labels=[1]+[0]*len(other)
            model_points=[[x-left,y-top] for x,y in points]
            prompted_box=candidate_box if name.startswith('candidate_box') else None
            kwargs={'bboxes':prompted_box['box']} if prompted_box else {}
            result=model.predict(array[top:bottom,left:right],points=[model_points],labels=[labels],imgsz=768,device='cpu',retina_masks=True,verbose=False,**kwargs)[0]
            entry={'name':name,'positive_point':points[0],'negative_points':points[1:],'negative_mark_ids':[x['id'] for x in other],
                   'candidate_box':prompted_box,
                   'inference_bbox_xyxy':[left,top,right,bottom],
                   'mask':None,'mask_sha256':None,'overlay':None,'mask_pixels':None,'contains_positive':None,'contains_negative':None,
                   'touches_inference_edge':None}
            if result.masks is not None and len(result.masks.data)==1:
                predicted=result.masks.data[0].cpu().numpy().astype(bool)
                if predicted.shape!=(bottom-top,right-left):raise ValueError('Unexpected mask shape')
                mask=np.zeros((size,size),dtype=bool);mask[top:bottom,left:right]=predicted
                mask_file=f'{item["id"]}-{name}-mask.png';overlay_file=f'{item["id"]}-{name}-overlay.png'
                Image.fromarray(mask.astype('uint8')*255).save(a.output/mask_file)
                display=np.asarray(source).copy();display[mask]=(.6*display[mask]+.4*np.array([255,45,145])).astype('uint8')
                image=Image.fromarray(display);draw=ImageDraw.Draw(image)
                if local:draw.rectangle((left,top,right-1,bottom-1),outline='#00c9ff',width=2)
                if prompted_box:draw.rectangle(tuple(prompted_box['box']),outline='#00c9ff',width=2)
                if prompted_box:draw.rectangle(prompted_box['box'],outline='#00c9ff',width=2)
                for (x,y),label in zip(points,labels):
                    color='#00e888' if label else '#ffcf00';draw.ellipse((x-5,y-5,x+5,y+5),outline=color,width=3)
                image.save(a.output/overlay_file)
                entry.update(mask=mask_file,mask_sha256=digest(a.output/mask_file),overlay=overlay_file,mask_pixels=int(mask.sum()),
                    contains_positive=bool(mask[int(item['y']),int(item['x'])]),
                    contains_negative=[bool(mask[int(x['y']),int(x['x'])]) for x in other],
                    touches_inference_edge=bool(predicted[0,:].any() or predicted[-1,:].any()
                                                or predicted[:,0].any() or predicted[:,-1].any()))
            row['variants'].append(entry)
        records.append(row);print(item['id'],len(variants),'mask proposals',flush=True)
    result={'format':'diatom-point-mask-proposals-v1','bundle_id':b['bundle_id'],'review_sha256':digest(a.review),
            'candidate_box_sources_sha256':box_sources,
            'segmenter_sha256':digest(a.segmenter),'warning':'Unverified proposals, not reviewed outlines or taxon labels.',
            'records':records}
    (a.output/'proposals.json').write_text(json.dumps(result,indent=2)+'\n')
    sections=[]
    for r in records:
        blocks=[]
        for v in r['variants']:
            title={'positive':'Full field · point only','group_contrast':'Full field · point with same-group negatives',
                   'local_positive':'Local crop · point only','local_group_contrast':'Local crop · point with same-group negatives',
                   'candidate_box':'Detector box and point','candidate_box_group_contrast':'Detector box, point and same-group negatives'}[v['name']]
            if v['overlay']:
                img=f'<a href="{html.escape(v["overlay"],quote=True)}"><img src="{html.escape(v["overlay"],quote=True)}" alt="{title} mask overlay"></a>'
                status=f"{v['mask_pixels']} mask pixels; contains positive: {v['contains_positive']}; contains negatives: {v['contains_negative']}; touches inference edge: {v['touches_inference_edge']}"
            else:img='';status='No single mask returned.'
            blocks.append(f'<div><h3>{title}</h3>{img}<p>{html.escape(status)}</p></div>')
        sections.append(f'<section><h2>{html.escape(r["id"])} · Z {r["z"]}</h2><div class="variants">{"".join(blocks)}</div><div class="mask-review" data-id="{html.escape(r["id"],quote=True)}"></div></section>')
    page='''<!doctype html><html lang="en"><meta charset="utf-8"><meta name="viewport" content="width=device-width"><title>Manual point mask proposals</title><style>body{font:16px/1.5 system-ui;margin:2em;color:#1c3835}section{border-top:1px solid #aac;padding:1em 0}.variants{display:flex;flex-wrap:wrap;gap:1em}.variants>div{max-width:48%}img{width:100%;height:auto}label{display:block;margin:.7em 0}@media(max-width:700px){.variants>div{max-width:100%}}</style><h1>Manual point mask proposals</h1><p>Pink shows the proposed mask, green marks the target point, and yellow marks same-group negative points. Blue outlines the local inference area or detector prompt box. Detector boxes are the smallest same-plane boxes containing the point and may merge or truncate specimens. Masks touching an inference edge may be cut off; even masks that do not touch an edge may be wrong. These are unverified suggestions, not specimen boundaries or taxon identifications.</p><p><a href="proposals.json">Proposal data and provenance</a></p><label>Mask reviewer ID <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 mask choices</button> <button id="open-choices" disabled>Open saved mask choices</button><input id="choice-file" type="file" accept=".json,application/json" hidden> <span id="status" role="status">Loading…</span><p>Choices remain in this browser until downloaded. Selecting a model mask does not make it a reviewer-drawn outline or an adjudicated label.</p>'''+''.join(sections)
    js='''<script>"use strict";const sourceHash=SOURCE_HASH,expected=EXPECTED_SOURCE,key='diatom-point-mask-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 your choices.'}}async function init(){try{const r=await fetch('proposals.json',{cache:'no-store'});if(!r.ok)throw Error('HTTP '+r.status);source=await r.json();if(JSON.stringify(source)!==JSON.stringify(expected))throw Error('Proposal file changed; regenerate the page');try{state=JSON.parse(localStorage.getItem(key))}catch(e){}if(!state||!state.choices)state={reviewer:'',role:'unknown',choices:{}};$('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('.mask-review')){const id=container.dataset.id,record=source.records.find(r=>r.id===id);if(!record)throw Error('Missing point');const choice=state.choices[id]||{variant:'',note:''};state.choices[id]=choice;const label=document.createElement('label');label.textContent='Preferred model mask (optional) ';const select=document.createElement('select');for(const v of [{name:'',title:'None / not chosen'},...record.variants.filter(x=>x.mask).map(x=>({name:x.name,title:x.name}))]){const opt=document.createElement('option');opt.value=v.name;opt.textContent=v.title;select.append(opt)}select.value=choice.variant;select.onchange=()=>{choice.variant=select.value;save()};label.append(select);const nl=document.createElement('label');nl.textContent='Notes ';const note=document.createElement('textarea');note.value=choice.note||'';note.oninput=()=>{choice.note=note.value;save()};nl.append(note);container.append(label,nl)}$('download').disabled=false;$('open-choices').disabled=false;$('status').textContent='Ready.'}catch(e){$('status').textContent='Could not load choices: '+e.message}}$('download').onclick=()=>{const result={format:'diatom-point-mask-choices-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-point-mask-choices.json';a.click();setTimeout(()=>URL.revokeObjectURL(url),1000)};function validateSavedChoices(file){if(!file||file.format!=='diatom-point-mask-choices-v1'||file.source_sha256!==sourceHash||JSON.stringify(file.source)!==JSON.stringify(source))throw Error('Saved choices do not match these mask proposals');const r=file.review;if(!r||typeof r.reviewer!=='string'||!['unknown','nonexpert','expert'].includes(r.role)||!r.choices||typeof r.choices!=='object'||Array.isArray(r.choices))throw Error('Invalid reviewer or choices');for(const [id,c] of Object.entries(r.choices)){const record=source.records.find(x=>x.id===id);if(!record||!c||typeof c.variant!=='string'||typeof c.note!=='string'||(c.variant&&!record.variants.some(v=>v.name===c.variant&&v.mask)))throw Error('Invalid mask choice for '+id)}return r}$('open-choices').onclick=()=>$('choice-file').click();$('choice-file').onchange=async e=>{const file=e.target.files[0];e.target.value='';if(!file)return;try{const loaded=validateSavedChoices(JSON.parse(await file.text()));if(!confirm('Replace this browser’s mask choices? Download the current choices first if you want to keep them.'))return;localStorage.setItem(key,JSON.stringify(loaded));location.reload()}catch(err){$('status').textContent='Choices not opened: '+err.message}};init();</script></html>'''
    expected=json.dumps(result,ensure_ascii=True,separators=(',',':')).replace('</','<\\/')
    (a.output/'index.html').write_text(page+js.replace('SOURCE_HASH',json.dumps(digest(a.output/'proposals.json'))).replace('EXPECTED_SOURCE',expected))


if __name__=='__main__':main()
