"""Quality metrics, abstention, raw source isolation and target-label exclusion."""
from dataclasses import replace
from types import SimpleNamespace

import cv2
import numpy as np
import pytest

from pallet import mask_boundary_fit as fit
from pallet import mask_quality_recovery as recovery
from pallet.mask_quality_metrics import compare_polygons,summarize,release_decision
from pallet.pose_review_geometry import raster_mask

POLYGON=[[20,20],[100,20],[100,70],[80,70],[80,35],[40,35],[40,70],[20,70]]
BOX=dict(x=20,y=20,width=80,height=50)


def image(polygon=POLYGON):return np.where(raster_mask(polygon,128,96),210,20).astype(np.uint8)


def test_pixel_edge_identical_masks_have_perfect_finite_scores():
    result=compare_polygons(POLYGON,POLYGON,[128,96],50)
    assert result['iou']==result['boundary_f1_1px']==result['reviewed_to_draft_area_ratio']==1
    assert result['hd95_native_pixels']==result['assd_native_pixels']==0
    assert not result['polygon_changed'] and not result['vertex_count_changed']


def test_metric_respects_vertex_cycle_and_orientation_but_measures_changed_boundary():
    rotated=POLYGON[2:]+POLYGON[:2]
    assert compare_polygons(POLYGON,rotated,[128,96],50)['mean_vertex_distance_native_pixels']==0
    assert compare_polygons(POLYGON,POLYGON[::-1],[128,96],50)['iou']==1
    shifted=(np.asarray(POLYGON)+[2,0]).tolist();result=compare_polygons(POLYGON,shifted,[128,96],50)
    assert result['iou']<1 and result['hd95_native_pixels']>=2 and result['mean_vertex_distance_native_pixels']==2


def test_nonempty_masks_touching_image_edge_have_well_defined_boundaries():
    value=compare_polygons([[0,0],[128,0],[128,96],[0,96]],[[1,1],[127,1],[127,95],[1,95]],[128,96],96)
    assert value['assd_native_pixels']>0 and 0<value['iou']<1


def test_empty_raster_or_invalid_polygon_cannot_score_perfect():
    with pytest.raises(ValueError):compare_polygons([[0,0],[1,1],[0,1]],POLYGON,[128,96],50)


def test_zero_delivery_never_passes_quality_gate():
    assert summarize([])['iou_median'] is None
    gate=release_decision([],100)
    assert gate['state']=='blocked' and gate['delivery_rate']==0 and not gate['production_publication_authorized']


def test_predeclared_release_gate_needs_sample_size_quality_and_boundary_error():
    perfect=dict(compare_polygons(POLYGON,POLYGON,[128,96],50),bbox_height=50)
    assert release_decision([perfect]*10,100)['state']=='passed'
    assert release_decision([perfect]*9,100)['state']=='blocked'
    bad=dict(perfect,hd95_native_pixels=6)
    assert 'boundary_error_above_native_or_relative_limit' in release_decision([bad]*10,100)['reasons']


def test_source_family_uses_actual_topology_and_concavity():
    assert fit.shape_family(POLYGON,BOX)[:2]==(8,2)
    assert fit.shape_family([[20,20],[100,20],[100,70],[20,70]],BOX)[:2]==(4,0)


def test_native_line_fit_returns_real_supported_edge_not_initial_guess():
    im=image();line,metrics=fit.fit_edge(im,[20,21],[100,21],im,[20,20],[100,20])
    assert line is not None and metrics['rejection'] is None
    assert abs(line[0][1]-20)<.6 and metrics['support_fraction']>=.65


def test_blank_or_wrong_polarity_edges_abstain():
    blank=np.full((96,128),100,np.uint8)
    assert fit.fit_edge(blank,[20,20],[100,20],image(),[20,20],[100,20])[0] is None
    inverted=230-image()
    assert fit.fit_edge(inverted,[20,20],[100,20],image(),[20,20],[100,20])[0] is None
    assert fit.fit_edge(image(),[20,20],[100,20],blank,[20,20],[100,20])[0] is None


def test_fit_inherits_vertex_count_order_and_finds_line_intersections():
    im=image();initial=np.asarray(POLYGON)+[.6,.7]
    polygon,metrics=fit.refine_polygon(im,im,POLYGON,initial,BOX)
    assert polygon is not None,metrics
    assert len(polygon)==8 and metrics['vertex_count_inherited'] and metrics['vertex_order_inherited']
    assert np.linalg.norm(np.asarray(polygon)-POLYGON,axis=1).max()<1


def candidate(key,component,polygon=POLYGON):
    return dict(reference_key=key,independent_component=component,polygon=polygon,family=fit.shape_family(polygon,BOX))


def test_consensus_requires_two_independent_components_and_same_family():
    a=candidate('a','same');b=candidate('b','same')
    assert fit.consensus([a,b])[0] is None
    b['independent_component']='independent';assert fit.consensus([a,b])[0] is a
    b['polygon']=(np.asarray(POLYGON)+[2,0]).tolist();assert fit.consensus([a,b])[0] is None
    b['family']=(4,0,'wide');b['polygon']=[[0,0]]*4
    assert fit.consensus([a,b])[0] is None


def record(key,split='train',view='front',policy='p',cls=11):
    return dict(target_key=key,row=dict(target_key=key,split=split,viewpoint_candidate=view,policy_id=policy,final_class_id=cls),polygon=POLYGON)


@pytest.mark.parametrize('field,value',[('split','val'),('split','test'),('viewpoint_candidate','unknown'),('viewpoint_candidate','side'),('policy_id','other'),('final_class_id',12)])
def test_incompatible_or_held_out_sources_not_available(field,value):
    a,b=record('a'),record('b');b['row'][field]=value
    components={'a':'0'*64,'b':'0000000000000001'+'0'*48}
    assert not recovery.eligible_reference(a,b,components)


def test_known_coarse_primary_is_not_enough_for_ambiguous_class14():
    a,b=record('a',cls=14),record('b',cls=14)
    assert not recovery.eligible_reference(a,b,{'a':'0'*64,'b':'0000000000000001'+'0'*48})


def test_components_and_folds_not_target_labels_determine_source_exclusion():
    a,b=record('a'),record('b');components={'a':'0'*64,'b':'0000000000000001'+'0'*48}
    assert recovery.eligible_reference(a,b,components)
    b['polygon']=[[0,0],[1,0],[1,1],[0,1]]
    assert recovery.eligible_reference(a,b,components)
    components['b']=components['a'];assert not recovery.eligible_reference(a,b,components)
    components['b']='0000000000000003'+'0'*48;assert not recovery.eligible_reference(a,b,components)


def test_predict_refuses_target_annotation_pose_or_identity_features():
    target=dict(image=image(),box=BOX,class_id=11,policy_id='p',known_view='front')
    for key in ('polygon','pose','ruler','target_key','group_id','ground_truth'):
        with pytest.raises(ValueError,match='Unapproved'):recovery.predict(dict(target,**{key:'forbidden'}),[])
    polygon,metrics=recovery.predict(target,[])
    assert polygon is None and metrics['rejection']=='no_compatible_independent_reference'


def test_conflicting_components_connected_by_group_and_exact_image():
    values=[]
    for n in range(3):
        values.append(dict(target_key=str(n),row=dict(target_key=str(n),group_id='group'+str(n),frame_id=str(n),
            source_pcd_sha256=str(n),final_class_id=11,policy_id='p',bbox=BOX)))
    evidence=SimpleNamespace(image=lambda _:image(),patch=lambda _:fit.patch(image(),BOX))
    components,links=recovery.independent_components(values,evidence)
    assert len(set(components.values()))==1 and links


def test_readonly_fingerprint_never_writes_a_store(tmp_path):
    import sqlite3
    path=tmp_path/'store.sqlite3'
    with sqlite3.connect(path) as db:db.execute('CREATE TABLE events(id INTEGER,payload TEXT)');db.execute('INSERT INTO events VALUES(?,?)',(1,'原始UTF-8'))
    before=path.read_bytes();one=recovery.fingerprint(path);two=recovery.fingerprint(path)
    assert one==two and path.read_bytes()==before


def test_recovery_refuses_existing_outputs_before_source_reads(tmp_path,monkeypatch):
    monkeypatch.setattr(recovery,'PROJECT',tmp_path);out=tmp_path/'outputs/existing';out.mkdir(parents=True)
    with pytest.raises(ValueError,match='fresh'):recovery.run(out)
