"""Local beam-boundary diagnostics independent of the frozen transfer algorithm.

These are conservative review gates, not segmentation accuracy estimates. The
reference is a proposal's affine initialization, never a ground-truth contour.
"""
from __future__ import annotations

import cv2
import numpy as np

from .mask_template_transfer import patch_matrix,transform
from .pose_review_geometry import polygon_value

VERSION='local_beam_boundary_guard_v1'


def affine_reference(proposal,template):
    p=transform(template['polygon'],patch_matrix(template['row']))
    p=transform(p,proposal['metrics']['affine_patch_transform'])
    return transform(p,cv2.invertAffineTransform(patch_matrix(proposal['source'])))


def cross(a,b):return a[0]*b[1]-a[1]*b[0]


def ray_intersections(origin,direction,polygon):
    result=[]
    for a,b in zip(polygon,np.roll(polygon,-1,axis=0)):
        edge=b-a;den=cross(direction,edge)
        if abs(den)<1e-9:continue
        s=cross(a-origin,edge)/den;t=cross(a-origin,direction)/den
        if -1e-7<=t<=1+1e-7:result.append(float(s))
    return sorted(result)


def sample(image,points):
    """Bilinear grayscale samples in editor pixel-edge coordinates."""
    p=np.asarray(points,np.float32)
    return cv2.remap(image.astype(np.float32),p[...,0]-.5,p[...,1]-.5,cv2.INTER_LINEAR,
        borderMode=cv2.BORDER_REPLICATE)


def beam_boundary_audit(image,polygon,reference):
    p,ref=np.asarray(polygon,float),np.asarray(reference,float)
    if len(p)!=len(ref) or len(p)<4:raise ValueError('Mismatched boundary topology')
    v=ref[1]-ref[0];n=np.array([-v[1],v[0]])/np.linalg.norm(v)
    area=sum(cross(a,b) for a,b in zip(ref,np.roll(ref,-1,axis=0)))
    if area<0:n=-n
    records=[]
    for t in np.linspace(.15,.85,29):
        o=ref[0]+t*v
        before=ray_intersections(o,n,ref);after=ray_intersections(o,n,p)
        positives=[s for s in before if s>1e-5]
        if not positives or len(after)<2:continue
        thickness=min(positives);top=after[0];bottom=after[1]
        if thickness<1 or thickness>np.linalg.norm(v)*.4:continue
        # Is bright observed material above the candidate boundary being left
        # out? Only use an inset strip away from the noisy physical outer edge.
        excluded=max(0.,top-.5)
        if excluded>.5:
            coords=o+np.linspace(.5,max(.5,top-.25),12)[:,None]*n
            strip=sample(image,coords.reshape(1,-1,2)).ravel()
            inside=sample(image,(o+np.linspace(top+.5,min(bottom-.25,top+2.5),12)[:,None]*n).reshape(1,-1,2)).ravel()
            bright_excluded=float(np.mean(strip>=.75*max(float(np.median(inside)),1.)))
        else:bright_excluded=0.
        records.append(dict(fraction=float(t),reference_thickness_pixels=thickness,
            top_inward_pixels=top,thickness_ratio=(bottom-top)/thickness,
            excluded_bright_strip_fraction=bright_excluded))
    if len(records)<10:
        return dict(version=VERSION,state='not_applicable',reason='insufficient_unoccluded_beam_sections',sections=records)
    inward=np.array([r['top_inward_pixels'] for r in records]);ratios=np.array([r['thickness_ratio'] for r in records])
    relative=np.array([max(r['top_inward_pixels'],0)/r['reference_thickness_pixels'] for r in records])
    bright=np.array([r['excluded_bright_strip_fraction'] for r in records])
    flags=[]
    if np.quantile(relative,.9)>.25 and np.quantile(inward,.9)>1.25:flags.append('top_edge_inward_drift')
    if np.quantile(ratios,.1)<.7:flags.append('local_beam_thickness_collapse')
    if np.mean((inward>1.)&(bright>.65))>.25:flags.append('observed_bright_material_excluded_above_top')
    return dict(version=VERSION,state='review_required' if flags else 'passed',flags=flags,
        inward_p90_native_pixels=float(np.quantile(inward,.9)),inward_fraction_p90=float(np.quantile(relative,.9)),
        thickness_ratio_p10=float(np.quantile(ratios,.1)),bright_exclusion_sections_fraction=float(np.mean((inward>1.)&(bright>.65))),
        sections=records,reference_is_not_GT=True,metrics_are_not_accuracy_probabilities=True)


def image_corner_fit(image,polygon,reference,size):
    """Fit the observed beam upper edge and right edge near an affine seed.

    Scope is an explicit reviewed eight-vertex beam contour. Only vertex 2 is
    changed. A bounded intensity transition fit gives a reproducible proposal;
    it is not an automatic human confirmation.
    """
    p,ref=np.asarray(polygon,float),np.asarray(reference,float)
    if len(p)!=8:raise ValueError('Corner repair requires the reviewed 8-vertex topology')
    edge=ref[1]-ref[0]
    if edge[0]<20 or abs(edge[1]/edge[0])>.4:raise ValueError('Unsupported beam orientation')
    xs=np.arange(np.ceil(ref[0,0]+.18*edge[0]),np.floor(ref[0,0]+.85*edge[0]))+.5
    slope=edge[1]/edge[0];top=[]
    for x in xs:
        y=ref[0,1]+(x-ref[0,0])*slope
        ys=np.arange(y-4,y+4.01,.125)
        values=sample(image,np.stack((np.full_like(ys,x),ys),axis=-1).reshape(1,-1,2)).ravel()
        peak=float(np.quantile(values,.9));threshold=.7*peak
        crossings=np.flatnonzero((values[:-1]<threshold)&(values[1:]>=threshold))
        if peak<100 or not len(crossings):continue
        options=[]
        for j in crossings:
            crossing=ys[j]+(threshold-values[j])/(values[j+1]-values[j])*(ys[j+1]-ys[j])
            sustained=sample(image,np.array([[[x,crossing+.5],[x,crossing+1.5]]])).ravel()
            if np.min(sustained)>=threshold:options.append(crossing)
        if options:top.append([x,min(options,key=lambda yy:abs(yy-y))])
    if len(top)<25:raise ValueError('Upper beam edge has insufficient observed support')
    top=np.array(top);fit=cv2.fitLine(top.astype(np.float32),cv2.DIST_HUBER,0,.001,.001).ravel()
    m=float(fit[1]/fit[0]);b=float(fit[3]-m*fit[2]);residual=top[:,1]-(m*top[:,0]+b)
    if np.quantile(abs(residual),.9)>1.25:raise ValueError('Ambiguous upper beam edge')
    # Strong observed right-hand exit, below the upper corner and above the
    # blurred foot/floor. Fit x(y); no coordinates are supplied by a raw bbox.
    right=[]
    # Fit only the upper 40% adjacent to this corner. The lower leg can bend or
    # merge into floor/background returns; extrapolating it biases the corner.
    for y in np.arange(ref[1,1]+2,ref[1,1]+.4*(ref[2,1]-ref[1,1]),.5):
        x=ref[1,0]+(ref[2,0]-ref[1,0])*(y-ref[1,1])/(ref[2,1]-ref[1,1])
        xx=np.arange(x-3,x+3.01,.125)
        values=sample(image,np.stack((xx,np.full_like(xx,y)),axis=-1).reshape(1,-1,2)).ravel()
        peak=float(np.quantile(values,.75));threshold=.5*peak
        exits=np.flatnonzero((values[:-1]>=threshold)&(values[1:]<threshold))
        if peak<100 or not len(exits):continue
        j=min(exits,key=lambda j:abs(xx[j]-x))
        crossing=xx[j]+(threshold-values[j])/(values[j+1]-values[j])*(xx[j+1]-xx[j])
        right.append([crossing,y])
    if len(right)<10:raise ValueError('Right beam edge has insufficient observed support')
    right=np.array(right);rfit=cv2.fitLine(right[:,::-1].astype(np.float32),cv2.DIST_HUBER,0,.001,.001).ravel()
    a=float(rfit[1]/rfit[0]);c=float(rfit[3]-a*rfit[2])
    right_residual=right[:,0]-(a*right[:,1]+c)
    if np.quantile(abs(right_residual),.9)>.5:raise ValueError('Ambiguous right beam edge')
    x=(a*b+c)/(1-a*m);y=m*x+b
    if abs(x-ref[1,0])>2 or abs(y-ref[1,1])>2:raise ValueError('Observed corner too far from affine reference')
    new=p.copy();new[1]=[x,y];polygon_value(new.tolist(),*size)
    return new.tolist(),dict(method='observed_upper_and_right_edge_robust_intersection_v1',
        changed_vertex_1based=2,old_vertex=p[1].tolist(),new_vertex=new[1].tolist(),
        upper_line_y_from_x=[m,b],right_line_x_from_y=[a,c],upper_support_points=top.tolist(),
        right_support_points=right.tolist(),upper_residual_p90_pixels=float(np.quantile(abs(residual),.9)),
        right_residual_p90_pixels=float(np.quantile(abs(right_residual),.9)),
        affine_seed=ref[1].tolist(),human_confirmation_inferred=False)
