"""Independent raster, raw-source, fold, abstention and exclusive-seal attacks."""
import ast
import copy
import json
from pathlib import Path
import sqlite3

import numpy as np
import pytest

from scripts import verify_mask_quality_recovery as audit


FOUR = [[2,2],[12,2],[12,10],[2,10]]
FINE = [[2,2],[12,2],[12,10],[9,10],[9,6],[5,6],[5,10],[2,10]]


def row(key='a', cls=4, split='train', view='front', group=None, frame=None, pcd=None):
    return dict(target_key=key,final_class_id=cls,split=split,viewpoint_candidate=view,
        policy_id='sensor',frame_id=frame or 'frame-'+key,group_id=group or 'group-'+key,
        source_pcd_sha256=pcd or 'pcd-'+key,bbox=dict(x=2,y=2,width=10,height=8),size=[16,14])


def record(key='a', **kwargs):
    return dict(target_key=key,row=row(key,**kwargs),polygon=copy.deepcopy(FOUR),
        payload_sha256=audit.sha(dict(actual_payload=key)))


def component(fold, salt=''):
    for i in range(1000):
        value = audit.sha([salt,i])
        if audit.fold_for(value) == fold:
            return value
    raise RuntimeError('No synthetic fold hash')


def metric(iou=1., hd95=0., height=20):
    return dict(iou=iou,assd_native_pixels=0.,hd95_native_pixels=hd95,
        hd95_bbox_height_fraction=hd95/max(height,1),boundary_f1_1px=1.,
        reviewed_to_draft_area_ratio=1.,polygon_changed=False,vertex_count_changed=False,
        bbox_height=height)


def write_jsonl(path, records):
    path.write_bytes(b''.join(audit.canonical(record)+b'\n' for record in records))


def test_raster_pixel_centers_not_cv_fillpoly_inclusive_integer_vertices():
    mask = audit.raster([[0,0],[4,0],[4,3],[0,3]],(6,5))
    expected = np.zeros((5,6),bool); expected[:3,:4] = True
    np.testing.assert_array_equal(mask,expected)
    assert mask.sum() == 12


def test_raster_exact_half_pixel_edges_are_left_included_right_excluded():
    mask = audit.raster([[.5,.5],[3.5,.5],[3.5,3.5],[.5,3.5]],(5,5))
    expected = np.zeros((5,5),bool); expected[:3,:3] = True
    np.testing.assert_array_equal(mask,expected)


def test_scanline_raster_reversed_and_cyclic_polygons_identical_and_notches_preserved():
    mask = audit.raster(FINE,(16,14))
    assert mask[4,7] and not mask[8,7] and mask[8,3]
    np.testing.assert_array_equal(mask,audit.raster(FINE[::-1],(16,14)))
    np.testing.assert_array_equal(mask,audit.raster(FINE[3:]+FINE[:3],(16,14)))


@pytest.mark.parametrize('bad', [[],[[0,0],[3,0]],[[0,0],[3,0],[float('nan'),3]],
    [[-1,0],[3,0],[3,3]],[[0,0],[40,0],[0,3]],[[0,0],[0,0],[3,3]],
    [[0,0],[3,3],[0,3],[3,0]],[[0,0],[.1,0],[0,.1]]])
def test_invalid_polygons_do_not_get_perfect_fallback_metrics(bad):
    with pytest.raises(ValueError):
        audit.independent_metrics(bad,FOUR,(16,14),8)


def test_perfect_mask_has_zero_boundary_distance_and_exact_iou_and_area():
    value = audit.independent_metrics(FOUR,FOUR,(16,14),8)
    assert value['iou'] == value['boundary_f1_1px'] == value['reviewed_to_draft_area_ratio'] == 1
    assert value['assd_native_pixels'] == value['hd95_native_pixels'] == value['mean_vertex_distance_native_pixels'] == 0
    assert not value['polygon_changed'] and value['saved_annotation_is_research_reference_not_confirmed_GT']


def test_one_pixel_shift_has_analytic_iou_hd95_and_boundary_f1():
    shifted = [[x+1,y] for x,y in FOUR]
    value = audit.independent_metrics(FOUR,shifted,(16,14),8)
    assert value['iou'] == pytest.approx(9/11)
    assert value['hd95_native_pixels'] == 1
    assert value['boundary_f1_1px'] == 1
    assert value['reviewed_to_draft_area_ratio'] == 1
    assert value['mean_vertex_distance_native_pixels'] == 1


def test_boundary_erosion_uses_zero_outside_image_not_opencv_neutral_padding():
    # Full-image contours still have a real image-edge boundary, not an empty edge.
    full = [[0,0],[6,0],[6,5],[0,5]]
    inset = [[1,1],[5,1],[5,4],[1,4]]
    value = audit.independent_metrics(full,inset,(6,5),5)
    assert value['iou'] == .4
    assert value['hd95_native_pixels'] == pytest.approx(np.sqrt(2))
    assert 1 < value['assd_native_pixels'] < np.sqrt(2)
    assert value['boundary_f1_1px'] < 1


def test_geometry_equivalence_does_not_invent_matching_vertex_topology():
    value = audit.independent_metrics(FOUR,FOUR[2:]+FOUR[:2],(16,14),8)
    assert value['iou'] == 1 and value['mean_vertex_distance_native_pixels'] == 0
    assert value['polygon_changed'] and not value['vertex_count_changed']
    extra = FOUR[:1]+[[7,2]]+FOUR[1:]
    value = audit.independent_metrics(FOUR,extra,(16,14),8)
    assert value['iou'] == 1 and value['mean_vertex_distance_native_pixels'] is None
    assert value['vertex_count_changed']


def test_subpixel_empty_valid_area_polygon_is_rejected_without_fake_accuracy():
    thin = [[.6,.6],[8.6,.6],[8.6,.8],[.6,.8]]
    with pytest.raises(ValueError,match='Raster-empty'):
        audit.independent_metrics(thin,FOUR,(16,14),8)


def test_empty_summary_and_gate_are_blocked_with_null_quality_and_zero_delivery():
    value = audit.quality_gate([],100)
    assert value['state'] == 'blocked' and value['accepted'] == 0 and value['total'] == 100
    assert value['quality']['iou_median'] is None and value['delivery_rate'] == 0
    assert len(value['reasons']) == 3 and not value['production_publication_authorized']
    assert audit.quality_gate([],0)['delivery_rate'] == 0


def test_gate_can_pass_only_predeclared_minimum_quality_not_publication_permission():
    values = [metric(.95,2) for _ in range(10)]
    gate = audit.quality_gate(values,100)
    assert gate['state'] == 'passed' and gate['accepted'] == 10 and gate['delivery_rate'] == .1
    assert gate['reasons'] == [] and not gate['production_publication_authorized']
    assert audit.quality_gate(values[:9],100)['state'] == 'blocked'


@pytest.mark.parametrize('attack', ['median','fraction','boundary','relative_boundary'])
def test_gate_rejects_low_iou_fraction_or_single_boundary_failure(attack):
    values = [metric(.99,2,height=20) for _ in range(10)]
    if attack == 'median':
        values = [metric(.949999,2) for _ in range(10)]
    elif attack == 'fraction':
        values[0]['iou'] = values[1]['iou'] = .899999
    elif attack == 'boundary':
        values[0]['hd95_native_pixels'] = 2.00001
    else:
        values[0].update(bbox_height=40,hd95_native_pixels=4.00001)
    assert audit.quality_gate(values,100)['state'] == 'blocked'


def test_gate_fraction_is_accepted_denominator_and_coverage_is_full_target_denominator():
    values = [metric(.99) for _ in range(9)]+[metric(.89)]
    gate = audit.quality_gate(values,1000)
    assert gate['state'] == 'passed' and gate['delivery_rate'] == .01
    with pytest.raises(ValueError):
        audit.quality_gate(values,9)


@pytest.mark.parametrize('raw', ['{"a":1,"a":2}','{"a":NaN}','{"a":Infinity}'])
def test_json_duplicate_keys_and_nonfinite_values_are_not_silently_accepted(raw):
    with pytest.raises(ValueError):
        audit.loads(raw)


@pytest.mark.parametrize('actual,expected', [(False,0),(True,1),('0',0),(1.,1),(float('nan'),1.),
    ({'a':1,'extra':1},{'a':1}),([1,2],[1])])
def test_claims_are_type_strict_and_cannot_launder_boolean_writes_or_extra_fields(actual,expected):
    with pytest.raises(ValueError):
        audit.equal(actual,expected)


def snapshot(path, current_raw=None, event_raw=None, revision=1, event_revision=1):
    value = dict(target_key='a',revision=revision,polygon=FOUR)
    current_raw = current_raw or json.dumps(value,indent=2)
    event_raw = event_raw or current_raw
    with sqlite3.connect(path) as db:
        db.executescript('CREATE TABLE annotations(target_key TEXT,revision INTEGER,payload TEXT);'
            'CREATE TABLE events(id INTEGER,target_key TEXT,revision INTEGER,payload TEXT);'
            'CREATE TABLE metadata(key TEXT,value TEXT);')
        db.execute('INSERT INTO annotations VALUES (?,?,?)',('a',revision,current_raw))
        db.execute('INSERT INTO events VALUES (?,?,?,?)',(1,'a',event_revision,event_raw))
        db.execute('INSERT INTO metadata VALUES (?,?)',('binding','{"actual":"source"}'))
    return path


def test_read_only_store_fingerprint_and_exact_utf8_latest_do_not_write_database(tmp_path):
    path = snapshot(tmp_path/'pose.sqlite3')
    before = path.read_bytes()
    store = audit.read_store(path,'pose',True)
    value,last = audit.exact_latest(store,'a')
    assert value['polygon'] == FOUR and last[2] == store['current']['a'][1]
    assert store['fingerprint'] == audit.read_store(path,'pose')['fingerprint']
    assert path.read_bytes() == before


def test_semantically_equal_reformatted_current_is_not_exact_raw_latest_event(tmp_path):
    current = json.dumps(dict(target_key='a',revision=1,polygon=FOUR),indent=2)
    path = snapshot(tmp_path/'pose.sqlite3',current,json.dumps(json.loads(current)))
    store = audit.read_store(path,'pose',True)
    with pytest.raises(ValueError,match='raw latest'):
        audit.exact_latest(store,'a')


def test_current_latest_event_cannot_be_stale_even_when_polygon_matches(tmp_path):
    path = snapshot(tmp_path/'pose.sqlite3')
    with sqlite3.connect(path) as db:
        db.execute('INSERT INTO events VALUES (?,?,?,?)',(2,'a',2,json.dumps(dict(target_key='a',revision=2,polygon=FOUR))))
    with pytest.raises(ValueError,match='raw latest'):
        audit.exact_latest(audit.read_store(path,'pose',True),'a')


@pytest.mark.parametrize('attack', ['duplicate_revision','wrong_current_key','wrong_current_revision','wrong_event_key','wrong_event_revision'])
def test_read_store_rejects_relational_laundering_or_duplicate_event_revision(tmp_path,attack):
    path = snapshot(tmp_path/'pose.sqlite3')
    with sqlite3.connect(path) as db:
        if attack == 'duplicate_revision':
            db.execute('INSERT INTO events SELECT 2,target_key,revision,payload FROM events')
        elif attack == 'wrong_current_key':
            db.execute("UPDATE annotations SET target_key='foreign'")
        elif attack == 'wrong_current_revision':
            db.execute('UPDATE annotations SET revision=2')
        elif attack == 'wrong_event_key':
            db.execute("UPDATE events SET target_key='foreign'")
        else:
            db.execute('UPDATE events SET revision=2')
    with pytest.raises(ValueError):
        audit.read_store(path,'pose',True)


def test_fingerprints_detect_current_raw_event_raw_and_metadata_mutations(tmp_path):
    path = snapshot(tmp_path/'pose.sqlite3')
    before = audit.read_store(path,'pose',True)['fingerprint']
    with sqlite3.connect(path) as db:
        db.execute("UPDATE metadata SET value='changed'")
    after = audit.read_store(path,'pose',True)['fingerprint']
    assert before['tables']['metadata'] != after['tables']['metadata']
    assert before['tables']['events'] == after['tables']['events']
    assert before['schema_sha256'] == after['schema_sha256']


@pytest.mark.parametrize('field',audit.FALSE_FLAGS)
def test_unconfirmed_rejects_every_gt_or_eligibility_promotion(field):
    value = dict(state='draft',**dict.fromkeys(audit.FALSE_FLAGS,False))
    audit.unconfirmed(value)
    value[field] = True
    with pytest.raises(ValueError):
        audit.unconfirmed(value)


@pytest.mark.parametrize('state',['confirmed','deleted','deferred'])
def test_protected_states_cannot_be_research_contour_sources(state):
    with pytest.raises(ValueError):
        audit.unconfirmed(dict(state=state))


def test_original_rectangle_detection_cannot_be_evaded_by_rotation_or_reversal():
    r = row()
    for p in (FOUR,FOUR[::-1],FOUR[2:]+FOUR[:2]):
        assert audit.original_rectangle(p,r)
    assert not audit.original_rectangle(FINE,r)
    changed = copy.deepcopy(FOUR); changed[0][0] += .01
    assert not audit.original_rectangle(changed,r)


def test_registry_uses_full_publication_hash_key_triple_not_target_or_task_namespace():
    old = dict(target_key='task',polygon=FOUR)
    later = dict(target_key='task',polygon=FINE)
    pubs = {13:dict(path=Path('pub13'),proposals={}),15:dict(path=Path('pub15'),proposals={'task':later})}
    task = dict(kind='independent_preannotation',namespace='v1',proposal=old,path=Path('task1'))
    registry = {(13,audit.sha(old),'task'):task}
    saved = dict(target_key='task',proposal_publication=13,base_proposal_id=audit.sha(old))
    assert audit.resolve_event(saved,pubs,registry) == task
    saved.update(proposal_publication=15,base_proposal_id=audit.sha(later))
    result = audit.resolve_event(saved,pubs,registry)
    assert result['kind'] == 'canonical_publication' and result['namespace'] is None and result['proposal'] == later


@pytest.mark.parametrize('version,base,key',[(True,'base','a'),(16,'base','a'),(15,'foreign','a'),(13,'base','foreign')])
def test_registry_rejects_boolean_unknown_publication_and_foreign_base_or_key(version,base,key):
    proposal = dict(target_key='a',polygon=FOUR)
    pubs = {13:dict(path=Path('pub13'),proposals={}),15:dict(path=Path('pub15'),proposals={'a':proposal})}
    registry = {(13,'base','a'):dict(kind='independent_preannotation')}
    with pytest.raises(ValueError):
        audit.resolve_event(dict(proposal_publication=version,base_proposal_id=base,target_key=key),pubs,registry)


def test_all_three_task_registries_route_13_14_15_and_allow_normal15():
    registry,pubs = {},{}
    for number,version in ((1,13),(2,14),(3,15)):
        draft = dict(target_key=f'task{number}',polygon=FOUR)
        reference = dict(kind='independent_preannotation',namespace=f'v{number}',proposal=draft)
        registry[version,audit.sha(draft),draft['target_key']] = reference
        pubs[version] = dict(path=Path(str(version)),proposals={})
    normal = dict(target_key='normal',polygon=FINE)
    pubs[15]['proposals']['normal'] = normal
    for (version,base,key),expected in registry.items():
        assert audit.resolve_event(dict(proposal_publication=version,base_proposal_id=base,target_key=key),pubs,registry) == expected
    assert audit.resolve_event(dict(proposal_publication=15,base_proposal_id=audit.sha(normal),target_key='normal'),pubs,registry)['kind'] == 'canonical_publication'


class Evidence:
    def __init__(self, catalog, images=None, patches=None):
        self.rows = {r['target_key']:r['row'] for r in catalog}
        self.images = images or {r['row']['frame_id']:np.random.default_rng(i).integers(0,256,(14,16),dtype=np.uint8)
            for i,r in enumerate(catalog)}
        self.patches = patches or {key:np.random.default_rng(i).normal(size=(8,8)) for i,key in enumerate(self.rows)}

    def image(self,key):
        return self.images[key]

    def patch(self,key):
        return self.patches[key]


def test_connected_components_include_transitive_group_frame_and_pcd_links():
    catalog = [record('a',group='ga'),record('b',group='ga',pcd='shared'),
        record('c',pcd='shared',frame='same'),record('d',frame='same'),record('unrelated')]
    components = audit.independent_components(catalog,Evidence(catalog))
    expected = audit.sha(['a','b','c','d'])
    assert all(components[key] == expected for key in ('a','b','c','d'))
    assert components['unrelated'] == audit.sha(['unrelated'])


def test_exact_decoded_image_duplicates_are_connected_across_class_and_split():
    catalog = [record('a'),record('b',cls=19,split='test')]
    image = np.arange(14*16,dtype=np.uint8).reshape(14,16)
    evidence = Evidence(catalog,images={'frame-a':image,'frame-b':image.copy()})
    components = audit.independent_components(catalog,evidence)
    assert components['a'] == components['b'] == audit.sha(['a','b'])


def test_verified_near_duplicate_requires_same_class_policy_dhash_and_ncc(monkeypatch):
    catalog = [record('a'),record('b'),record('differentclass',cls=5),record('differentpolicy')]
    catalog[-1]['row']['policy_id'] = 'other-camera'
    evidence = Evidence(catalog)
    evidence.patches['b'] = evidence.patches['a'].copy()
    monkeypatch.setattr(audit,'image_dhash',lambda *_:0)
    components = audit.independent_components(catalog,evidence)
    assert components['a'] == components['b'] == audit.sha(['a','b'])
    assert components['differentclass'] != components['a'] and components['differentpolicy'] != components['a']


def test_low_correlation_dhash_collision_is_not_falsely_unioned(monkeypatch):
    catalog = [record('a'),record('b')]
    monkeypatch.setattr(audit,'image_dhash',lambda *_:0)
    components = audit.independent_components(catalog,Evidence(catalog))
    assert components['a'] != components['b']


def test_nontrain_bridge_still_prevents_train_reference_target_leakage():
    catalog = [record('target',group='shared'),record('bridge',group='shared',pcd='pcd-joined',split='val'),
        record('source',pcd='pcd-joined')]
    components = audit.independent_components(catalog,Evidence(catalog))
    assert components['target'] == components['bridge'] == components['source']
    assert not audit.eligible(catalog[0],catalog[2],components)


def test_recorded_component_link_forest_requires_actual_transitive_proof():
    catalog = [record('a',group='same'),record('b',group='same',pcd='join'),record('c',pcd='join')]
    sources = {r['target_key']:r for r in catalog}
    components = {key:audit.sha(['a','b','c']) for key in sources}
    links = [dict(left='a',right='b',reason='group'),dict(left='b',right='c',reason='pcd')]
    audit.check_component_links(links,sources,components,Evidence(catalog))
    links[1]['reason'] = 'group'
    with pytest.raises(ValueError,match='Fabricated'):
        audit.check_component_links(links,sources,components,Evidence(catalog))


def test_recorded_component_link_forest_rejects_missing_link_or_cycle():
    catalog = [record('a',group='same'),record('b',group='same'),record('c',group='same')]
    sources = {r['target_key']:r for r in catalog}
    components = {key:audit.sha(['a','b','c']) for key in sources}
    links = [dict(left='a',right='b',reason='group')]
    with pytest.raises(ValueError,match='length'):
        audit.check_component_links(links,sources,components,Evidence(catalog))
    links.append(dict(left='b',right='a',reason='group'))
    with pytest.raises(ValueError,match='cycle'):
        audit.check_component_links(links,sources,components,Evidence(catalog))


def test_protected_inventory_detects_added_labels_not_just_mutations_to_named_baseline(tmp_path):
    formal = tmp_path/'formal'
    for name in ('labels','annotations','protocol','images'):
        (formal/name).mkdir(parents=True)
    (formal/'manifest.json').write_text('{}')
    (formal/'checksums.sha256').write_text('frozen')
    (formal/'labels/old.txt').write_text('1 0.5 0.5 1 1')
    before = audit.protected_inventory(formal)
    (formal/'labels/new.txt').write_text('not authorized')
    assert audit.protected_inventory(formal) != before


@pytest.mark.parametrize('attack',['target_val','source_test','class','policy','view','unknown_target','unknown_source',
    'none_view','class14','same_component','same_fold'])
def test_reference_policy_is_train_only_known_equal_view_same_class_policy_other_fold_component(attack):
    target,source = record('target'),record('source')
    components = {'target':component(0,'t'),'source':component(1,'s')}
    assert audit.eligible(target,source,components)
    if attack == 'target_val': target['row']['split'] = 'val'
    elif attack == 'source_test': source['row']['split'] = 'test'
    elif attack == 'class': source['row']['final_class_id'] = 7
    elif attack == 'policy': source['row']['policy_id'] = 'other'
    elif attack == 'view': source['row']['viewpoint_candidate'] = 'rear'
    elif attack == 'unknown_target': target['row']['viewpoint_candidate'] = 'unknown'
    elif attack == 'unknown_source': source['row']['viewpoint_candidate'] = 'unknown'
    elif attack == 'none_view': target['row']['viewpoint_candidate'] = source['row']['viewpoint_candidate'] = None
    elif attack == 'class14': target['row']['final_class_id'] = source['row']['final_class_id'] = 14
    elif attack == 'same_component': components['source'] = components['target']
    else: components['source'] = component(0,'differentcomponent')
    assert not audit.eligible(target,source,components)


def test_reference_budget_is_image_only_top3_and_distinct_source_components(monkeypatch):
    catalog = [record(key) for key in ('target','best','samecomponent','second','third','fourth')]
    components = {'target':component(0,'target')}
    components.update({key:component(1,key) for key in ('best','second','third','fourth')})
    components['samecomponent'] = components['best']
    similarity = {'best':.9,'samecomponent':.85,'second':.8,'third':.7,'fourth':.6}
    class KeyEvidence:
        def patch(self,key): return key
    monkeypatch.setattr(audit,'ncc',lambda source,target:similarity[source])
    options,refs = audit.reference_budget(catalog[0],catalog,components,KeyEvidence())
    assert len(options) == 5 and [r['target_key'] for r in refs] == ['best','second','third']
    catalog[0]['polygon'] = FINE
    assert audit.reference_budget(catalog[0],catalog,components,KeyEvidence())[1] == refs


def test_reference_tie_break_is_key_only_not_target_truth_topology(monkeypatch):
    target = record('target')
    catalog = [target,record('b'),record('a')]
    components = {'target':component(0,'target'),'a':component(1,'a'),'b':component(2,'b')}
    monkeypatch.setattr(audit,'ncc',lambda *_:.7)
    class Dummy:
        def patch(self,key): return key
    assert [r['target_key'] for r in audit.reference_budget(target,catalog,components,Dummy())[1]] == ['a','b']


@pytest.fixture
def numbers():
    return dict(initial_ncc_min=.55,ecc_min=.84,boundary_ncc_min=.78,
        normal_search_native_pixels=4.,max_line_angle_degrees=5.,support_fraction_min=.65,
        contrast_min=18.,fit_residual_p90_max=.8,consensus_native_pixels_max=1.5,
        minimum_independent_references=2,maximum_references=3)


def native_rectangle():
    value = [[20,20],[120,20],[120,60],[20,60]]
    mask = audit.raster(value,(160,90))
    image = np.full((90,160),30,np.uint8); image[mask] = 200
    return image,value


def test_native_edge_replay_uses_measured_signed_transition_not_saved_support_claim(numbers):
    image,value = native_rectangle()
    line,diag = audit.replay_edge(image,value[0],value[1],image,value[0],value[1],numbers)
    assert line is not None and diag['rejection'] is None and diag['support_fraction'] == 1
    assert diag['median_contrast'] == 170 and diag['normal_offset_median'] == 0
    assert len(diag['support_points']) == 96
    assert max(abs(y-20) for x,y in diag['support_points']) == 0


def test_native_edge_replay_rejects_reverse_polarity_weak_source_and_weak_target(numbers):
    image,value = native_rectangle()
    weak = np.full_like(image,100)
    line,diag = audit.replay_edge(image,value[0],value[1],weak,value[0],value[1],numbers)
    assert line is None and diag['rejection'] == 'weak_source_boundary_polarity'
    for target in (weak,255-image):
        line,diag = audit.replay_edge(target,value[0],value[1],image,value[0],value[1],numbers)
        assert line is None and diag['rejection'] == 'insufficient_boundary_support'


@pytest.mark.parametrize('attack',['short_target','short_source','image_edge'])
def test_native_edge_replay_rejects_too_short_or_clipped_search(numbers,attack):
    image,value = native_rectangle()
    a,b,sa,sb = value[0],value[1],value[0],value[1]
    if attack == 'short_target': b = [22,20]
    elif attack == 'short_source': sb = [22,20]
    else: a,b = [20,2],[120,2]
    line,diag = audit.replay_edge(image,a,b,image,sa,sb,numbers)
    assert line is None
    assert diag['rejection'] == {'short_target':'edge_too_short_for_independent_support',
        'short_source':'source_edge_too_short','image_edge':'boundary_search_touches_image_edge'}[attack]


def test_refinement_independently_intersects_measured_lines_and_preserves_four_points(numbers):
    image,value = native_rectangle()
    target,source = record('target'),record('source')
    for r in (target,source):
        r['polygon'] = copy.deepcopy(value)
        r['row'].update(size=[160,90],bbox=dict(x=20,y=20,width=100,height=40))
    evidence = Evidence([source,target],images={'frame-source':image,'frame-target':image})
    candidate,diag = audit.replay_refinement(source,target,np.asarray(value,float),evidence,numbers)
    np.testing.assert_allclose(candidate,value,atol=1e-5)
    assert diag['rejection'] is None and len(diag['edges']) == 4
    assert diag['vertex_count_inherited'] and diag['vertex_order_inherited']
    assert diag['refinement_area_ratio'] == pytest.approx(1)


def test_refinement_stops_at_actual_first_failed_native_edge(numbers):
    image,value = native_rectangle()
    target,source = record('target'),record('source')
    for r in (target,source):
        r['polygon'] = value
        r['row'].update(size=[160,90],bbox=dict(x=20,y=20,width=100,height=40))
    evidence = Evidence([source,target],images={'frame-source':image,'frame-target':np.full_like(image,100)})
    candidate,diag = audit.replay_refinement(source,target,np.asarray(value,float),evidence,numbers)
    assert candidate is None and diag['rejection'] == 'native_edge_support_failed'
    assert diag['failed_edge'] == 0 and len(diag['edges']) == 1


def test_ecc_alignment_replays_actual_optimization_and_not_reported_matrix(numbers):
    image,value = native_rectangle()
    target,source = record('target'),record('source')
    for r in (target,source):
        r['polygon'] = value
        r['row'].update(size=[160,90],bbox=dict(x=20,y=20,width=100,height=40))
    class Native:
        def patch(self,key): return audit.native_patch(image,source['row']['bbox'])
    initial,diag = audit.replay_alignment(source,target,Native(),numbers)
    assert diag['rejection'] is None and diag['initial_ncc'] == pytest.approx(1)
    assert diag['ecc'] >= .99 and diag['boundary_ncc'] >= .99
    np.testing.assert_allclose(initial,value,atol=1e-3)


def test_alignment_rejects_initial_low_similarity_before_ecc(numbers,monkeypatch):
    target,source = record('target'),record('source')
    class Different:
        def patch(self,key): return np.ones((20,20),np.uint8)
    called = []
    monkeypatch.setattr(audit.cv2,'findTransformECC',lambda *_:called.append(True))
    initial,diag = audit.replay_alignment(source,target,Different(),numbers)
    assert initial is None and diag['rejection'] == 'initial_similarity_below_original_gate' and not called


@pytest.mark.parametrize('attack',['ecc','boundary','deformation'])
def test_alignment_rejects_original_photometric_and_affine_deformation_gates(numbers,monkeypatch,attack):
    target,source = record('target'),record('source')
    patch = np.random.default_rng(71).integers(0,256,(112,256),dtype=np.uint8)
    class Native:
        def patch(self,key): return patch
    matrix = np.eye(2,3,dtype=np.float32)
    if attack == 'deformation': matrix[0,0] = 1.401
    monkeypatch.setattr(audit.cv2,'findTransformECC',lambda *_:(.83999 if attack == 'ecc' else .99,matrix))
    if attack == 'boundary':
        original = audit.ncc
        monkeypatch.setattr(audit,'ncc',lambda a,b:original(a,b) if np.ndim(a) == 2 else .77999)
    initial,diag = audit.replay_alignment(source,target,Native(),numbers)
    assert initial is None and diag['rejection'] == ('excessive_affine_deformation' if attack == 'deformation' else 'photometric_gates_not_met')


def supported(key='a',comp='component-a',poly=None,family=None):
    return dict(reference_key=key,independent_component=comp,polygon=copy.deepcopy(FOUR if poly is None else poly),
        family=[4,0,'narrow'] if family is None else family)


def test_consensus_needs_two_different_source_components_and_agreement_at_most_15(numbers):
    a,b = supported(),supported('b','component-b',[[x+1.5,y] for x,y in FOUR])
    chosen,diag = audit.replay_consensus([a,b],numbers)
    assert chosen is a and diag['support_reference_keys'] == ['b'] and diag['agreement_limit_native_pixels'] == 1.5
    b['polygon'][0][0] += .00001
    chosen,diag = audit.replay_consensus([a,b],numbers)
    assert chosen is None and diag['rejection'] == 'multi_reference_geometry_disagreement'


@pytest.mark.parametrize('attack',['single_reference','same_component','different_topology_family'])
def test_consensus_never_accepts_unsupported_single_source_or_mismatched_family(numbers,attack):
    a,b = supported(),supported('b','component-b')
    candidates = [a,b]
    if attack == 'single_reference': candidates = [a]
    elif attack == 'same_component': b['independent_component'] = a['independent_component']
    else: b['family'] = [4,0,'wide']
    chosen,diag = audit.replay_consensus(candidates,numbers)
    assert chosen is None and diag['rejection'] is not None


def test_reference_family_comes_from_reference_polygon_not_target_label():
    box = dict(x=2,y=2,width=10,height=8)
    assert audit.reference_family(FOUR,box) == [4,0,'narrow']
    assert audit.reference_family(FINE,box) == [8,2,'narrow']
    assert audit.reference_family(FINE[::-1],box) == [8,2,'narrow']


def test_zero_reference_prediction_is_honest_abstention_without_using_target_polygon(numbers):
    target = record('target'); target['polygon'] = 'must not be read'
    candidate,diag = audit.replay_prediction(target,[],None,numbers,{'target':'unused'})
    assert candidate is None and diag['attempts'] == [] and diag['rejection'] == 'no_compatible_independent_reference'


def test_prediction_replay_does_not_get_to_select_by_target_truth(numbers,monkeypatch):
    target = record('target'); target['polygon'] = 'deliberately unavailable to prediction'
    sources = [record('a'),record('b')]
    comps = {'a':'component-a','b':'component-b'}
    monkeypatch.setattr(audit,'replay_alignment',lambda *_:(np.asarray(FOUR),dict(rejection=None,initial_ncc=.9)))
    monkeypatch.setattr(audit,'replay_refinement',lambda *_:(copy.deepcopy(FOUR),dict(rejection=None)))
    candidate,diag = audit.replay_prediction(target,sources,None,numbers,comps)
    assert candidate == FOUR and diag['candidate_family'] == [4,0,'narrow']
    assert diag['consensus']['support_reference_keys'] == ['b']


def test_fresh_v2_directory_is_supported_not_fixed_to_failed_v1(seal_output):
    output = seal_output.parent/'pallet_mask_quality_recovery_v2'
    output.mkdir(); (output/'result.json').write_text('{}')
    audit.seal(output,lambda _:dict(state='passed'))
    assert (output/audit.SEAL).is_file() and not (seal_output/audit.SEAL).exists()


def test_member_and_inventory_refuse_symlinks_and_parent_escape(tmp_path):
    root = tmp_path/'root'; root.mkdir()
    external = tmp_path/'external'; external.write_text('untouched')
    with pytest.raises(ValueError): audit.member(root,'../external')
    with pytest.raises(ValueError): audit.member(root,str(external))
    (root/'link').symlink_to(external)
    with pytest.raises(ValueError): audit.member(root,'link')
    with pytest.raises(ValueError): audit.inventory(root)
    assert external.read_text() == 'untouched'


@pytest.fixture
def seal_output(tmp_path,monkeypatch):
    project = tmp_path/'project'
    output = project/'outputs/pallet_mask_quality_recovery_v1'
    output.mkdir(parents=True)
    (output/'result.json').write_bytes(b'{"state":"completed_offline_not_published"}\n')
    monkeypatch.setattr(audit,'PROJECT',project)
    monkeypatch.setattr(audit,'OUTPUT',output)
    return output


def test_success_writes_only_exclusive_private_independent_seal_never_rewrites_result(seal_output):
    original = (seal_output/'result.json').read_bytes()
    result = audit.seal(seal_output,lambda _:dict(state='passed',production_publication_authorized=False))
    saved = (seal_output/audit.SEAL).read_bytes()
    assert audit.loads(saved) == result
    assert (seal_output/audit.SEAL).stat().st_mode & 0o077 == 0
    assert (seal_output/'result.json').read_bytes() == original
    with pytest.raises(ValueError,match='overwrite'):
        audit.seal(seal_output,lambda _:dict(state='passed'))
    assert (seal_output/audit.SEAL).read_bytes() == saved
    assert {path.name for path in seal_output.iterdir()} == {'result.json',audit.SEAL}


def test_failed_audit_writes_only_fresh_failure_no_pass_seal_and_preserves_failure(seal_output):
    original = (seal_output/'result.json').read_bytes()
    def fail(_): raise ValueError('independent metric mismatch')
    with pytest.raises(ValueError,match='metric mismatch'):
        audit.seal(seal_output,fail)
    raw = (seal_output/audit.FAILURE).read_bytes()
    value = audit.loads(raw)
    assert value['state'] == 'failed' and value['result_sha256'] == audit.digest(seal_output/'result.json')
    assert not (seal_output/audit.SEAL).exists() and (seal_output/'result.json').read_bytes() == original
    with pytest.raises(ValueError,match='overwrite'):
        audit.seal(seal_output,lambda _:dict(state='passed'))
    assert (seal_output/audit.FAILURE).read_bytes() == raw


def test_unfinished_output_or_nonpassed_auditor_never_gets_a_success_seal(seal_output):
    with pytest.raises(ValueError,match='successfully'):
        audit.seal(seal_output,lambda _:dict(state='failed'))
    assert not (seal_output/audit.SEAL).exists()


def test_output_symlink_and_other_output_name_cannot_redirect_verifier_writes(seal_output):
    link = seal_output.parent/'link'; link.symlink_to(seal_output,target_is_directory=True)
    with pytest.raises(ValueError,match='exact'):
        audit.seal(link,lambda _:dict(state='passed'))
    other = seal_output.parent/'other'; other.mkdir(); (other/'result.json').write_text('{}')
    with pytest.raises(ValueError,match='exact'):
        audit.seal(other,lambda _:dict(state='passed'))
    assert not (other/audit.SEAL).exists() and not (seal_output/audit.SEAL).exists()


def test_existing_broken_symlink_seal_or_hardlinked_seal_never_overwritten(seal_output):
    protected = seal_output.parent/'protected.json'; protected.write_text('preserve')
    (seal_output/audit.SEAL).symlink_to(seal_output/'not-there')
    with pytest.raises(ValueError,match='overwrite'):
        audit.seal(seal_output,lambda _:dict(state='passed'))
    assert protected.read_text() == 'preserve'


def test_no_new_generator_fitter_metrics_import_as_evaluator_truth_or_hidden_polling():
    tree = ast.parse(Path(audit.__file__).read_text())
    forbidden = {'pallet.mask_quality_recovery','pallet.mask_quality_metrics','pallet.mask_boundary_fit'}
    for node in ast.walk(tree):
        assert not isinstance(node,ast.Assert)
        if isinstance(node,ast.ImportFrom):
            assert node.module not in forbidden
        if isinstance(node,ast.Import):
            assert not forbidden & {name.name for name in node.names}
        if isinstance(node,ast.Call) and isinstance(node.func,ast.Attribute):
            assert node.func.attr not in ('backup','save_review','save_annotation','sleep','unlink','rename','replace','rmtree')
            if node.func.attr == 'open' and node.args and isinstance(node.args[0],ast.Constant):
                assert node.args[0].value not in ('w','wb','a','ab','w+','r+')
    assert 'from scipy import ndimage' in Path(audit.__file__).read_text()


def test_parent_manifest_seal_and_new_code_policy_pins_are_explicit_and_not_self_selected():
    assert audit.PARENT_PINS == {
        'manifest.json':'eced4c61119ee63bef7f80e4ae92d76db3d28f3228daef049fa00ad5da69e487',
        'verification.json':'5165170284205283adfaa6514c65cc8126773f49be54ed6398f1dba55f321631'}
    assert set(audit.PUBLICATIONS) == set(range(3,16))
    assert audit.PUBLICATIONS[15] == 'pallet_mask_remaining_round5_v1'
    assert audit.NEW_CODE == ('pallet/mask_quality_recovery.py','pallet/mask_quality_metrics.py','pallet/mask_boundary_fit.py')
