"""Compare grid and split-grid proposal matching at fixed confidence-ranked budgets."""
import itertools
import json
import sys
from pathlib import Path

import numpy as np
from PIL import Image,ImageDraw,ImageFont

ROOT=Path(__file__).resolve().parent.parent
sys.path.insert(0,str(ROOT/'research'))
from r18_pair_data import load_pair

selected=json.loads((ROOT/'results/r18/selection.json').read_text())['selected_pairs']
grid=json.loads((ROOT/'results/l19/grid-proposals.json').read_text())['records']
split=json.loads((ROOT/'results/l20/split-grid.json').read_text())['records']
budgets=[5,10,20,40,None]
comparisons=[]
for i,row in enumerate(selected,1):
    image,refs,path=load_pair(i,row)
    case={'image_file':row['image']['file_name'],'methods':{}}
    for name,base,entries in [('grid',ROOT/'results/l19',grid[i-1]['candidates']),('split',ROOT/'results/l20',split[i-1]['candidates'])]:
        ordered=sorted(enumerate(entries),key=lambda pair:(-pair[1]['score'],pair[0]))
        masks=[np.asarray(Image.open(base/e['mask_file']).convert('L'))>0 for _,e in ordered]
        scores=[]
        for ref in refs:
            scores.append([float(np.logical_and(ref,m).sum()/np.logical_or(ref,m).sum()) for m in masks])
        out=[]
        for budget in budgets:
            n=min(budget or len(masks),len(masks));choices=[None]+list(range(n));valid=[]
            for a,b in itertools.product(choices,repeat=2):
                if a is not None and b is not None and a==b:continue
                if a is not None and scores[0][a]<.5:continue
                if b is not None and scores[1][b]<.5:continue
                rank=((a is not None)+(b is not None),(scores[0][a] if a is not None else 0)+(scores[1][b] if b is not None else 0))
                valid.append((rank,(a,b)))
            best=max(valid,key=lambda x:x[0])
            out.append({'budget':budget,'candidates_inspected':n,'matched_targets':best[0][0],
                        'matched_rank_indices':[None if v is None else v+1 for v in best[1]]})
        case['methods'][name]=out
    comparisons.append(case)

summaries={}
for name in ('grid','split'):
    summaries[name]=[{'budget':budget,'target_matches':sum(case['methods'][name][i]['matched_targets'] for case in comparisons),
                       'complete_pairs':sum(case['methods'][name][i]['matched_targets']==2 for case in comparisons)}
                      for i,budget in enumerate(budgets)]
out=ROOT/'results/r19';out.mkdir(exist_ok=True)
(out/'candidate-budget.json').write_text(json.dumps({'description':'posthoc reference matching in three selected public pairs; not a practical reviewer simulation',
 'budgets':budgets,'summaries':summaries,'cases':comparisons},indent=2))
font=ImageFont.truetype('DejaVuSans.ttf',19);small=ImageFont.truetype('DejaVuSans.ttf',15)
plot=Image.new('RGB',(1200,620),'#f8f8f2');d=ImageDraw.Draw(plot)
labels=['5','10','20','40','All'];colors={'grid':'#007d68','split':'#b44c79'}
for panel,(metric,maxy,title) in enumerate([('target_matches',6,'Matched annotated targets (out of 6)'),('complete_pairs',3,'Pairs with both targets matched (out of 3)')]):
    x0=80+panel*580;y0=115;w=480;h=400
    d.text((x0-5,40),title,font=font,fill='#193b36')
    for tick in range(maxy+1):
        y=y0+h-h*tick/maxy;d.line((x0,y,x0+w,y),fill='#d4ddd5',width=1);d.text((x0-25,y-9),str(tick),font=small,fill='#526a63')
    for j,label in enumerate(labels):
        x=x0+j*w/4;d.text((x-10,y0+h+12),label,font=small,fill='#526a63')
    for name in ('grid','split'):
        # Small horizontal offsets reveal coincident results.
        off=-5 if name=='grid' else 5
        pts=[(x0+j*w/4+off,y0+h-h*s[metric]/maxy) for j,s in enumerate(summaries[name])]
        d.line(pts,fill=colors[name],width=3)
        for x,y in pts:d.ellipse((x-5,y-5,x+5,y+5),fill=colors[name])
    d.text((x0+80,570),'Maximum candidates per image, ordered by model score',font=small,fill='#526a63')
d.text((400,5),'Grid only',font=small,fill=colors['grid']);d.text((540,5),'Grid + automatic split',font=small,fill=colors['split'])
plot.save(out/'candidate-budget.png')
for n in ('grid','split'):print(n,[(x['budget'],x['target_matches'],x['complete_pairs']) for x in summaries[n]])
