from copy import deepcopy

import numpy as np
import pytest

from pallet.mask_class_keypoints import modal_counts,convert,clockwise_top_left,corner_geometry
from pallet.pose_review_geometry import raster_mask


def test_each_class_gets_unique_mode_not_average_or_max():
    records=[dict(target_key=str(c),class_id=c,polygon=[[0,0]]*8) for c in range(1,23)]
    records.extend([dict(target_key='a',class_id=9,polygon=[[0,0]]*16),dict(target_key='b',class_id=9,polygon=[[0,0]]*16)])
    result=modal_counts(records);assert result['9']['standard_count']==16 and result['9']['modal_support']==2
    assert result['1']['standard_count']==8


def test_tied_modes_are_not_silently_resolved():
    records=[dict(target_key=str(c),class_id=c,polygon=[[0,0]]*8) for c in range(1,23)]
    records.append(dict(target_key='different',class_id=9,polygon=[[0,0]]*12))
    with pytest.raises(ValueError,match='tied'):modal_counts(records)


def test_events_cannot_duplicate_one_human_target_in_mode_statistics():
    r=dict(target_key='a',class_id=1,polygon=[[0,0]]*4)
    with pytest.raises(ValueError,match='once'):modal_counts([r,r])


def test_true_rectangle_stays_four_not_padded_to_eight():
    p=[[10,10],[90,10],[90,35],[10,35]];mask=raster_mask(p,100,50)
    points,info=convert(mask,p,4,25)
    assert len(points)==4 and info['inserted_or_collinear_padding_points']==0
    points,info=convert(mask,p,8,25);assert points is None


def test_opening_is_not_erased_to_satisfy_four_point_class():
    p=[[5,5],[95,5],[95,40],[80,40],[80,20],[20,20],[20,40],[5,40]]
    mask=raster_mask(p,100,50);points,info=convert(mask,p,4,35)
    assert points is None and info['reason']=='class_four_points_would_erase_model_openings'


def test_eight_actual_corners_and_indent_are_preserved():
    p=[[5,5],[95,5],[95,40],[80,40],[80,20],[20,20],[20,40],[5,40]];mask=raster_mask(p,100,50)
    points,info=convert(mask,p,8,35)
    assert len(points)==8 and info['model_mask_fidelity_not_human_accuracy']['iou']==1
    assert np.array_equal(raster_mask(points,100,50),mask)


def test_clockwise_start_rule_does_not_depend_on_input_rotation_or_winding():
    p=np.array([[5,5],[95,5],[95,40],[5,40]],float)
    assert np.array_equal(clockwise_top_left(p),clockwise_top_left(np.roll(p[::-1],2,axis=0)))


def test_nearly_collinear_points_cannot_fake_keypoints():
    p=[[5,5],[40,5],[95,5],[95,40],[40,40],[5,40]];mask=raster_mask(p,100,50)
    points,info=convert(mask,p,6,35);assert points is None and info['reason']=='no_supported_exact_K_polygon'


def test_closed_holes_are_not_filled_in_keypoint_conversion():
    mask=np.zeros((50,100),bool);mask[5:45,5:95]=1;mask[15:25,20:40]=0
    points,info=convert(mask,[[5,5],[95,5],[95,45],[5,45]],4,40)
    assert points is None and info['reason']=='closed_hole_cannot_be_encoded_by_single_ring'


def test_conversion_diagnostics_use_exact_full_native_export_frame():
    from pallet.mask_class_keypoints import mask_fidelity
    p=[[5,5],[95,8],[95,40],[5,35]];mask=raster_mask(p,100,50)
    points,info=convert(mask,p,4,35,origin=(71,106),native_size=(224,172))
    assert points and len(points)==4 and min(v[0] for v in points)>=71
    assert info['fidelity_raster_frame']=='serialized_final_full_native_image'
    assert info['model_mask_fidelity_not_human_accuracy']==mask_fidelity(points,mask,(71,106),(224,172))
