"""Visualize provisional practice marks against review-bundle proposals."""
import argparse
import html
import json
from pathlib import Path

from PIL import Image,ImageDraw
from ingest_review import digest,inside


def matching(edges):
    """One-to-one maximum matching of mark indices to proposal indices."""
    owners={}
    def assign(i,seen):
        for j in edges[i]:
            if j in seen:continue
            seen.add(j)
            if j not in owners or assign(owners[j],seen):owners[j]=i;return True
        return False
    for i in sorted(range(len(edges)),key=lambda x:len(edges[x])):assign(i,set())
    return sorted((i,j) for j,i in owners.items())


def box_on_plane(candidate,z,model_z):
    if candidate.get('source')=='stack_track':
        observations=[o for o in candidate.get('observations',[]) if o.get('z')==z]
        if len(observations)>1:raise ValueError('Multiple track observations on one plane')
        return observations[0]['box'] if observations else None
    return candidate['box'] if candidate.get('plane_z',model_z)==z else None


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);a=p.parse_args()
    jobs=json.loads(a.jobs.read_text())['fields']
    if a.output.exists() and any(a.output.iterdir()):raise FileExistsError('Output directory must be empty')
    a.output.mkdir(parents=True,exist_ok=True);records=[];sections=[]
    for job in jobs:
        field=a.batch/job['id'];b=json.loads((field/'bundle.json').read_text())
        review_path=a.batch/(job['id']+'-practice-review.json');review=json.loads(review_path.read_text())
        if review.get('bundle')!=b or review.get('review',{}).get('context',{}).get('practice_source_status')!='provisional':raise ValueError('Practice review mismatch')
        marks=[m for m in review['review']['manual'] if m.get('decision')=='possible']
        if any(m.get('z')!=b['z'] for m in marks):raise ValueError('This diagnostic requires marks on the model plane')
        stack=json.loads((field/'stack-proposals.json').read_text())
        if stack.get('bundle_id')!=b['bundle_id']:raise ValueError('Stack mismatch')
        original=b['candidates'];tracks=stack['proposals'];pools=[('original',original),('stack',tracks),('pooled',original+tracks)]
        results={}
        for name,proposals in pools:
            box_edges=[];mask_edges=[]
            masks=[]
            for candidate in proposals:
                if candidate.get('mask'):
                    with Image.open(inside(field,candidate['mask'])) as im:
                        if im.size!=(b['size'],b['size']):raise ValueError('Unexpected mask dimensions')
                        masks.append(im.convert('L'))
                else:masks.append(None)
            for mark in marks:
                x,y,z=mark['x'],mark['y'],mark['z'];box_set=[];mask_set=[]
                for i,candidate in enumerate(proposals):
                    box=box_on_plane(candidate,z,b['z'])
                    if box is not None:
                        x0,y0,x1,y1=box
                        if x0<=x<x1 and y0<=y<y1:box_set.append(i)
                    if candidate.get('plane_z',b['z'])==z and masks[i] is not None and masks[i].getpixel((int(x),int(y)))>0:mask_set.append(i)
                box_edges.append(box_set);mask_edges.append(mask_set)
            results[name]={'proposals':len(proposals),'same_plane_boxes':sum(box_on_plane(c,b['z'],b['z']) is not None for c in proposals),
                           'same_plane_masks':sum(c.get('plane_z',b['z'])==b['z'] and m is not None for c,m in zip(proposals,masks)),
                           'box_matches':len(matching(box_edges)),'mask_matches':len(matching(mask_edges)),
                           'box_assignments':[{'mark':i+1,'candidate_id':proposals[j]['id']} for i,j in matching(box_edges)],
                           'mask_assignments':[{'mark':i+1,'candidate_id':proposals[j]['id']} for i,j in matching(mask_edges)]}
        with Image.open(inside(field,b['field_image'])) as im:display=im.convert('RGB')
        draw=ImageDraw.Draw(display)
        for c in original:
            draw.rectangle(c['box'],outline='#00dba2',width=3);draw.text((c['box'][0]+3,c['box'][1]+3),c['id'],fill='#00dba2')
        for c in tracks:
            box=box_on_plane(c,b['z'],b['z'])
            if box:
                draw.rectangle(box,outline='#ffaf00',width=2);draw.text((box[0]+3,box[1]+18),c['id'],fill='#ffaf00')
        for i,m in enumerate(marks,1):
            x,y=m['x'],m['y'];draw.ellipse((x-6,y-6,x+6,y+6),outline='#ffec00',width=3);draw.text((x+8,y-8),str(i),fill='#ffec00')
        image=f'{job["id"]}.png';display.save(a.output/image)
        records.append({'id':job['id'],'bundle_id':b['bundle_id'],'review_sha256':digest(review_path),'marked_points':len(marks),
                        'mark_z':b['z'],'results':results,'image':image})
        rows=''.join(f'<tr><td>{html.escape(name)}</td><td>{v["proposals"]}</td><td>{v["same_plane_boxes"]}</td><td>{v["same_plane_masks"]}</td><td>{v["box_matches"]}/{len(marks)}</td><td>{v["mask_matches"]}/{len(marks)}</td></tr>' for name,v in results.items())
        sections.append(f'<section><h2>{html.escape(job["id"])}</h2><img src="{image}" alt="Provisional marks and same-plane proposal boxes"><table><thead><tr><th>Proposals</th><th>Total</th><th>Boxes on plane</th><th>Masks on plane</th><th>Box matches</th><th>Mask matches</th></tr></thead><tbody>{rows}</tbody></table></section>')
    (a.output/'comparison.json').write_text(json.dumps({'format':'diatom-practice-coverage-v1','records':records},indent=2)+'\n')
    (a.output/'index.html').write_text('''<!doctype html><html lang="en"><meta charset="utf-8"><meta name="viewport" content="width=device-width"><title>Practice mark comparison</title><style>body{font:16px/1.5 system-ui;color:#1c3835;max-width:960px;margin:2em auto;padding:0 1em}img{max-width:100%}table{border-collapse:collapse}th,td{padding:.4em;border:1px solid #bbb}</style><h1>Practice marks and model proposals</h1><p>Yellow circles are provisional nonexpert marks. Green boxes are original detector candidates; orange boxes are track observations on the marked plane, regardless of their representative plane. A track mask exists only on its representative plane, so fewer masks than boxes may be comparable.</p><p>Each mark can match at most one proposal, and each proposal at most one mark. A box match contains the point; a mask match contains its pixel. These are location diagnostics, not recall or precision: the marks are incomplete and unverified, a box or mask can contain background, and pooled proposals may duplicate each other.</p><p><a href="comparison.json">Detailed assignments and provenance</a> · <a href="../index.html">Review fields</a></p>'''+''.join(sections)+'</html>')


if __name__=='__main__':main()
