from copy import deepcopy

from pallet.pallet_description_round4_data import canonical_classes,observation_text,semantic_record


def info():
    return dict(class_id=1,parent='3legs-2beams-木质',train_enabled=True,K=4,targets=1,distinct_images=1)


def row(**changes):
    r=dict(target_key='k',class_id=1,image='i',source={},image_sha256='h',component='c',evaluation_branch_split='train',
        original_review_action='draft',original_human_note='',description=dict(text='3支腿，上下横梁，木质',legs=3,beams=2,material='木质',observation=''))
    r.update(changes);return r


def test_alias_keeps_source_and_reindexes_only_new_taxonomy():
    source={'1':info(),'148':{**info(),'class_id':148},'149':{**info(),'class_id':149}}
    before=deepcopy(source);rs=[dict(class_id=1,image_sha256='a'),dict(class_id=148,image_sha256='b')]
    updated=canonical_classes(source,rs)
    assert source==before and not updated['149']['train_enabled'] and updated['149']['merged_into']==148
    assert updated['1']['fine_index']==0 and updated['148']['fine_index']==1


def test_observation_suffix_is_exact_not_keyword_gt():
    d=row()['description'];d['text']+='，右侧支腿被遮挡，视角偏斜'
    value,source=observation_text(d,True)
    assert value=='右侧支腿被遮挡，视角偏斜' and value in d['text']
    assert observation_text(d,False)[0] is None


def test_blank_observation_is_not_supervised_normal():
    r=semantic_record(row(),info(),{'text','legs','beams','material','observation'})
    assert r['target']['观察'] is None and not r['supervised_fields']['观察'] and not r['missing_observation_is_normal']


def test_conflict_masks_attribute_without_template_overwrite():
    r=row();r['description']['legs']=2;before=deepcopy(r)
    result=semantic_record(r,info(),{'text','legs','beams','material'})
    assert result['target']['支腿']==2 and not result['supervised_fields']['支腿']
    assert result['supervised_fields']['横梁'] and result['supervised_fields']['结构']
    assert r==before and 'legs' in result['semantic_conflicts']


def test_unsaved_model_initialization_not_human_semantic_target():
    result=semantic_record(row(original_review_action='never_saved'),info(),set())
    assert not any(result['supervised_fields'].values())


def test_batch_text_does_not_confirm_other_attributes():
    result=semantic_record(row(),info(),{'text'})
    assert result['supervised_fields']['结构'] and not result['supervised_fields']['材质']


def test_new_serving_namespace_does_not_rebind_frozen_source_discovery():
    from pallet import pallet_description_review as review
    from pallet import pallet_description_round4_data as data
    from pallet.pallet_description_round4_release import bind_review_sets
    previous=review.SETS;source=data.SETS;before=deepcopy(source)
    try:
        bind_review_sets()
        assert review.SETS is not source and data.SETS==before
        assert all('round3_' in str(s['reviews']) for s in data.SETS.values())
        assert all('round4_' in str(s['reviews']) for s in review.SETS.values())
    finally:review.SETS=previous


def test_json_spans_cover_values_not_delimiters():
    from pallet.pallet_description_round4_vlm import answer_spans,parse
    target={'支腿':3,'横梁':2,'材质':'木质','结构':'含"引号"，遮挡','观察':None}
    text,spans=answer_spans(target)
    assert parse(text)['valid']
    assert text[slice(*spans['观察'])]=='null'
    assert text[slice(*spans['结构'])]=='"含\\"引号\\"，遮挡"'
    assert text[spans['观察'][1]]=='}'


def test_strict_vlm_parser_rejects_booleans_and_missing_keys():
    from pallet.pallet_description_round4_vlm import parse
    assert not parse('{"支腿":true,"横梁":1,"材质":"金属","结构":"","观察":null}')['valid']
    assert not parse('{"支腿":3,"横梁":1,"材质":"金属","结构":""}')['valid']
    assert not parse('```json\n{"支腿":3,"横梁":1,"材质":"金属","结构":"","观察":null}\n```')['valid']


def test_batched_label_mask_preserves_eos_and_prompt_padding(monkeypatch):
    import torch
    from pallet import pallet_description_round4_vlm as vlm
    class Data(dict):
        def to(self,*args):return self
    class Tokenizer:
        def __call__(self,text,**kwargs):
            return dict(input_ids=[ord(c) for c in text],offset_mapping=[(i,i+1) for i in range(len(text))])
    class Processor:
        tokenizer=Tokenizer()
        def apply_chat_template(self,msg,**kwargs):
            return 'PROMPT'+(msg[1]['content'][0]['text']+'!' if len(msg)>1 else '')
        def __call__(self,text,**kwargs):
            width=max(map(len,text));ids=torch.zeros((len(text),width),dtype=torch.long);attention=ids.clone()
            for i,t in enumerate(text):ids[i,:len(t)]=torch.tensor([ord(c) for c in t]);attention[i,:len(t)]=1
            return Data(input_ids=ids,attention_mask=attention)
    monkeypatch.setattr(vlm,'image_for',lambda r:None)
    monkeypatch.setattr(torch.Tensor,'to',lambda self,*args,**kwargs:self)
    r=semantic_record(row(),info(),{'text','legs','beams','material'})
    r2=deepcopy(r);r2['target_key']='second';r2['target']['结构']='短';r2['supervised_fields']['支腿']=False
    full,labels,audits=vlm.training_batch(Processor(),[r,r2])
    for j,record in enumerate((r,r2)):
        text,spans=vlm.answer_spans(record['target'])
        assert (labels[j,:6]==-100).all()
        for key,(start,end) in spans.items():
            if not record['supervised_fields'][key]:assert (labels[j,6+start:6+end]==-100).all()
        assert labels[j,6+len(text)-1]==ord('}') and labels[j,6+len(text)]==ord('!')
        assert (labels[j,full['attention_mask'][j]==0]==-100).all()
        assert audits[j]['eos_supervised']
