import pytest

from pallet.mask_taxonomy_data import parent_attributes, split_components


def test_main_beams_not_reinforcement():
    assert parent_attributes('2支腿，上横梁，金属，上加强筋，下加强筋') == dict(legs=2, beams=1, material='金属')
    assert parent_attributes('3支腿，上下横梁，木质，上横梁不平')['beams'] == 2


@pytest.mark.parametrize('text', ['上横梁，金属', '2支腿，金属', '2支腿，上横梁，金属，木质', '2支腿，3支腿，上横梁，塑料'])
def test_ambiguous_parent_rejected(text):
    with pytest.raises(ValueError): parent_attributes(text)


def test_component_split_keeps_cross_class_targets_together():
    records = [dict(target_key=str(i), component='component'+str(i//3)) for i in range(300)]
    split = split_components(records)
    for i in range(0,300,3): assert len({split[str(j)] for j in range(i,i+3)}) == 1
    assert set(split.values()) == {'train', 'holdout'}


def test_quota_is_per_fine_class_and_original_image_bytes():
    from pallet.mask_taxonomy_infer import select_quotas
    classes=[dict(class_id=c,K=k,parent='same-parent',small_sample=False) for c,k in ((1,4),(2,8))]
    predictions=[]
    for c in (1,2):
        for i in range(130):
            predictions.append(dict(target_key=f'{c}-{i}',candidate_class_id=c,classified_class_id=c,
                classification_gate_passed=True,geometry_gate_passed=True,image_sha256=f'{c}-{i//2}',component=str(i%4),fine_confidence=.99))
    selected,reports=select_quotas(predictions,classes)
    assert len(selected)==130 and reports['1']['selected_new_images']==65 and reports['2']['selected_new_images']==65
    assert reports['1']['gap']==reports['2']['gap']==35
    assert len({p['image_sha256'] for p in selected})==130


def test_low_confidence_or_failed_geometry_does_not_fill_quota():
    from pallet.mask_taxonomy_infer import select_quotas
    classes=[dict(class_id=147,K=8,parent='p',small_sample=True)]
    base=dict(target_key='a',candidate_class_id=147,classified_class_id=None,classification_gate_passed=False,
        geometry_gate_passed=True,image_sha256='new',component='g',fine_confidence=.2)
    selected,report=select_quotas([base],classes)
    assert not selected and report['147']['gap']==100


def test_parent_alone_is_not_fine_class_confidence():
    import numpy as np
    from pallet.mask_taxonomy_infer import classify
    classes=[dict(class_id=c,K=k,parent='parent',parent_index=0,small_sample=False) for c,k in ((1,4),(2,8))]
    parent=[dict(legs=2,beams=1,material='金属')]
    result=classify([.51,.49],[1.],[1.,0.],[[1.,0.],[0.,1.]],classes,[0,0,2],parent)
    assert result['classified_class_id'] is None and result['parent_confidence']==1
    assert len(result['fine_candidates'])==2 and result['fine_candidates'][1]['K']==8


@pytest.fixture
def editor(monkeypatch):
    import tempfile
    from types import SimpleNamespace
    import pallet.mask_taxonomy_review as review
    key='a'*24;proposal=dict(target_key=key,polygon=[[5,5],[45,5],[45,30],[5,30]],class_id=1,K=4,
        source=dict(size=[60,40]),checkpoint_sha256='checkpoint',original_formal_class_id=12)
    gallery=SimpleNamespace(manifest_sha256='unique-test-binding',proposals={key:proposal},
        classes={'1':dict(train_enabled=True,K=4),'2':dict(train_enabled=True,K=8),'37':dict(train_enabled=False,K=12)})
    monkeypatch.setattr(review,'sources_current',lambda:True)
    with tempfile.TemporaryDirectory(prefix='taxonomy-test-',dir='/tmp/opencode') as directory:
        yield review.TaxonomyEditor(gallery,directory,'synthetic-only-credential-12345'),key,proposal


def save_body(editor,key,p,**overrides):
    from pallet.mask_model_training_data import sha
    return dict(binding=editor.binding,source_binding=sha(p),expected_revision=0,class_id=1,polygon=p['polygon'],reviewer='SYNTHETIC',note='',action='correct',**overrides)


def test_empty_note_save_and_stale409_are_append_only(editor):
    from pallet.mask_gallery_review import ReviewError
    ed,key,p=editor;body=save_body(ed,key,p)
    saved=ed.save(key,body)
    assert saved['note']=='' and saved['revision']==1 and not saved['formal_class_or_polygon_written']
    with pytest.raises(ReviewError) as error:ed.save(key,body)
    assert error.value.status==409 and len(ed.store.history(key))==1


def test_changed_class_rechecks_actualK_and_draft_can_preserve_mismatch(editor):
    from pallet.mask_gallery_review import ReviewError
    ed,key,p=editor;body=save_body(ed,key,p);body['class_id']=2
    with pytest.raises(ReviewError) as error:ed.save(key,body)
    assert error.value.status==400 and not ed.store.history(key)
    body['action']='draft';saved=ed.save(key,body)
    assert saved['class_id']==2 and saved['expected_K']==8 and not saved['class_K_matches']


def test_new_source_blocks_save_without_discarding_history(editor,monkeypatch):
    import pallet.mask_taxonomy_review as review
    from pallet.mask_gallery_review import ReviewError
    ed,key,p=editor;body=save_body(ed,key,p);ed.save(key,body)
    monkeypatch.setattr(review,'sources_current',lambda:False);body['expected_revision']=1
    with pytest.raises(ReviewError) as error:ed.save(key,body)
    assert error.value.status==409 and len(ed.store.history(key))==1


def test_restore_is_new_revision_not_history_rewrite(editor):
    ed,key,p=editor;body=save_body(ed,key,p);old=ed.save(key,body)
    body.update(expected_revision=1,action='defer');ed.save(key,body)
    body.update(expected_revision=2,action='correct',restored_from_revision=1);restored=ed.save(key,body)
    assert restored['revision']==3 and restored['restored_from_revision']==1 and ed.store.history(key)[-1]==old
