"""Thin-beam clipping must not pass just because the full patch still correlates."""
import copy
import json
from pathlib import Path

import cv2
import numpy as np
import pytest

from pallet.mask_boundary_review import affine_reference,beam_boundary_audit,image_corner_fit


def synthetic():
    poly=[[20.,30.],[130.,20.],[132.,75.],[125.,76.],[124.,32.],[28.,42.],[28.,82.],[20.,83.]]
    image=np.full((100,160),20,np.uint8)
    cv2.fillPoly(image,[np.array(poly,np.int32)],230)
    return image,poly


def test_local_drift_and_thickness_collapse_detected_with_vertex_order_unchanged():
    im,ref=synthetic();bad=copy.deepcopy(ref);bad[1][0]+=1.;bad[1][1]+=5.
    result=beam_boundary_audit(im,bad,ref)
    assert result['state']=='review_required'
    assert 'top_edge_inward_drift' in result['flags']
    assert 'observed_bright_material_excluded_above_top' in result['flags']
    assert beam_boundary_audit(im,ref,ref)['state']=='passed'


def test_observed_corner_changes_only_vertex_two_not_other_geometry():
    im,ref=synthetic();bad=copy.deepcopy(ref);bad[1]=[131.,25.]
    fixed,evidence=image_corner_fit(im,bad,ref,[160,100])
    assert len(fixed)==8 and fixed[:1]+fixed[2:]==bad[:1]+bad[2:]
    np.testing.assert_allclose(fixed[1],ref[1],atol=1.25)
    assert not evidence['human_confirmation_inferred']
    assert beam_boundary_audit(im,fixed,ref)['state']=='passed'


def test_ambiguous_or_different_topology_is_not_fabricated():
    im,ref=synthetic()
    with pytest.raises(ValueError,match='8-vertex'):image_corner_fit(im,ref[:4],ref[:4],[160,100])
    with pytest.raises(ValueError,match='insufficient'):image_corner_fit(im*0,ref,ref,[160,100])


def test_reported_yellow_pallet_regression_and_same_template_review():
    root=Path(__file__).resolve().parents[1]/'outputs/pallet_mask_template_bulk_v2'
    if not root.exists():pytest.skip('Frozen real-image regression fixture unavailable')
    proposals=[json.loads(s) for s in (root/'proposals.jsonl').read_text().splitlines()]
    results={}
    for p in proposals:
        if p['template']['target_key']!='b62526c40d7f972094b41bdb':continue
        t=json.loads((root/'templates'/(p['template']['target_key']+'.json')).read_text())
        im=cv2.imread(str(root/'images'/(p['target_key']+'.png')),0);ref=affine_reference(p,t)
        old=copy.deepcopy(p['polygon']);results[p['target_key']]=beam_boundary_audit(im,old,ref)['state']
        if p['target_key']=='ecb32bf169bd814b13791e4d':
            fixed,evidence=image_corner_fit(im,old,ref,p['source']['size'])
            np.testing.assert_allclose(fixed[1],[259.98245,186.64089],atol=.005)
            assert fixed[:1]+fixed[2:]==old[:1]+old[2:]
            assert beam_boundary_audit(im,fixed,ref)['state']=='passed'
            assert abs(evidence['old_vertex'][1]-evidence['new_vertex'][1])>4.
    assert results=={'a2cbe35521d401dbcfc6a83a':'passed',
        'bf59aa3d7d604db6fe49debd':'review_required','ecb32bf169bd814b13791e4d':'review_required'}
