from copy import deepcopy

import pytest

from scripts.summarize_pallet_dataset_stage_20261107 import attributes_for,geometry_changed,summarize,text_structure


@pytest.mark.parametrize('text,expected',[
    ('3支腿，上下横梁，木质，右支腿被部分遮挡',dict(legs=3,beams=2,material='木质')),
    ('2 支腿，上横梁，金属',dict(legs=2,beams=1,material='金属')),
    ('无法判断',{}),
    ('材质可能是木质或金属',{}),
])
def test_text_is_indexed_not_completed(text,expected):
    assert text_structure(text)==expected


def test_geometry_tolerance_and_vertex_count():
    polygon=[[0,0],[4,0],[4,2],[0,2]]
    tiny=deepcopy(polygon);tiny[1][0]+=5e-7
    actual=deepcopy(polygon);actual[1][0]+=.01
    assert not geometry_changed(polygon,tiny)
    assert geometry_changed(polygon,actual)
    assert geometry_changed(polygon,polygon[:3])


def test_parent_attributes_are_explicit_and_unknown_parent_rejected():
    assert attributes_for({'parent':'3legs-2beams-木质'})==dict(legs=3,beams=2,material='木质')
    with pytest.raises(ValueError):attributes_for({'parent':'unknown'})


def record(key,action,**changes):
    value=dict(target_key=key,mode='existing',class_id=1,class_parent='2legs-1beams-塑料',image_sha256='same-image',
        frame_id='same-frame',component='same-component',original_split='train',action=action,
        polygon=[[0,0],[4,0],[4,2],[0,2]],description=dict(legs=2,beams=1,material='塑料',observation=''))
    for field in ('has_review','class_changed','polygon_changed','polygon_exact_changed','vertex_count_changed',
        'description_text_changed','description_fields_changed','class_attribute_conflict','text_attribute_conflict','text_class_conflict',
        'invalid_polygon','wrong_K','blank_structure_text','observation_nonempty','structure_text_anomaly_hint','note_anomaly_hint',
        'any_anomaly_hint','attributes_unknown','new_joint_correct','text_batch_ever','attributes_batch_ever','geometry_previously_completed'):
        value[field]=False
    value.update(changes)
    return value


def test_targets_images_actions_and_conflict_origins_are_separate():
    rows=[record('a','never_saved',class_attribute_conflict=True),record('b','draft',has_review=True,structure_text_anomaly_hint=True,any_anomaly_hint=True)]
    report=summarize(rows)
    assert report['targets']==2 and report['unique_original_images']==1
    assert report['saved_actions']=={'never_saved':1,'draft':1}
    assert report['new_joint_correct']==0 and report['has_review']==1
    assert report['class_attribute_conflicts_by_action']=={'never_saved':1}
    assert report['never_saved_class_counts']=={1:1} and report['draft_class_counts']=={1:1}
    assert report['observation_nonempty']==0 and report['any_anomaly_hint']==1
    assert not any('normal_negative' in field for field in report)


def test_summary_does_not_mutate_descriptions_or_actions():
    rows=[record('a','draft')];before=deepcopy(rows)
    summarize(rows)
    assert rows==before
