"""Shared six-image polygon inputs for conditional model comparisons."""
import json
from pathlib import Path

import cv2
import numpy as np
from PIL import Image

ROOT=Path(__file__).resolve().parent.parent

def load_case(index,entry):
    annotation=json.loads((Path('/tmp/diatom-mask-coco')/entry['annotation_file']).read_text())
    annotations=[a for a in annotation['annotations'] if a['image_id']==entry['image']['id']]
    if len(annotations)!=1:raise ValueError('Expected one selected annotation per image')
    path=Path('/tmp/diatom-mask-images')/f'{index:02d}.jpg'
    image=np.asarray(Image.open(path).convert('RGB'));h,w=image.shape[:2]
    if (w,h)!=(entry['image']['width'],entry['image']['height']):raise ValueError('Image dimensions disagree')
    scale=768/max(w,h);W,H=round(w*scale),round(h*scale)
    image=cv2.resize(image,(W,H),interpolation=cv2.INTER_AREA)
    ref=np.zeros((H,W),dtype=np.uint8)
    for polygon in annotations[0]['segmentation']:
        xy=np.asarray(polygon,dtype=np.float32).reshape(-1,2);xy[:,0]*=W/w;xy[:,1]*=H/h
        cv2.fillPoly(ref,[np.rint(xy).astype(np.int32)],1)
    if not ref.any():raise ValueError('Empty annotation polygon')
    return image,ref,path
