from collections import Counter
from copy import deepcopy
from contextlib import closing
from pathlib import Path
from types import SimpleNamespace
import json

import numpy as np
import pytest

from pallet.mask_class_correction import majority_mapping,vote_units,outline,distance
from pallet.mask_class_correction_review import transition,initial_state,ClassReviewer
from pallet.mask_gallery_review import MaskReviewStore,ReviewError


def record(key,cls,k=4,unit=None):
    return dict(target_key=key,old_class_id=cls,actual_K=k,vote_unit=unit or key,polygon=[[0,0],[10,0],[10,5],[0,5]],image_sha256=key,
        row=dict(bbox=dict(x=0,y=0,width=10,height=5)))


def test_strict_whole_class_majority_not_sameK_subgroup():
    rs=[record('a'+str(i),9,16) for i in range(49)]+[record('b'+str(i),9,12) for i in range(47)]+[record('c'+str(i),9) for i in range(4)]
    a={r['target_key']:'K'+str(r['actual_K']) for r in rs};groups,_=majority_mapping(rs,a)
    assert all(not g['majority_anchors'] and g['proposed_class_id']>=23 for g in groups.values())
    assert groups['K16']['majority_support']['9']==dict(support=49.,denominator=100,fraction=.49)


def test_cross_class_sameK_not_automatically_merged():
    rs=[record('a'+str(i),1,8) for i in range(3)]+[record('b'+str(i),6,8) for i in range(3)]
    a={r['target_key']:'faceA' if r['old_class_id']==1 else 'faceB' for r in rs};groups,_=majority_mapping(rs,a)
    assert groups['faceA']['proposed_class_id']==1 and groups['faceB']['proposed_class_id']==6


def test_same_face_majority_in_two_classes_tie_requires_human():
    rs=[record(str(i),1 if i<3 else 2) for i in range(6)];a={r['target_key']:'one' for r in rs}
    gs,_=majority_mapping(rs,a);assert gs['one']['proposed_class_id'] is None and gs['one']['tied_majority_anchors']==[1,2]
    gs,_=majority_mapping(rs,a,anchor_choices={'one':2});assert gs['one']['proposed_class_id']==2
    with pytest.raises(ValueError):majority_mapping(rs,a,anchor_choices={'one':3})


def test_duplicate_samples_share_vote_not_overturn_majority():
    rs=[record('a',1,unit='dup'),record('b',1,unit='dup'),record('c',1,unit='unique')]
    gs,_=majority_mapping(rs,{'a':'A','b':'A','c':'B'});assert not gs['A']['majority_anchors']
    assert gs['A']['majority_support']['1']['fraction']==.5


def test_conflicting_duplicates_split_one_vote_never_cross_K_merge():
    rs=[record('a',1,4,'dup'),record('b',1,8,'dup')];gs,_=majority_mapping(rs,{'a':'A','b':'B'})
    assert gs['A']['majority_support']['1']['support']==.5
    with pytest.raises(ValueError):majority_mapping(rs,{'a':'A','b':'A'})


def test_vote_units_same_image_different_objects_are_distinct():
    a=record('a',1);b=record('b',1);c=record('c',2)
    for r in (a,b,c):r['image_sha256']='same'
    c['row']['bbox']['x']=50
    units=vote_units([a,b,c]);assert units['a']==units['b'] and units['a']!=units['c']


def sample_state():
    rs=[record('a',1),record('b',1),record('c',1),record('d',2,8)]
    return rs,dict(assignments={'a':'A','b':'A','c':'B','d':'D'},new_ids={},anchor_choices={},group_status={'A':'confirm'},reason='initial')


def test_merge_resets_confirmations_and_original_inputs_not_mutated():
    rs,state=sample_state();old=deepcopy(state)
    value=transition(rs,state,'merge',dict(face_id='B',destination_face='A',note='same visible fork face'))
    assert value['assignments']['c']=='A' and not value['group_status'] and state==old


def test_merge_and_move_differentK_rejected():
    rs,state=sample_state()
    for action in ('merge','move'):
        with pytest.raises(ValueError):transition(rs,state,action,dict(face_id='A',destination_face='D',target_keys=['a'],note='wrong'))


def test_split_never_changes_actual_polygons_and_class_ids():
    rs,state=sample_state();before=deepcopy(rs)
    value=transition(rs,state,'split',dict(face_id='A',target_keys=['a'],note='different face'))
    assert value['assignments']['a'].startswith('H4-') and rs==before and not value['group_status']
    with pytest.raises(ValueError):transition(rs,state,'split',dict(face_id='A',target_keys=['a','b'],note='all'))


def test_note_and_valid_selection_required():
    rs,state=sample_state()
    with pytest.raises(ValueError):transition(rs,state,'confirm',dict(face_id='A',note=''))
    with pytest.raises(ValueError):transition(rs,state,'split',dict(face_id='A',target_keys=['d'],note='bad'))


def test_distance_hardK_and_internal_image_structure_has_own_gate():
    p=np.array([[0,0],[10,0],[10,5],[0,5]])
    q,t,a=outline(p.tolist());left=(*outline(p.tolist()),np.array([1.,0.]));right=(*outline(p.tolist()),np.array([0.,1.]))
    assert distance(left,right)>1 and len(q)==4
    other=(np.zeros((8,2)),np.zeros(8),a,np.array([1.,0.]))
    assert distance(left,other)==float('inf')


def reviewer(tmp_path):
    rs,state=sample_state();root=tmp_path/'package';root.mkdir();(root/'assignments.json').write_text(json.dumps(state['assignments']))
    (root/'new_class_registry.json').write_text('{}');(root/'targets.json').write_text('[]')
    gallery=SimpleNamespace(root=root,manifest_sha256='binding',manifest=dict(source_records_sha256='source'),inputs=dict(source_fingerprints={}),records=rs)
    e=ClassReviewer(gallery,tmp_path/'temp-store','x'*32)
    return e,rs


def data(action='confirm',**extra):return dict(binding='binding',expected_revision=0,reviewer='synthetic test',note='manual reason',action=action,face_id='A',**extra)


def test_real_append_store_confirm_export_and_stale_conflict(tmp_path):
    e,_=reviewer(tmp_path);value=e.save(data());assert value['revision']==1
    with pytest.raises(ReviewError) as err:e.save(data())
    assert err.value.status==409 and len(e.store.history('class_graph'))==1
    confirmed=e.export(True);assert len(confirmed['records'])==2 and all(v['corrected_class_id']==1 for v in confirmed['records'])
    assert not value['old_classes_overwritten'] and not value['human_polygons_modified']


def test_restore_appends_and_source_change_blocks_save_and_export(tmp_path):
    e,_=reviewer(tmp_path);e.save(data());e.save(dict(data('defer'),expected_revision=1));third=e.save(dict(data('restore',restore_revision=1),expected_revision=2))
    assert third['revision']==3 and third['state']['group_status']['A']=='confirm' and third['restored_from_revision']==1
    e.sources_current=lambda:False
    with pytest.raises(ReviewError):e.save(dict(data(),expected_revision=3))
    with pytest.raises(ReviewError):e.export(True)
    assert len(e.store.history('class_graph'))==3


def test_unknown_class_id_cannot_bypass_majority_rule(tmp_path):
    e,_=reviewer(tmp_path)
    with pytest.raises(ValueError):e.save(data('anchor',class_id=999))
    assert not e.store.summary()


def test_full_history_and_restore_older_than_default_store_limit(tmp_path):
    e,_=reviewer(tmp_path)
    for revision in range(55):e.save(dict(data('confirm' if revision==0 else 'defer'),expected_revision=revision))
    assert len(e.store.history('class_graph'))==50
    assert [r['revision'] for r in e.get()['history']]==list(range(55,0,-1))
    restored=e.save(dict(data('restore',restore_revision=1),expected_revision=55))
    assert restored['revision']==56 and restored['state']['group_status']['A']=='confirm'
    assert len(e.history())==56 and e.history()[-1]['revision']==1


def test_csv_exports_auth_scope_and_source_conflict(tmp_path):
    import csv
    import io
    import threading
    from http.server import ThreadingHTTPServer
    from urllib.error import HTTPError
    from urllib.request import Request,urlopen
    from pallet.mask_class_correction_review import ClassHandler
    from pallet.mask_gallery_review import COOKIE

    e,_=reviewer(tmp_path);e.gallery.editor=e;e.gallery.csp="default-src 'none'"
    class QuietHandler(ClassHandler):
        def log_message(self,*args):pass
    server=ThreadingHTTPServer(('127.0.0.1',0),QuietHandler);server.gallery=e.gallery;server.daemon_threads=True
    worker=threading.Thread(target=server.serve_forever,daemon=True);worker.start()
    def get(name,auth=True):
        return urlopen(Request(f'http://127.0.0.1:{server.server_port}/api/review/export/'+name,
            headers={'Cookie':f'{COOKIE}={e.cookie_token}'} if auth else {}),timeout=10)
    try:
        with pytest.raises(HTTPError) as err:get('proposals.csv',False)
        assert err.value.code==401
        with get('confirmed.csv') as response:
            assert response.headers['Content-Type']=='text/csv; charset=utf-8'
            assert response.headers['Content-Disposition'].startswith('attachment;')
            assert not list(csv.DictReader(io.StringIO(response.read().decode('utf-8-sig'))))
        e.save(data())
        with get('confirmed.csv') as response:rows=list(csv.DictReader(io.StringIO(response.read().decode('utf-8-sig'))))
        assert len(rows)==2 and all(r['corrected_class_id']=='1' and r['effective_label_is_human_confirmed']=='True' for r in rows)
        with get('proposals.csv') as response:rows=list(csv.DictReader(io.StringIO(response.read().decode('utf-8-sig'))))
        assert len(rows)==4 and sum(bool(r['corrected_class_id']) for r in rows)==2
        e.sources_current=lambda:False
        for name in ('confirmed.csv','confirmed.json'):
            with pytest.raises(HTTPError) as err:get(name)
            assert err.value.code==409
        with get('proposals.csv') as response:assert response.status==200
        assert len(e.history())==1
    finally:server.shutdown();server.server_close();worker.join()


def class_move_sample():
    rs=[record('a',1),record('b',1),record('c',2),record('d',2),record('e',3,8)]
    state=dict(assignments={'a':'A','b':'A','c':'B','d':'B','e':'C'},new_ids={},anchor_choices={},group_status={'A':'confirm','B':'confirm'},reason='initial')
    return rs,state


def test_move_selected_targets_by_class_preserves_other_targets_and_original_data():
    rs,state=class_move_sample();original=deepcopy((rs,state))
    value=transition(rs,state,'move_class',dict(face_id='A',target_keys=['a'],destination_class_id=2,note='human compared same fork face'))
    assert value['assignments']=={'a':'B','b':'A','c':'B','d':'B','e':'C'}
    assert not value['group_status'] and (rs,state)==original
    from pallet.mask_class_correction_review import compute
    groups,_=compute(rs,value);assert groups['B']['proposed_class_id']==2 and groups['B']['majority_support']['1']['denominator']==2


@pytest.mark.parametrize('cls',[None,True,'2',0,-1,999,1,3])
def test_move_class_rejects_unknown_invalid_same_group_or_crossK(cls):
    rs,state=class_move_sample();original=deepcopy(state)
    with pytest.raises(ValueError):transition(rs,state,'move_class',dict(face_id='A',target_keys=['a'],destination_class_id=cls,note='invalid destination'))
    assert state==original


def test_move_class_cannot_silently_change_requested_class_after_revote():
    rs=[record('a'+str(i),1) for i in range(5)]+[record('b',2)]
    state=dict(assignments={r['target_key']:'A' if r['old_class_id']==1 else 'B' for r in rs},new_ids={},anchor_choices={},group_status={},reason='initial')
    with pytest.raises(ValueError,match='改变目标Class'):
        transition(rs,state,'move_class',dict(face_id='A',target_keys=['a0','a1','a2'],destination_class_id=2,note='would change destination winner'))


def test_move_class_can_resolve_revote_tie_as_explicit_requested_class():
    rs=[record('a',1),record('b',2)]
    state=dict(assignments={'a':'A','b':'B'},new_ids={},anchor_choices={},group_status={},reason='initial')
    value=transition(rs,state,'move_class',dict(face_id='A',target_keys=['a'],destination_class_id=2,note='explicit keep class2 in tie'))
    assert value['anchor_choices']=={'B':2} and value['assignments']=={'a':'B','b':'B'}


def test_move_class_save_is_append_only_and_retains_requested_destination(tmp_path):
    e,_=reviewer(tmp_path);rs,state=class_move_sample();e.gallery.records=rs
    (e.gallery.root/'assignments.json').write_text(json.dumps(state['assignments']))
    saved=e.save(data('move_class',target_keys=['a'],destination_class_id=2))
    assert saved['revision']==1 and saved['requested_destination_class_id']==2 and saved['selected_target_keys']==['a']
    assert not e.export(True)['records']
    with pytest.raises(ReviewError) as err:e.save(data('move_class',target_keys=['b'],destination_class_id=2))
    assert err.value.status==409 and len(e.history())==1
    e.save(dict(data('restore',restore_revision=1),expected_revision=1));assert len(e.history())==2


def test_lightweight_version_follows_graph_without_writing_events(tmp_path):
    e,_=reviewer(tmp_path)
    assert e.version()==dict(binding='binding',revision=0) and not e.history()
    e.save(data());e.save(dict(data('defer'),expected_revision=1))
    for _ in range(3):assert e.version()==dict(binding='binding',revision=2)
    assert len(e.history())==2


@pytest.mark.parametrize('action,extra',[
    ('split',dict(target_keys=['a'])),('merge',dict(destination_face='B')),
    ('move',dict(target_keys=['a'],destination_face='B')),('move_class',dict(target_keys=['a'],destination_class_id=2))])
def test_topology_preserves_unaffected_confirmations(action,extra):
    rs,state=class_move_sample();state['group_status']['C']='confirm'
    value=transition(rs,state,action,dict(face_id='A',note='only A/B edited',**extra))
    assert value['group_status']['C']=='confirm' and 'A' not in value['group_status']
    if action!='split':assert 'B' not in value['group_status']
    else:assert value['group_status']['B']=='confirm'


def test_indirect_duplicate_vote_evidence_change_invalidates_untouched_group():
    rs=[record('a',1,unit='dup'),record('b',1,unit='dup'),record('c',1,unit='dup'),record('d',1)]
    state=dict(assignments={'a':'A','b':'B','c':'B','d':'C'},new_ids={},anchor_choices={},group_status={'A':'confirm'},reason='initial')
    value=transition(rs,state,'move',dict(face_id='B',target_keys=['b'],destination_face='C',note='duplicate now shared by three groups'))
    assert value['assignments']['a']=='A' and 'A' not in value['group_status']


def test_unrelated_topology_keeps_explicit_tie_choice_and_confirmation():
    rs=[record('a',1),record('b',2),record('c',3,8),record('d',3,8)]
    state=dict(assignments={'a':'A','b':'A','c':'C','d':'C'},new_ids={},anchor_choices={'A':2},group_status={'A':'confirm'},reason='initial')
    value=transition(rs,state,'split',dict(face_id='C',target_keys=['c'],note='unrelated K8 split'))
    assert value['anchor_choices']=={'A':2} and value['group_status']=={'A':'confirm'}


def history_event(revision,action,state):
    return dict(revision=revision,action=action,state=deepcopy(state),reviewer='original human',updated_at='2026-10-29T00:00:00Z')


def test_recovery_only_carries_continuously_unchanged_original_confirmations():
    from pallet.mask_class_correction_review import recoverable_confirmations
    rs,state=class_move_sample();state['group_status']={'C':'confirm'}
    changed=transition(rs,state,'split',dict(face_id='A',target_keys=['a'],note='historical unrelated split'));changed['group_status']={}
    history=[history_event(1,'confirm',state),history_event(2,'split',changed)]
    result=recoverable_confirmations(rs,history,changed)
    assert set(result)=={'C'} and result['C']['source_revision']==1 and result['C']['class_id']==3


@pytest.mark.parametrize('later_action',['defer','reject','restore'])
def test_recovery_does_not_override_later_explicit_decision(later_action):
    from pallet.mask_class_correction_review import recoverable_confirmations
    rs,state=class_move_sample();state['group_status']={'C':'confirm'}
    cleared=deepcopy(state);cleared['group_status']={}
    later=deepcopy(cleared)
    if later_action!='restore':later['group_status']={'C':later_action}
    assert not recoverable_confirmations(rs,[history_event(1,'confirm',state),history_event(2,'split',cleared),history_event(3,later_action,later)],later)


def test_recovery_does_not_revive_changed_then_returned_group():
    from pallet.mask_class_correction_review import recoverable_confirmations
    rs,state=class_move_sample();state['group_status']={'A':'confirm'}
    changed=transition(rs,state,'move',dict(face_id='A',target_keys=['a'],destination_face='B',note='changed membership'))
    returned=deepcopy(state);returned['group_status']={}
    assert not recoverable_confirmations(rs,[history_event(1,'confirm',state),history_event(2,'move',changed),history_event(3,'move',returned)],returned)


def test_recovery_append_preserves_graph_and_original_events_and_conflicts(tmp_path):
    e,_=reviewer(tmp_path);e.save(data())
    state=e.store.get('class_graph')['state'];state['group_status']={}
    e.store.save('class_graph',1,dict(state=state,reviewer='old implementation',note='legacy unrelated edit cleared all',action='split'))
    old=e.history();original=deepcopy(state)
    value=e.recover_confirmations(2)
    assert value['revision']==3 and value['state']['group_status']=={'A':'confirm'}
    assert value['recovered_confirmations']['A']['source_revision']==1 and not value['new_semantic_confirmations']
    for field in ('assignments','anchor_choices','new_ids'):assert value['state'][field]==original[field]
    assert e.history()[1:]==old and len(e.export(True)['records'])==2
    with pytest.raises(ReviewError):e.recover_confirmations(2)
    with pytest.raises(ValueError):e.recover_confirmations(3)
    e.sources_current=lambda:False
    with pytest.raises(ReviewError):e.recover_confirmations(3)


def test_confirmed_read_and_new_reviewer_reload_do_not_write_or_lose_status(tmp_path):
    e,_=reviewer(tmp_path);e.save(data());old=e.history()
    reloaded=ClassReviewer(e.gallery,tmp_path/'temp-store','x'*32)
    for _ in range(3):assert reloaded.get()['groups']['A']['review_status']=='confirm'
    assert reloaded.history()==old and len(reloaded.export(True)['records'])==2


def reuse_sample():
    rs=[record('a',2),record('b',2),record('c',2),record('d',2),record('e',3,8)]
    state=dict(assignments={'a':'A','b':'A','c':'B','d':'C','e':'D'},new_ids={},anchor_choices={},group_status={'A':'confirm','D':'confirm'},reason='initial')
    return rs,state


def test_reuse_old_class_is_manual_whole_group_not_retain_and_preserves_votes():
    from pallet.mask_class_correction_review import compute
    rs,state=reuse_sample();before,_=compute(rs,state);original=deepcopy((rs,state))
    value=transition(rs,state,'reuse_old_class',dict(face_id='A',destination_class_id=2,note='human compared oldClass2 samples',target_keys=['a']))
    groups,_=compute(rs,value)
    assert groups['A']['proposed_class_id']==2 and groups['A']['decision']=='manual_old_class_assignment'
    assert groups['A']['majority_proposed_class_id']==before['A']['proposed_class_id']>=23
    assert groups['A']['majority_support']==before['A']['majority_support'] and not groups['A']['majority_anchors']
    assert value['assignments']==state['assignments'] and value['group_status']=={'D':'confirm'}
    assert groups['A']['targets']==2 and value['manual_class_choices']['A']['class_id']==2 and (rs,state)==original


@pytest.mark.parametrize('cls',[None,True,'2',0,-1,23,999,3])
def test_reuse_old_class_rejects_invalid_or_incompatible_target(cls):
    rs,state=reuse_sample()
    with pytest.raises(ValueError):transition(rs,state,'reuse_old_class',dict(face_id='A',destination_class_id=cls,note='invalid'))


def test_reuse_old_class_cannot_override_strict_majority_or_duplicate_owner():
    rs,state=class_move_sample()
    with pytest.raises(ValueError,match='严格过半'):transition(rs,state,'reuse_old_class',dict(face_id='A',destination_class_id=2,note='must not override majority'))
    rs,state=reuse_sample();value=transition(rs,state,'reuse_old_class',dict(face_id='A',destination_class_id=2,note='human choice'))
    with pytest.raises(ValueError):transition(rs,value,'reuse_old_class',dict(face_id='B',destination_class_id=2,note='Class already owned'))


def test_reuse_cannot_put_two_different_K_groups_into_same_old_class():
    rs=[record('a',9,4),record('b',9,8)]
    state=dict(assignments={'a':'A','b':'B'},new_ids={},anchor_choices={},group_status={},reason='initial')
    value=transition(rs,state,'reuse_old_class',dict(face_id='A',destination_class_id=9,note='oldClass9 K4'))
    with pytest.raises(ValueError):transition(rs,value,'reuse_old_class',dict(face_id='B',destination_class_id=9,note='K8 cannot share Class9'))


def test_topology_keeps_manual_group_label_but_requires_reconfirmation():
    from pallet.mask_class_correction_review import compute
    rs,state=reuse_sample();state=transition(rs,state,'reuse_old_class',dict(face_id='A',destination_class_id=2,note='manual oldClass2'))
    state=transition(rs,state,'confirm',dict(face_id='A',note='checked all members'))
    # Moving a different duplicate-free member out leaves a no-majority group;
    # its chosen Class remains a pending suggestion, not silently confirmed.
    moved=transition(rs,state,'move',dict(face_id='A',target_keys=['a'],destination_face='B',note='different face found'))
    groups,_=compute(rs,moved)
    assert groups['A']['proposed_class_id']==2 and 'A' not in moved['group_status'] and moved['group_status']['D']=='confirm'


def test_real_majority_after_edit_supersedes_manual_choice():
    from pallet.mask_class_correction_review import compute
    rs,state=reuse_sample();state=transition(rs,state,'reuse_old_class',dict(face_id='A',destination_class_id=2,note='manual oldClass2'))
    state=transition(rs,state,'confirm',dict(face_id='A',note='checked'))
    moved=transition(rs,state,'merge',dict(face_id='B',destination_face='A',note='same face, now true majority'))
    groups,_=compute(rs,moved)
    assert groups['A']['proposed_class_id']==2 and groups['A']['decision']=='retain_majority_class'
    assert 'A' not in moved['manual_class_choices'] and 'A' not in moved['group_status'] and moved['group_status']['D']=='confirm'


def test_reuse_save_reload_confirm_exports_and_restore_append_only(tmp_path):
    from pallet.mask_class_correction_review import compute
    e,_=reviewer(tmp_path);rs,state=reuse_sample();e.gallery.records=rs
    (e.gallery.root/'assignments.json').write_text(json.dumps(state['assignments']))
    e.save(data('defer'))
    saved=e.save(dict(data('reuse_old_class',destination_class_id=2),expected_revision=1))
    assert saved['whole_face_group'] and not saved['majority_rule_overridden'] and saved['assignment_method']=='manual_old_class_assignment'
    assert not e.export(True)['records']
    e.save(dict(data('confirm'),expected_revision=2));reloaded=ClassReviewer(e.gallery,tmp_path/'temp-store','x'*32)
    rows=reloaded.export(True)['records'];assert len(rows)==2 and all(r['corrected_class_id']==2 and r['class_assignment_method']=='manual_old_class_assignment' and r['majority_proposed_class_id']>=23 for r in rows)
    with pytest.raises(ReviewError):reloaded.save(data('reuse_old_class',destination_class_id=2))
    e.save(dict(data('restore',restore_revision=1),expected_revision=3))
    assert e.get()['groups']['A']['proposed_class_id']>=23 and len(e.history())==4
    assert e.history()[2]['action']=='reuse_old_class'


def test_forged_manual_choice_with_majority_or_duplicate_owner_is_rejected():
    from pallet.mask_class_correction_review import compute
    rs,state=reuse_sample();state['manual_class_choices']={'A':dict(class_id=2,K=4,reason='human'),'B':dict(class_id=2,K=4,reason='human')}
    with pytest.raises(ValueError):compute(rs,state)
    rs,state=class_move_sample();state['manual_class_choices']={'A':dict(class_id=1,K=4,reason='forged')}
    with pytest.raises(ValueError):compute(rs,state)


def test_unrelated_topology_preserves_manual_class_after_other_group_tie_resolution():
    from pallet.mask_class_correction_review import compute
    # The tied A group explicitly kept Class1, leaving Class2 free for B.
    # An unrelated edit must restore A's valid tie choice before checking
    # whether B's manually assigned Class2 has become occupied.
    rs=[record('a',1),record('b',2),record('x',2,unit='shared'),record('y',4),record('z',4),record('c',3,8),record('d',3,8)]
    rs[1]['vote_unit']='shared'
    state=dict(assignments={'a':'A','b':'A','x':'A','y':'B','z':'C','c':'D','d':'D'},new_ids={},anchor_choices={'A':1},group_status={},reason='initial')
    state=transition(rs,state,'reuse_old_class',dict(face_id='B',destination_class_id=2,note='old2 no longer retained because tied group chose old1'))
    state=transition(rs,state,'confirm',dict(face_id='B',note='manual old2 checked'))
    moved=transition(rs,state,'split',dict(face_id='D',target_keys=['c'],note='unrelated K8 edit'))
    groups,_=compute(rs,moved)
    assert moved['anchor_choices']=={'A':1} and groups['B']['proposed_class_id']==2 and moved['group_status']['B']=='confirm'
