"""Audit competing cross-plane box links without forcing a track assignment."""
import collections
import json
import sys
from pathlib import Path

from PIL import Image, ImageDraw, ImageFont

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

rows = json.loads((ROOT/'results/r5/planes.json').read_text())
records = []
for field in rows:
    nodes = [{'id': f"{p['z']}:{i}", 'z': p['z'], 'box': b, 'confidence': c}
             for p in field['planes'] for i,(b,c) in enumerate(zip(p['boxes'],p['confidences']))]
    configurations = []
    for threshold in (.1,.5):
        edges = []
        for a in nodes:
            for b in nodes:
                if not 0 < b['z'] - a['z'] <= 3:
                    continue
                overlap = iou(a['box'], b['box'])
                if overlap >= threshold:
                    edges.append({'from': a['id'], 'to': b['id'], 'from_z': a['z'], 'to_z': b['z'], 'box_iou': overlap})
        forward = collections.Counter((e['from'],e['to_z']) for e in edges)
        backward = collections.Counter((e['to'],e['from_z']) for e in edges)
        configurations.append({'iou_threshold': threshold, 'edge_count': len(edges),
            'forward_same_plane_choice_groups': sum(n>1 for n in forward.values()),
            'backward_same_plane_choice_groups': sum(n>1 for n in backward.values()), 'edges': edges})
    records.append({'slide':field['slide'], 'field':field['field'], 'nodes':nodes, 'configurations':configurations})
totals = []
for i, threshold in enumerate((.1,.5)):
    configs = [r['configurations'][i] for r in records]
    totals.append({'iou_threshold': threshold, 'edges':sum(x['edge_count'] for x in configs),
        'forward_same_plane_choice_groups':sum(x['forward_same_plane_choice_groups'] for x in configs),
        'backward_same_plane_choice_groups':sum(x['backward_same_plane_choice_groups'] for x in configs)})
out = ROOT/'results/l27'; out.mkdir(parents=True,exist_ok=True)
(out/'ambiguity-graph.json').write_text(json.dumps({'max_z_index_gap':3,'fields':records,'totals':totals},indent=2)+'\n')
img=Image.new('RGB',(1000,340),'#f8f8f2');d=ImageDraw.Draw(img)
font=ImageFont.truetype('DejaVuSans.ttf',22);small=ImageFont.truetype('DejaVuSans.ttf',17)
for i, total in enumerate(totals):
    x=40+i*490; d.rounded_rectangle((x,25,x+440,300),radius=12,fill='#e2eee6')
    d.text((x+20,45),f"Box IoU >= {total['iou_threshold']:.1f}",font=font,fill='#193b36')
    d.text((x+20,100),f"{total['edges']} possible links",font=font,fill='#193b36')
    d.text((x+20,155),f"{total['forward_same_plane_choice_groups']} forward choice groups",font=small,fill='#193b36')
    d.text((x+20,195),f"{total['backward_same_plane_choice_groups']} backward choice groups",font=small,fill='#193b36')
    d.text((x+20,250),'Each group concerns one plane.',font=small,fill='#526c65')
img.save(out/'choice-summary.png')
print(json.dumps(totals,indent=2))
