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_cycle2_review import CycleEditor
from pallet.mask_taxonomy_cycle2_data import NAMESPACE
from pallet.mask_taxonomy_review import TaxonomyEditor


@pytest.fixture
def editor():
    key='a'*24;p=dict(target_key=key,class_id=1,K=4,polygon=[[5,5],[45,5],[45,30],[5,30]],source=dict(size=[60,40],box_index=1),checkpoint_sha256='new-model',original_formal_class_id=12)
    gallery=SimpleNamespace(manifest_sha256='cycle2-frozen-test',proposals={key:p},classes={'1':dict(train_enabled=True,K=4),'2':dict(train_enabled=True,K=8)})
    guard=SimpleNamespace(current=lambda:True)
    with tempfile.TemporaryDirectory(prefix='taxonomy-cycle2-',dir='/tmp/opencode') as directory:
        yield CycleEditor(gallery,directory+'/new','synthetic-credential-long-enough',guard),key,p,guard,gallery,directory


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


def test_new_epoch_cookie_and_store_are_not_old_epoch(editor):
    ed,key,p,guard,gallery,directory=editor
    old=TaxonomyEditor(gallery,directory+'/old','synthetic-credential-long-enough')
    assert ed.cookie_token!=old.cookie_token
    with ed.store.connect() as db:assert db.execute("SELECT value FROM metadata WHERE key='namespace'").fetchone()[0]==NAMESPACE
    assert ed.store.path!=old.store.path


def test_complete_save_and_atomic409_preserved(editor):
    ed,key,p,guard,gallery,directory=editor;value=ed.save(key,body(ed,p))
    assert value['action']=='correct' and value['class_id']==1 and not value['ground_truth_eligible']
    with pytest.raises(ReviewError) as e:ed.save(key,body(ed,p))
    assert e.value.status==409 and len(ed.store.history(key))==1


def test_K_mismatch_draft_only_and_source_change_blocks(editor):
    ed,key,p,guard,gallery,directory=editor;value=body(ed,p);value['class_id']=2
    with pytest.raises(ReviewError) as e:ed.save(key,value)
    assert e.value.status==400 and not ed.store.history(key)
    value['action']='draft';ed.save(key,value);guard.current=lambda:False
    assert not ed.detail(key)['source_current']
    value['expected_revision']=1
    with pytest.raises(ReviewError) as e:ed.save(key,value)
    assert e.value.status==409 and len(ed.store.history(key))==1


def test_export_uses_new_namespace_and_source_guard(editor):
    import json
    ed,key,p,guard,gallery,directory=editor;ed.save(key,body(ed,p));raw,mime,name=ed.export(key,'labelme.json');value=json.loads(raw)
    assert value['version']==NAMESPACE and value['shapes'][0]['points']==p['polygon'] and not value['training_eligible']
    guard.current=lambda:False
    with pytest.raises(ReviewError) as e:ed.export(key,'mask.png')
    assert e.value.status==409
