from copy import deepcopy
import math

import pytest

from pallet.mask_class_note_integration import plan,sha,AUTHORIZATION


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


def fixture():
    records=[]
    for key,cls,k in [('a',1,4),('b',1,4),('c',2,4),('d',3,8)]:
        records.append(dict(target_key=key,old_class_id=cls,actual_K=k,vote_unit=key,polygon=polygon(k),source_revision=1,source_event_raw_sha256='oldraw',
            row=dict(size=[100,80],bbox=dict(x=20,y=15,width=60,height=50)),image_sha256='original'))
    state=dict(assignments={'a':'A','b':'A','c':'B','d':'C'},new_ids={},anchor_choices={},manual_class_choices={},group_status={'A':'confirm','B':'confirm','C':'confirm'},reason='human source')
    tasks={};saved={}
    for r in records[:2]:
        key=r['target_key'];p=dict(target_key=key,polygon=r['polygon'],source=r['row'],class_id=1,actual_K=4,expected_K=12,target_class_id=1,face_id='A',kind='reannotate',class_note=dict(note_revision=10,full_review_note='attrs\n注：改K12',annotation='改K12'))
        tasks[key]=p;saved[key]=dict(source_binding=sha(p),base_proposal_id=sha(p),source_class_graph_revision=421,source_class_id=1,requested_target_class_id=1,effective_class_id=None,
            action='draft',polygon=polygon(12),vertex_count=12,revision=1)
    graph=dict(state=state,revision=421,authorization=AUTHORIZATION,note_raw_hashes={key:'newraw' for key in saved})
    return records,graph,saved,tasks


def test_user_authorized_all_saved_group_K_migration_preserves_originals_and_draft_status():
    records,graph,saved,tasks=fixture();before=deepcopy((records,graph,saved,tasks))
    new,state,groups,imported,unresolved=plan(records,graph,saved,tasks)
    assert groups['A']['K']==12 and groups['A']['proposed_class_id']==1 and state['group_status']==graph['state']['group_status']
    assert all(p['note_original_action']=='draft' and p['completion_basis']=='explicit_user_completed_annotations_integration_request' for p in imported.values())
    assert new[2:]==records[2:] and (records,graph,saved,tasks)==before and not unresolved


def test_draft_K_match_without_explicit_user_authorization_does_not_complete():
    records,graph,saved,tasks=fixture();graph['authorization']='automatic because K matches'
    with pytest.raises(ValueError):plan(records,graph,saved,tasks)


def test_partial_class_K_migration_rejected_instead_of_mixing_K():
    records,graph,saved,tasks=fixture();saved.pop('b')
    with pytest.raises(ValueError,match='mixed-K'):plan(records,graph,saved,tasks)


def test_unresolved_other_class_is_retained_not_excluded_or_padded():
    records,graph,saved,tasks=fixture();r=records[-1]
    tasks['d']=dict(target_key='d',polygon=r['polygon'],source=r['row'],class_id=3,actual_K=8,expected_K=16,target_class_id=9,face_id='C',kind='occlusion',class_note=dict(annotation='遮挡'))
    new,state,groups,imported,unresolved=plan(records,graph,saved,tasks)
    assert new[-1]==r and groups['C']['K']==8 and unresolved['d']['action']=='unsaved' and 'd' not in imported


@pytest.mark.parametrize('field,value',[('source_binding','wrong'),('requested_target_class_id',999),('source_class_graph_revision',422),('effective_class_id',1),('vertex_count',11)])
def test_wrong_save_provenance_or_action_rejected(field,value):
    records,graph,saved,tasks=fixture();saved['a'][field]=value
    with pytest.raises(ValueError):plan(records,graph,saved,tasks)


def test_explicit_correct_save_retains_its_original_completion_basis():
    records,graph,saved,tasks=fixture();saved['a'].update(action='correct',effective_class_id=1)
    _,_,_,imported,_=plan(records,graph,saved,tasks)
    assert imported['a']['note_original_action']=='correct' and imported['a']['completion_basis']=='existing_explicit_correct_save'


def test_target_reassignment_applies_only_after_human_saved_compatible_K():
    records,graph,saved,tasks=fixture()
    for key in ('e','f'):
        r=deepcopy(records[2]);r.update(target_key=key,vote_unit=key);records.append(r);graph['state']['assignments'][key]='B'
    # All A members become K4 Class2, so A retires without any mixedK group.
    for key in tasks:
        tasks[key].update(expected_K=4,target_class_id=2,kind='reannotate_and_move')
        saved[key].update(polygon=[[20,20],[85,20],[85,65],[20,65]],vertex_count=4,requested_target_class_id=2,source_binding=sha(tasks[key]),base_proposal_id=sha(tasks[key]))
    _,state,groups,imported,_=plan(records,graph,saved,tasks)
    assert 'A' not in groups and groups['B']['targets']==5 and state['assignments']['a']=='B'
    assert imported['a']['destination_class_id']==2


def test_initial_human_confirmation_is_not_inferred_when_missing():
    records,graph,saved,tasks=fixture();graph['state']['group_status'].pop('B')
    with pytest.raises(ValueError):plan(records,graph,saved,tasks)
