import tempfile
from types import SimpleNamespace

import pytest

from pallet.mask_gallery_review import ReviewError
from pallet.mask_model_training_data import sha
from pallet.mask_taxonomy_review import TaxonomyEditor
from pallet.mask_taxonomy_fast_review import FastTaxonomyEditor


@pytest.fixture
def editors(monkeypatch):
    import pallet.mask_taxonomy_review as base
    monkeypatch.setattr(base,'sources_current',lambda:True)
    key='a'*24;p=dict(target_key=key,class_id=1,K=4,source=dict(size=[60,40]),polygon=[[5,5],[45,5],[45,30],[5,30]],checkpoint_sha256='model',original_formal_class_id=12)
    gallery=SimpleNamespace(manifest_sha256='frozen-test',proposals={key:p},classes={'1':dict(train_enabled=True,K=4),'2':dict(train_enabled=True,K=8)})
    with tempfile.TemporaryDirectory(dir='/tmp/opencode',prefix='fast-review-') as directory:
        old=TaxonomyEditor(gallery,directory+'/old','synthetic-only-access-credential')
        new=TaxonomyEditor(gallery,directory+'/new','synthetic-only-access-credential')
        guard=SimpleNamespace(current=lambda:True)
        yield old,FastTaxonomyEditor(new,guard),guard,key,p


def body(editor,p,action='correct'):
    return dict(binding=editor.binding,source_binding=sha(p),expected_revision=0,class_id=1,polygon=p['polygon'],reviewer='SYNTHETIC',note='',action=action)


@pytest.mark.parametrize('action',['correct','draft','defer'])
def test_saved_payload_matches_legacy_exactly(editors,action):
    old,new,guard,key,p=editors;a=old.save(key,body(old,p,action));b=new.save(key,body(new,p,action))
    a.pop('updated_at');b.pop('updated_at');assert a==b and old.cookie_token==new.cookie_token


def test_revision409_still_atomic_and_append_only(editors):
    old,new,guard,key,p=editors;value=body(new,p);new.save(key,value)
    with pytest.raises(ReviewError) as error:new.save(key,value)
    assert error.value.status==409 and len(new.store.history(key))==1


def test_source_change_blocks_detail_and_save_without_history_writes(editors):
    old,new,guard,key,p=editors;guard.current=lambda:False
    assert not new.detail(key)['source_current']
    with pytest.raises(ReviewError) as error:new.save(key,body(new,p))
    assert error.value.status==409 and not new.store.history(key)


def test_change_during_validation_checked_again_before_commit(editors):
    old,new,guard,key,p=editors;answers=iter([True,False]);guard.current=lambda:next(answers)
    with pytest.raises(ReviewError) as error:new.save(key,body(new,p))
    assert error.value.status==409 and not new.store.history(key)


def test_classK_check_and_draft_mismatch_preserved(editors):
    old,new,guard,key,p=editors;value=body(new,p);value['class_id']=2
    with pytest.raises(ReviewError) as error:new.save(key,value)
    assert error.value.status==400 and not new.store.history(key)
    value['action']='draft';saved=new.save(key,value)
    assert saved['expected_K']==8 and not saved['class_K_matches']
