"""Audit filename-level train/test overlap and coarse naming-group overlap."""
import json
import re
from collections import Counter
from pathlib import Path

from PIL import Image,ImageDraw,ImageFont

ROOT=Path(__file__).resolve().parent.parent
SOURCE=Path('/tmp/diatom-mask-coco')
OUT=ROOT/'results/r20';OUT.mkdir(exist_ok=True)
specs=[('Gomphonema','Gomphonema_train_160_coco.json','Gomphonema_test_53_coco.json'),
       ('Pinnularia','Pinnularia_train_100_coco.json','pinnularia_test_33_coco.json')]
def group(name):
    # Conservative filename-family heuristic, not a biological sample ID.
    return re.sub(r'(?:_|\s)\d+(?:_\d+)?$','',Path(name).stem,flags=re.I)
records=[]
for genus,trainfile,testfile in specs:
    train=json.loads((SOURCE/trainfile).read_text());test=json.loads((SOURCE/testfile).read_text())
    train_names={r['file_name'] for r in train['images']};test_names={r['file_name'] for r in test['images']}
    train_groups=Counter(group(n) for n in train_names);test_groups=Counter(group(n) for n in test_names)
    shared_groups=sorted(set(train_groups)&set(test_groups))
    records.append({'genus':genus,'train_file':trainfile,'test_file':testfile,'train_images':len(train_names),'test_images':len(test_names),
                    'exact_filename_overlap':sorted(train_names&test_names),'train_family_count':len(train_groups),
                    'test_family_count':len(test_groups),'shared_families':shared_groups,
                    'train_images_in_shared_families':sum(train_groups[g] for g in shared_groups),
                    'test_images_in_shared_families':sum(test_groups[g] for g in shared_groups),
                    'train_family_counts':dict(sorted(train_groups.items())),'test_family_counts':dict(sorted(test_groups.items()))})
    print(genus,'images',len(train_names),len(test_names),'exact shared',len(train_names&test_names),
          'heuristic shared families',len(shared_groups),'test images in these families',sum(test_groups[g] for g in shared_groups))
(OUT/'training-preflight.json').write_text(json.dumps({'warning':'Filename families are heuristic and are not verified specimen or sample identifiers. Comparison of two largest named variants per genus only.',
 'records':records},indent=2))
font=ImageFont.truetype('DejaVuSans.ttf',22);small=ImageFont.truetype('DejaVuSans.ttf',17)
im=Image.new('RGB',(1100,420),'#f8f8f2');d=ImageDraw.Draw(im)
for i,r in enumerate(records):
    y=30+i*190
    d.text((25,y),r['genus']+' test images',font=font,fill='#193b36')
    x=300;w=700;shared=r['test_images_in_shared_families'];total=r['test_images']
    d.rectangle((x,y+40,x+w,y+90),fill='#d6e5d9')
    d.rectangle((x,y+40,x+w*shared/total,y+90),fill='#b97546')
    d.text((x,y+105),f"{shared} of {total} test filenames share a heuristic name family with training",font=small,fill='#193b36')
    d.text((x,y+130),f"Exact train/test filename matches: {len(r['exact_filename_overlap'])}",font=small,fill='#193b36')
im.save(OUT/'training-preflight.png')
