"""Apply a previously selected threshold to the L22 partial-query experiment."""
import json
import statistics
from collections import Counter
from pathlib import Path

from PIL import Image,ImageDraw,ImageFont

ROOT=Path(__file__).resolve().parent.parent
src=json.loads((ROOT/'results/l22/partial-retrieval.json').read_text())
folds=json.loads((ROOT/'results/r14/unknown-genus-results.json').read_text())['folds']
threshold=statistics.median(f['threshold'] for f in folds)
records=[]
for row in src['records']:
    out={'query_id':row['query']['annotation_id'],'reference_genus':row['query']['genus']}
    for kind in ('full','half_a','half_b'):
        candidate=row[kind];accepted=candidate['score']>=threshold;correct=candidate['genus']==row['query']['genus']
        out[kind]={'score':candidate['score'],'suggested_genus':candidate['genus'],'accepted':accepted,'matches_public_genus':correct,
                   'outcome':'accepted_match' if accepted and correct else 'accepted_mismatch' if accepted else 'abstained'}
    records.append(out)
summary={}
for kind in ('full','half_a','half_b'):
    counts=Counter(r[kind]['outcome'] for r in records)
    summary[kind]={name:counts[name] for name in ('accepted_match','accepted_mismatch','abstained')}
OUT=ROOT/'results/r23';OUT.mkdir(exist_ok=True)
(OUT/'partial-abstention.json').write_text(json.dumps({'threshold':threshold,'threshold_source':'median of prior R14 calibration folds on different source slides',
 'warning':'Threshold not calibrated for this gallery or artificial partials; all 42 queries are from one nonrandom slide.',
 'summary':summary,'records':records},indent=2))
font=ImageFont.truetype('DejaVuSans.ttf',19);small=ImageFont.truetype('DejaVuSans.ttf',16)
im=Image.new('RGB',(1150,380),'#f8f8f2');d=ImageDraw.Draw(im)
colors={'accepted_match':'#18856c','accepted_mismatch':'#bb5960','abstained':'#c9d5cc'}
for j,(key,label) in enumerate((('full','Complete'),('half_a','Half A'),('half_b','Half B'))):
    y=75+j*95;d.text((20,y+17),label,font=font,fill='#193b36');x=220
    for outcome in ('accepted_match','accepted_mismatch','abstained'):
        count=summary[key][outcome];w=850*count/len(records)
        d.rectangle((x,y,x+w,y+50),fill=colors[outcome]);
        if w>35:d.text((x+w/2-8,y+14),str(count),font=small,fill='#ffffff' if outcome!='abstained' else '#193b36')
        x+=w
for j,(key,label) in enumerate((('accepted_match','Accepted, matching genus'),('accepted_mismatch','Accepted, different genus'),('abstained','Abstained'))):
    x=180+j*310;d.rectangle((x,6,x+16,22),fill=colors[key]);d.text((x+23,3),label,font=small,fill='#193b36')
im.save(OUT/'partial-abstention.png')
print('threshold',round(threshold,6),'queries',len(records))
for name,counts in summary.items():print(name,counts)
