from contextlib import closing
from copy import deepcopy
import io
import json
import sqlite3
from types import SimpleNamespace

import pytest

from pallet.mask_gallery_review import ReviewError
from pallet.mask_model_training_data import sha
from pallet.pallet_description_batch import preview,apply,batch_body
from test_pallet_description import editor,item,body,description


@pytest.fixture
def batch(editor):
    ed,p,guard=editor
    for char in ('b','c'):
        q=deepcopy(p);q['target_key']=char*24;ed.proposals[q['target_key']]=q
    data=dict(binding=ed.binding,source_key=p['target_key'],source_binding=sha(p),batch_id='1'*32,
        items=[[p['target_key'],0],['b'*24,0]],text='统一结构描述',reviewer='SYNTHETIC batch',scope=dict(class_filter='1',state_filter='all'))
    return ed,p,guard,data


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


def test_preview_does_not_create_events_or_batch_tables(batch):
    ed,p,_,data=batch;r=preview(ed,data)
    assert r['count']==2 and r['text_only'] and not r['geometry_completion'] and 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()


def test_text_only_batch_keeps_every_other_review_field_and_history(batch):
    ed,p,_,data=batch
    original={}
    for key,action in ((p['target_key'],'correct'),('b'*24,'defer')):
        q=ed.proposal(key);v=body(ed,q);v['action']=action;v['note']='人工原理由';v['description']['observation']='人工无法判断，保留'
        original[key]=ed.save(key,v)
    data['items']=[[k,1] for k in original];result=apply(ed,confirmed(ed,data))
    for key,old in original.items():
        new=ed.store.get(key);assert new['description']['text']==data['text'] and new['revision']==2
        assert {k:v for k,v in new['description'].items() if k!='text'}=={k:v for k,v in old['description'].items() if k!='text'}
        for field in old.keys()-{'description','revision','reviewer','updated_at','event_kind'}:assert new[field]==old[field]
        assert new['structure_description_status']=='batch_confirmed' and new['human_review_scope']==['structure_text'] and not new['joint_completion_performed']
        assert ed.store.history(key)[1]==old
    assert result['current_review']==ed.store.get(p['target_key']) and ed.store.get('c'*24) is None


def test_unsaved_targets_not_falsely_completed_and_human_note_preserved(batch):
    ed,p,_,data=batch;p['description']['observation']='无法判断';p['human_note']='原始左侧遮挡';data['source_binding']=sha(p)
    p['geometry_previously_completed']=False;data['source_binding']=sha(p)
    result=apply(ed,confirmed(ed,data));v=result['current_review']
    assert v['action']=='draft' and v['geometry_status']=='draft' and v['description_status']=='draft'
    assert v['description']['observation']=='原始左侧遮挡' and not v['ground_truth_eligible']
    other=ed.store.get('b'*24);assert other['action']=='draft' and other['geometry_status']=='imported_previously_completed'


def test_wrong_K_existing_draft_is_preserved_not_completed(batch):
    ed,p,_,data=batch;v=body(ed,p);v['class_id']=2;v['action']='draft';v['description_for']['class_id']=2
    old=ed.save(p['target_key'],v);data['items'][0][1]=1
    apply(ed,confirmed(ed,data));new=ed.store.get(p['target_key'])
    assert new['action']=='draft' and new['polygon']==old['polygon'] and new['class_K_matches'] is False


def test_conflict_after_preview_rolls_back_entire_sequence(batch):
    ed,p,_,data=batch;request=confirmed(ed,data);other=ed.proposal('b'*24);ed.save(other['target_key'],body(ed,other))
    with pytest.raises(ReviewError) as e:apply(ed,request)
    assert e.value.status==409 and not ed.store.get(p['target_key']) and len(ed.store.history(other['target_key']))==1


def test_single_save_from_before_batch_gets_409(batch):
    ed,p,_,data=batch;old=body(ed,p);apply(ed,confirmed(ed,data))
    with pytest.raises(ReviewError) as e:ed.save(p['target_key'],old)
    assert e.value.status==409 and len(ed.store.history(p['target_key']))==1


def test_batch_replay_is_idempotent_even_after_later_edit_and_token_expiry(batch,monkeypatch):
    ed,p,_,data=batch;request=confirmed(ed,data);first=apply(ed,request)
    v=body(ed,p);v['expected_revision']=1;latest=ed.save(p['target_key'],v)
    monkeypatch.setattr('pallet.pallet_description_batch.time.time',lambda:9999999999)
    replay=apply(ed,request)
    assert replay['replayed'] and replay['current_review']==first['current_review']
    assert ed.store.get(p['target_key'])==latest and len(ed.store.history(p['target_key']))==2 and len(ed.store.history('b'*24))==1


@pytest.mark.parametrize('field,value',[('text','其他内容'),('items',[['a'*24,0]]),('reviewer','其他人')])
def test_preview_signature_binds_content_and_exact_scope(batch,field,value):
    ed,p,_,data=batch;request=confirmed(ed,data);request[field]=value
    with pytest.raises(ReviewError):apply(ed,request)
    assert not ed.store.summary()


def test_expired_new_batch_writes_nothing(batch,monkeypatch):
    ed,p,_,data=batch;request=confirmed(ed,data);monkeypatch.setattr('pallet.pallet_description_batch.time.time',lambda:9999999999)
    with pytest.raises(ReviewError):apply(ed,request)
    assert not ed.store.summary()


@pytest.mark.parametrize('mutation',[lambda d:d.update(text=None),lambda d:d.update(text='a'*2001),lambda d:d.update(reviewer=[]),
    lambda d:d.update(items=[]),lambda d:d.update(items=[['a'*24,True]]),lambda d:d.update(items=[['a'*24,0],['a'*24,0]]),
    lambda d:d.update(items=[['d'*24,0]]),lambda d:d.update(polygon=[]),lambda d:d.update(batch_id='not-valid')])
def test_invalid_batch_rejected_without_writes(batch,mutation):
    ed,p,_,data=batch;mutation(data)
    with pytest.raises(ReviewError):preview(ed,data)
    assert not ed.store.summary()


def test_empty_text_is_an_explicit_batch_clear_not_anomaly_clear(batch):
    ed,p,_,data=batch;data['text']='  ';request=confirmed(ed,data);result=apply(ed,request)
    assert result['text']=='' and result['current_review']['description']['observation']==p['description']['observation']


def test_source_change_before_commit_rolls_back_all_events(batch):
    ed,p,guard,data=batch;request=confirmed(ed,data);answers=iter([True,False]);guard.current=lambda:next(answers)
    with pytest.raises(ReviewError):apply(ed,request)
    assert not ed.store.summary() and not ed.store.history(p['target_key'])


def test_sql_failure_halfway_rolls_back_all_events(batch):
    ed,p,_,data=batch;request=confirmed(ed,data)
    with closing(ed.store.connect()) as db:db.execute("CREATE TRIGGER synthetic_batch_failure BEFORE INSERT ON events WHEN NEW.target_key='"+'b'*24+"' BEGIN SELECT RAISE(ABORT,'SYNTHETIC batch failure'); END")
    with pytest.raises(sqlite3.IntegrityError):apply(ed,request)
    assert not ed.store.summary() and not ed.store.history(p['target_key'])


def test_single_save_retains_confirmation_only_when_text_stays_the_same(batch):
    ed,p,_,data=batch;apply(ed,confirmed(ed,data));v=body(ed,p);v['expected_revision']=1;v['description']['text']=data['text']
    same=ed.save(p['target_key'],v);assert same['structure_description_status']=='batch_confirmed'
    v['expected_revision']=2;v['description']['text']='人工再次修改';new=ed.save(p['target_key'],v)
    assert 'structure_description_status' not in new and ed.store.history(p['target_key'])[1]==same


def test_large_batch_body_retains_authentic_origin_rules():
    raw=json.dumps({'items':['a'*24]*3000}).encode();headers={'Content-Type':'application/json','Content-Length':str(len(raw)),'X-Review-Request':'1','Host':'127.0.0.1:9999','Origin':'http://127.0.0.1:9999'}
    assert len(raw)>65536 and batch_body(SimpleNamespace(headers=headers,rfile=io.BytesIO(raw)))['items']
    for change in ({'Sec-Fetch-Site':'cross-site'},{'Origin':'https://evil.invalid'},{'X-Review-Request':''},{'Content-Length':str(2**20+1)}):
        with pytest.raises(ReviewError):batch_body(SimpleNamespace(headers={**headers,**change},rfile=io.BytesIO(raw)))
