from copy import deepcopy
from types import SimpleNamespace
import json
import math

import pytest

from pallet.mask_class_note_corrections import split_note,interpret_note,NoteEditor,sha
from pallet.mask_gallery_review import ReviewError


def poly(n):return [[50+30*math.cos(2*math.pi*i/n),40+25*math.sin(2*math.pi*i/n)] for i in range(n)]


def editor(tmp_path,kind='reannotate',initial=4,expected=12,sourceclass=12,targetclass=12):
    root=tmp_path/'package';root.mkdir();key='a'*24
    p=dict(target_key=key,source=dict(size=[100,80],frame_id='frame',box_index=0,split='train',bbox=dict(x=10,y=5,width=80,height=70)),
        polygon=poly(initial),source_polygon_sha256=sha(poly(initial)),original_class_id=1,class_id=sourceclass,actual_K=initial,face_id='face',source_revision=2,
        source_event_raw_sha256='rawhuman',image_sha256='image',class_graph_revision=421,kind=kind,expected_K=expected,target_class_id=targetclass,
        reference_classes=[],target_attributes_text='目标属性原文',class_note=dict(note_revision=367,note_event_raw_sha256='rawnote',full_review_note='3支腿，上横梁，木质\n注：需要重新标注为K12',attributes_text='3支腿，上横梁，木质'))
    gallery=SimpleNamespace(root=root,manifest_sha256='binding',tasks={key:p},dependencies=dict(human_source_fingerprints={},class_graph_revision=421),references={})
    e=NoteEditor(gallery,tmp_path/'independent-store','x'*32);e.source_current=lambda:True
    return e,key,p


def payload(e,key,**extra):
    return dict(binding=e.binding,source_binding=e.source_binding(key),proposal_id=sha(e.proposal(key)),expected_revision=0,
        reviewer='synthetic human',note='manual correction reason',action='draft',polygon=deepcopy(e.proposal(key)['polygon']),**extra)


@pytest.mark.parametrize('text,kind,expected,destination',[
    ('需要重新标注为K12','reannotate',12,12),('应当修改为K4后放置于Class14中','reannotate_and_move',4,14),
    ('应当重新标注为k8，放置于Class115','reannotate_and_move',8,115),
    ('异常标注数据，缺少一个支腿，应当被移除','exclude',None,None),
    ('一侧支腿被部分遮挡，导致比K16缺少2个关键点，对应Class9。','occlusion',16,9),
    ('相对Class9的区别为，支腿平面缺少填充，存在孔洞。','comparison_only',4,12)])
def test_interpret_actual_note_actions(text,kind,expected,destination):
    value=interpret_note(text,12,4);assert value['kind']==kind and value['expected_K']==expected and value['target_class_id']==destination


def test_only_explicit_note_marker_not_word_annotation_creates_issue():
    assert split_note('应当重新按照K12进行标注')['annotation']==''
    value=split_note('3支腿，上横梁，木质\n注：需要重新标注为K12')
    assert value['attributes_text']=='3支腿，上横梁，木质' and value['annotation']=='需要重新标注为K12'


def test_draft_allows_intermediate_K_but_cannot_export_completed_label(tmp_path):
    e,key,p=editor(tmp_path);saved=e.save(key,payload(e,key))
    assert saved['vertex_count']==4 and saved['effective_class_id'] is None and not saved['ground_truth_eligible']
    with pytest.raises(ReviewError):e.export(key,'labelme.json')
    assert not e.all_records(True)['records'] and len(e.all_records(False)['records'])==1


def test_wrong_K_completion_rejected_without_store_write(tmp_path):
    e,key,p=editor(tmp_path)
    with pytest.raises(ValueError):e.save(key,dict(payload(e,key),action='correct'))
    assert not e.store.summary()


@pytest.mark.parametrize('initial,expected,sourceclass,targetclass',[(4,12,12,12),(4,12,85,85),(5,4,108,14),(9,8,124,115)])
def test_completed_contour_sidecar_changes_label_only_after_required_K(tmp_path,initial,expected,sourceclass,targetclass):
    e,key,p=editor(tmp_path,kind='reannotate_and_move' if sourceclass!=targetclass else 'reannotate',initial=initial,expected=expected,sourceclass=sourceclass,targetclass=targetclass);before=deepcopy(p)
    saved=e.save(key,dict(payload(e,key),action='correct',polygon=poly(expected)))
    assert saved['effective_class_id']==targetclass and saved['vertex_count']==expected and p==before
    assert saved['source_attributes_text']==p['class_note']['attributes_text'] and not saved['old_class_graph_written'] and not saved['old_human_polygons_written']
    raw,mime,name=e.export(key,'labelme.json');value=json.loads(raw)
    assert value['shapes'][0]['label']==f'Class{targetclass}' and len(value['shapes'][0]['points'])==expected and value['no_automatic_dataset_integration']
    mask,mime,name=e.export(key,'mask.png');assert mask.startswith(b'\x89PNG')


def test_exclusion_is_explicit_sidecar_not_deletion_or_polygon_export(tmp_path):
    e,key,p=editor(tmp_path,kind='exclude',initial=12,expected=None,sourceclass=37,targetclass=None)
    with pytest.raises(ValueError):e.save(key,dict(payload(e,key),action='correct'))
    saved=e.save(key,dict(payload(e,key),action='exclude'))
    assert saved['effective_class_id'] is None and saved['exclusion_is_not_source_deletion'] and key in e.proposals
    assert len(e.all_records(True)['records'])==1
    with pytest.raises(ReviewError):e.export(key,'mask.png')


def test_other_classes_cannot_use_exclude_action(tmp_path):
    e,key,p=editor(tmp_path)
    with pytest.raises(ValueError):e.save(key,dict(payload(e,key),action='exclude'))


def test_occluded_K14_not_silently_merged_to_K16_Class9(tmp_path):
    e,key,p=editor(tmp_path,kind='occlusion',initial=14,expected=16,sourceclass=47,targetclass=9)
    with pytest.raises(ValueError):e.save(key,dict(payload(e,key),action='correct',polygon=poly(16)))
    value=e.save(key,dict(payload(e,key),action='occluded_deferred'))
    assert value['vertex_count']==14 and value['effective_class_id'] is None and value['status']=='occluded_points_not_invented'
    with pytest.raises(ValueError):e.save(key,dict(payload(e,key),expected_revision=1,action='correct',polygon=poly(14),all_points_observed=True))
    complete=e.save(key,dict(payload(e,key),expected_revision=1,action='correct',polygon=poly(16),all_points_observed=True))
    assert complete['effective_class_id']==9 and complete['vertex_count']==16


def test_source_change_blocks_save_and_exports_but_preserves_local_source_history(tmp_path):
    e,key,p=editor(tmp_path);e.save(key,payload(e,key));before=e.history(key);e.source_current=lambda:False
    with pytest.raises(ReviewError) as err:e.save(key,dict(payload(e,key),expected_revision=1))
    assert err.value.status==409
    with pytest.raises(ReviewError):e.all_records(False)
    with pytest.raises(ReviewError):e.export(key,'labelme.json')
    assert e.history(key)==before and e.detail(key)['proposal_dependency_stale']


def test_stale_revision_does_not_overwrite_and_restore_is_append_only(tmp_path):
    e,key,p=editor(tmp_path);first=e.save(key,payload(e,key))
    with pytest.raises(ReviewError) as err:e.save(key,payload(e,key))
    assert err.value.status==409
    e.save(key,dict(payload(e,key),expected_revision=1,action='correct',polygon=poly(12)))
    third=e.save(key,dict(payload(e,key),expected_revision=2,restored_from_revision=1,polygon=first['polygon']))
    assert third['revision']==3 and third['restored_from_revision']==1 and len(e.history(key))==3
    with pytest.raises(ValueError):e.save(key,dict(payload(e,key),expected_revision=3,restored_from_revision=999))


@pytest.mark.parametrize('field,value',[('binding','other'),('proposal_id','other'),('source_binding','other')])
def test_wrong_binding_is409(tmp_path,field,value):
    e,key,p=editor(tmp_path)
    with pytest.raises(ReviewError) as err:e.save(key,dict(payload(e,key),**{field:value}))
    assert err.value.status==409 and not e.store.summary()


def test_class_override_and_invalid_polygon_rejected(tmp_path):
    e,key,p=editor(tmp_path)
    with pytest.raises(ValueError):e.save(key,dict(payload(e,key),target_class_id=999))
    with pytest.raises(ValueError):e.save(key,dict(payload(e,key),polygon=[[0,0],[10,10],[0,10],[10,0]]))
    assert not e.store.summary()


def test_store_cannot_be_nested_inside_source_package(tmp_path):
    e,key,p=editor(tmp_path)
    with pytest.raises(ValueError):NoteEditor(e.gallery,e.gallery.root/'reviews','x'*32)


@pytest.mark.parametrize('action',['draft','correct','exclude','occluded_deferred','defer'])
@pytest.mark.parametrize('note_mode',['empty','omitted','whitespace'])
def test_note_optional_for_all_correction_actions(tmp_path,action,note_mode):
    kwargs=dict(kind='exclude',initial=12,expected=None,sourceclass=37,targetclass=None) if action=='exclude' else \
        dict(kind='occlusion',initial=14,expected=16,sourceclass=47,targetclass=9) if action=='occluded_deferred' else {}
    e,key,p=editor(tmp_path,**kwargs);data=payload(e,key);data['action']=action
    if action=='correct':data['polygon']=poly(12)
    if note_mode=='omitted':data.pop('note')
    else:data['note']='' if note_mode=='empty' else ' \n\t '
    saved=e.save(key,data)
    assert saved['note']=='' and saved['revision']==1 and saved['action']==action
    assert saved['source_full_review_note']==p['class_note']['full_review_note']
    assert e.history(key)[0]['note']==''


@pytest.mark.parametrize('note',[None,False,123,[],{},'字'*2001])
def test_optional_note_still_validates_type_and_length(tmp_path,note):
    e,key,p=editor(tmp_path)
    with pytest.raises(ValueError):e.save(key,dict(payload(e,key),note=note))
    assert not e.store.summary()
