from contextlib import closing
from copy import deepcopy
import sqlite3

import pytest

from pallet.mask_gallery_review import ReviewError
from pallet.pallet_description_batch import preview,apply
from pallet.pallet_description_attributes import validate_attributes
from test_pallet_description import editor,item,body
from test_pallet_description_batch import batch,confirmed


@pytest.fixture
def attributes_batch(batch):
    ed,p,guard,data=batch;data.pop('text');data.pop('reviewer');data['attributes']=dict(legs=4,beams=2,material='木质')
    return ed,p,guard,data


def request(ed,data):return dict(data,preview_token=preview(ed,data,'attributes')['preview_token'])


@pytest.mark.parametrize('legs',[None,2,3,4])
@pytest.mark.parametrize('beams',[None,1,2])
def test_supported_counts_including_unknown(legs,beams):
    assert validate_attributes(dict(legs=legs,beams=beams,material='无法判断'))==dict(legs=legs,beams=beams,material='无法判断')


@pytest.mark.parametrize('value',[None,[],{},dict(legs=True,beams=1,material='木质'),dict(legs=2,beams=False,material='木质'),
    dict(legs='3',beams=1,material='木质'),dict(legs=5,beams=1,material='木质'),dict(legs=2,beams=3,material='木质'),
    dict(legs=2,beams=1,material=None),dict(legs=2,beams=1,material='steel'),dict(legs=2,beams=1,material=[]),
    dict(legs=2,beams=1,material='木质',text='不可覆盖')])
def test_invalid_attributes_rejected(value):
    with pytest.raises(ReviewError):validate_attributes(value)


def test_preview_is_readonly_and_reports_exact_values(attributes_batch):
    ed,p,_,data=attributes_batch;result=preview(ed,data,'attributes')
    assert result['count']==2 and result['attributes']==data['attributes'] and result['attributes_only'] and not result['text_only']
    assert not ed.store.summary()
    with closing(ed.store.connect()) as db:assert not db.execute("SELECT name FROM sqlite_master WHERE name='structure_batches'").fetchone()


@pytest.mark.parametrize('action',['draft','correct','defer'])
def test_only_three_fields_changed_with_history_preserved(attributes_batch,action):
    ed,p,_,data=attributes_batch;single=body(ed,p);single['action']=action;single['reviewer']='原复核人';single['note']='原理由';single['description']['text']='有效结构文字';single['description']['observation']='人工原异常'
    old=ed.save(p['target_key'],single);data['items'][0][1]=1
    response=apply(ed,request(ed,data),'attributes');new=ed.store.get(p['target_key'])
    assert new['description']=={**old['description'],**data['attributes']}
    for k in old.keys()-{'description','revision','updated_at','reviewer','event_kind'}:assert new[k]==old[k]
    assert new['reviewer']=='复核人1' and new['human_review_scope']==['legs','beams','material']
    assert new['structure_attributes_status']=='batch_confirmed' and ed.store.history(p['target_key'])[1]==old
    assert ed.store.get('c'*24) is None and response['attributes_only'] and not response['geometry_completion']


def test_unknown_values_propagated_without_filling_from_class(attributes_batch):
    ed,p,_,data=attributes_batch;data['attributes']=dict(legs=None,beams=None,material='无法判断')
    result=apply(ed,request(ed,data),'attributes');v=result['current_review']
    assert v['description']=={**p['description'],**data['attributes']} and v['action']=='draft' and v['geometry_status']=='imported_previously_completed'
    assert not v['ground_truth_eligible'] and not v['joint_completion_performed']


def test_text_and_attribute_confirmations_coexist(batch):
    ed,p,_,data=batch;text=apply(ed,confirmed(ed,data))['current_review']
    attrs={k:v for k,v in data.items() if k!='text'};attrs.update(batch_id='2'*32,items=[[k,1] for k,_ in data['items']],attributes=dict(legs=4,beams=2,material='塑料'))
    value=apply(ed,request(ed,attrs),'attributes')['current_review']
    assert value['structure_batch']==text['structure_batch'] and value['structure_description_status']=='batch_confirmed'
    data.update(batch_id='3'*32,items=[[k,2] for k,_ in data['items']],text='再次改文字')
    new=apply(ed,confirmed(ed,data))['current_review']
    assert new['structure_attributes_batch']==value['structure_attributes_batch'] and new['structure_attributes_status']=='batch_confirmed'


def test_attribute_conflict_rolls_back_all_targets(attributes_batch):
    ed,p,_,data=attributes_batch;req=request(ed,data);q=ed.proposal('b'*24);ed.save(q['target_key'],body(ed,q))
    with pytest.raises(ReviewError) as error:apply(ed,req,'attributes')
    assert error.value.status==409 and not ed.store.get(p['target_key']) and len(ed.store.history(q['target_key']))==1


def test_changed_source_before_commit_rolls_back(attributes_batch):
    ed,p,guard,data=attributes_batch;req=request(ed,data);answers=iter([True,False]);guard.current=lambda:next(answers)
    with pytest.raises(ReviewError):apply(ed,req,'attributes')
    assert not ed.store.summary()


def test_SQL_failure_rolls_back_whole_attribute_batch(attributes_batch):
    ed,p,_,data=attributes_batch;req=request(ed,data)
    with closing(ed.store.connect()) as db:db.execute("CREATE TRIGGER synthetic_attrs_failure BEFORE INSERT ON events WHEN NEW.target_key='"+'b'*24+"' BEGIN SELECT RAISE(ABORT,'SYNTHETIC attrs failure'); END")
    with pytest.raises(sqlite3.IntegrityError):apply(ed,req,'attributes')
    assert not ed.store.summary()


def test_idempotent_retry_after_later_single_save(attributes_batch):
    ed,p,_,data=attributes_batch;req=request(ed,data);first=apply(ed,req,'attributes')
    single=body(ed,p);single['expected_revision']=1;old=ed.save(p['target_key'],single)
    replay=apply(ed,req,'attributes')
    assert replay['replayed'] and replay['current_review']==first['current_review'] and ed.store.get(p['target_key'])==old and len(ed.store.history(p['target_key']))==2


@pytest.mark.parametrize('field,value',[('legs',3),('beams',1),('material','金属')])
def test_preview_binds_all_three_selections(attributes_batch,field,value):
    ed,p,_,data=attributes_batch;req=request(ed,data);req=deepcopy(req);req['attributes'][field]=value
    with pytest.raises(ReviewError):apply(ed,req,'attributes')
    assert not ed.store.summary()


def test_text_token_cannot_authorize_attributes_or_reuse_same_batch_id(batch):
    ed,p,_,data=batch;text_req=confirmed(ed,data);attrs={k:v for k,v in text_req.items() if k!='text'};attrs['attributes']=dict(legs=3,beams=2,material='金属')
    with pytest.raises(ReviewError):apply(ed,attrs,'attributes')
    apply(ed,text_req);attrs.pop('preview_token');attrs['items']=[[k,1] for k,_ in data['items']]
    with pytest.raises(ReviewError):apply(ed,request(ed,attrs),'attributes')
    assert len(ed.store.history(p['target_key']))==1


def test_cannot_mix_text_and_attribute_mutations(attributes_batch):
    ed,p,_,data=attributes_batch;data['text']='不允许同时改字'
    with pytest.raises(ReviewError):preview(ed,data,'attributes')
    with pytest.raises(ReviewError):preview(ed,data,'text')
    assert not ed.store.summary()


def test_single_save_preserves_attribute_confirmation_only_if_unchanged(attributes_batch):
    ed,p,_,data=attributes_batch;apply(ed,request(ed,data),'attributes');single=body(ed,p);single.update(expected_revision=1);single['description'].update(data['attributes'])
    same=ed.save(p['target_key'],single);assert same['structure_attributes_status']=='batch_confirmed'
    single['expected_revision']=2;single['description']['legs']=3
    changed=ed.save(p['target_key'],single);assert 'structure_attributes_status' not in changed and ed.store.history(p['target_key'])[1]==same
