"""Geometry comparisons against saved research annotations, never GT claims."""
from collections import Counter

import cv2
import numpy as np

from .pose_review_geometry import polygon_value,raster_mask


def compare_polygons(draft,reviewed,size,bbox_height):
    width,height=size
    draft=polygon_value(draft,width,height);reviewed=polygon_value(reviewed,width,height)
    a=raster_mask(draft,width,height);b=raster_mask(reviewed,width,height)
    if not a.any() or not b.any():raise ValueError('Raster-empty mask cannot be scored')
    kernel=np.ones((3,3),np.uint8)
    ae=a.astype(np.uint8)-cv2.erode(a.astype(np.uint8),kernel,borderType=cv2.BORDER_CONSTANT,borderValue=0)
    be=b.astype(np.uint8)-cv2.erode(b.astype(np.uint8),kernel,borderType=cv2.BORDER_CONSTANT,borderValue=0)
    da=cv2.distanceTransform(1-ae,cv2.DIST_L2,cv2.DIST_MASK_PRECISE)
    db=cv2.distanceTransform(1-be,cv2.DIST_L2,cv2.DIST_MASK_PRECISE)
    left,right=db[ae>0],da[be>0];distances=np.r_[left,right]
    precision,recall=float((left<=1).mean()),float((right<=1).mean())
    vertex=None
    if len(draft)==len(reviewed):
        p,q=np.asarray(draft),np.asarray(reviewed)
        vertex=min(float(np.linalg.norm(p-np.roll(v,i,axis=0),axis=1).mean())
            for v in (q,q[::-1]) for i in range(len(p)))
    return dict(iou=float((a&b).sum()/(a|b).sum()),assd_native_pixels=float(distances.mean()),
        hd95_native_pixels=float(np.quantile(distances,.95)),hd95_bbox_height_fraction=float(np.quantile(distances,.95)/max(bbox_height,1)),
        boundary_f1_1px=2*precision*recall/max(precision+recall,1e-12),reviewed_to_draft_area_ratio=float(b.sum()/a.sum()),
        mean_vertex_distance_native_pixels=vertex,vertex_count_changed=len(draft)!=len(reviewed),
        draft_vertex_count=len(draft),reviewed_vertex_count=len(reviewed),polygon_changed=draft!=reviewed,
        saved_annotation_is_research_reference_not_confirmed_GT=True)


def summarize(records):
    """An empty accepted set must never appear as perfect quality."""
    records=list(records);n=len(records)
    result=dict(count=n)
    for field in ('iou','assd_native_pixels','hd95_native_pixels','hd95_bbox_height_fraction','boundary_f1_1px','reviewed_to_draft_area_ratio'):
        values=[r[field] for r in records]
        result[field+'_median']=float(np.median(values)) if values else None
    result.update(iou_p10=float(np.quantile([r['iou'] for r in records],.1)) if n else None,
        iou_at_least_09=sum(r['iou']>=.9 for r in records),iou_below_08=sum(r['iou']<.8 for r in records),
        polygon_changed=sum(r['polygon_changed'] for r in records),vertex_count_changed=sum(r['vertex_count_changed'] for r in records))
    return result


def stratified(records,field):
    return {str(v):summarize(r for r in records if r[field]==v) for v in sorted({r[field] for r in records},key=str)}


def release_decision(records,total,minimum=10):
    """Predeclared pilot gate; coverage is reported even if every fit abstains."""
    records=list(records);summary=summarize(records);n=len(records)
    reasons=[]
    if n<minimum:reasons.append('insufficient_accepted_group_held_out_samples')
    if not n or summary['iou_median']<.95:reasons.append('median_iou_below_095')
    if not n or summary['iou_at_least_09']/n<.9:reasons.append('less_than_90pct_iou_at_least_09')
    if any(r['hd95_native_pixels']>max(2.,.1*r['bbox_height']) for r in records):reasons.append('boundary_error_above_native_or_relative_limit')
    return dict(state='passed' if not reasons else 'blocked',reasons=reasons,accepted=n,total=total,
        delivery_rate=n/total if total else 0.,quality=summary,production_publication_authorized=False,
        thresholds_are_predeclared_pilot_goals_not_accuracy_guarantees=True)
