"""Gallery provenance is frozen evidence; live human edits always take priority."""
from contextlib import closing
import copy
import json
import sqlite3

import pytest

from test_pose_review import dataset
from test_pose_review_masks import suggestions
from pallet.cluster_targets import digest
from pallet.mask_gallery_review import MaskReviewStore
from pallet.pose_review_geometry import canonical
from pallet.pose_review_masks import payload_hash


def publish(f):
    app,template,key,p,path,config,store,snapshot,value=f
    path.write_bytes(canonical(p)+b'\n')
    cfg=json.loads(config.read_text())
    cfg.update(proposals_sha256=digest(path),gallery_review_snapshot_sha256=digest(snapshot))
    config.write_bytes(canonical(cfg))


@pytest.fixture
def gallery(suggestions):
    app,template,key,p,path,config=suggestions
    store=MaskReviewStore(path.parent/'gallery',p['formal_manifest_sha256'])
    row=app.row(template)
    source={k:row[k] for k in ('target_key','frame_id','split','box_index','bbox','size','source_pcd_sha256')}
    source.update(formal_manifest_sha256=p['formal_manifest_sha256'],
                  image_sha256=digest(app.dataset/app.sources[row['frame_id']]['image']))
    value=dict(target_key=template,source=source,source_binding=payload_hash(source),polygon=p['polygon'],
        vertex_count=8,event_kind='human_mask_gallery_revision',human_edited=True,
        status='human_edited_draft_pending_confirmation',human_mask_confirmed=False,human_pose_confirmed=False,
        automatic_training_eligible=False,robot_command_eligible=False,pose_store_written=False,
        original_proposal_modified=False,pose=None,reviewer='gallery human')
    value=store.save(template,0,value)
    snapshot=path.parent/'gallery_snapshot.sqlite3'
    with closing(store.connect()) as live, closing(sqlite3.connect(snapshot)) as frozen:live.backup(frozen)
    p['template'].update(origin='mask_gallery_human_revision',snapshot_revision=1,human_polygon_revision=1,
        human_event_sha256=payload_hash(value),template_human_confirmed=False,
        gallery_review=dict(target_key=template,revision=1,payload_sha256=payload_hash(value),
            source_binding=value['source_binding'],polygon_sha256=payload_hash(value['polygon']),snapshot_sha256=digest(snapshot)))
    cfg=json.loads(config.read_text())
    cfg.update(gallery_review_database=str(store.path.relative_to(app.masks.root)),
        gallery_review_snapshot=str(snapshot.relative_to(app.masks.root)),gallery_review_snapshot_sha256=digest(snapshot))
    config.write_bytes(canonical(cfg))
    f=app,template,key,p,path,config,store,snapshot,value
    publish(f)
    return f


def test_gallery_template_is_read_only_and_retains_separate_pose_identity(gallery):
    app,template,key,p,path,config,store,snapshot,value=gallery
    before=app.store.all();history=app.store.history(template)
    files={f:f.read_bytes() for f in (store.path,snapshot,path,config)}
    result=app.detail(key)['mask_suggestion']
    assert result and result['template']==p['template']
    assert result['template']['current_payload_sha256']!=payload_hash(value)
    assert app.detail(key)['mask_suggestion']==result
    assert app.store.all()==before and app.store.history(template)==history
    assert all(f.read_bytes()==raw for f,raw in files.items())


@pytest.mark.parametrize('change',['revision','payload','delete','event_delete','event_revision'])
def test_live_template_change_revokes_cached_suggestion_and_adoption(gallery,change):
    app,template,key,p,path,config,store,snapshot,value=gallery
    suggestion=app.detail(key)['mask_suggestion'];assert suggestion
    with closing(store.connect()) as db:
        if change=='revision':store.save(template,1,dict(value,note='new edit'))
        elif change=='payload':db.execute('UPDATE reviews SET payload=? WHERE target_key=?',(canonical(dict(value,note='tampered')).decode(),template))
        elif change=='delete':db.execute('DELETE FROM reviews WHERE target_key=?',(template,))
        elif change=='event_delete':db.execute('DELETE FROM events WHERE target_key=?',(template,))
        else:db.execute('UPDATE events SET revision=2 WHERE target_key=?',(template,))
    assert app.detail(key)['mask_suggestion'] is None
    with pytest.raises(Exception,match='掩膜建议或人工修订已变化'):
        app.save(key,dict(binding=app.binding,expected_revision=0,polygon=p['polygon'],sensor=app.sensor(key),
            reviewer='human',mask_proposal_id=suggestion['proposal_id']))
    assert app.store.get(key) is None


@pytest.mark.parametrize('legacy',[False,True])
@pytest.mark.parametrize('history_only',[False,True])
def test_any_saved_target_gallery_edit_hides_all_proposals(gallery,legacy,history_only):
    app,template,key,p,path,config,store,snapshot,value=gallery
    if legacy:
        for name in ('origin','gallery_review'):p['template'].pop(name)
        publish(gallery)
    assert app.detail(key)['mask_suggestion']
    # Even an old source binding, a rectangle, or an unparseable payload is an edit.
    with closing(store.connect()) as db:
        table='events' if history_only else 'reviews'
        db.execute(f'INSERT INTO {table}(target_key,revision,payload) VALUES (?,?,?)',(key,1,'old review'))
    assert app.detail(key)['mask_suggestion'] is None


@pytest.mark.parametrize('change',['missing','corrupt','schema','foreign','snapshot_missing','snapshot_changed'])
def test_unavailable_gallery_fails_closed_without_creating_database(gallery,change):
    app,template,key,p,path,config,store,snapshot,value=gallery
    assert app.detail(key)['mask_suggestion']
    if change=='missing':store.path.unlink()
    elif change=='corrupt':store.path.write_bytes(b'not sqlite')
    elif change=='schema':
        with closing(store.connect()) as db:db.execute('DROP TABLE reviews')
    elif change=='foreign':
        with closing(store.connect()) as db:db.execute("UPDATE metadata SET value='foreign'")
    elif change=='snapshot_missing':snapshot.unlink()
    else:snapshot.write_bytes(b'changed snapshot')
    before=set(path.parent.rglob('*'))
    assert app.detail(key)['mask_suggestion'] is None
    assert set(path.parent.rglob('*'))==before


@pytest.mark.parametrize('change',['source','image','binding','polygon','count','event','origin','confirmed','human_revision','human_hash','snapshot_hash','payload_revision','payload_claim'])
def test_forged_frozen_gallery_evidence_is_rejected(gallery,change):
    app,template,key,p,path,config,store,snapshot,value=gallery
    value=copy.deepcopy(value);t=p['template'];g=t['gallery_review']
    if change in ('source','image'):
        value['source']['bbox' if change=='source' else 'image_sha256']=({} if change=='source' else 'forged')
        value['source_binding']=g['source_binding']=payload_hash(value['source'])
    elif change=='binding':g['source_binding']='forged'
    elif change=='polygon':value['polygon'][1][0]-=1
    elif change=='count':value['vertex_count']=7
    elif change=='origin':t['origin']='human_pose_revision'
    elif change=='confirmed':t['template_human_confirmed']=True
    elif change=='human_revision':t['human_polygon_revision']=2
    elif change=='human_hash':t['human_event_sha256']='forged'
    elif change=='payload_revision':value['revision']=2
    elif change=='payload_claim':value['human_mask_confirmed']=True
    with closing(sqlite3.connect(snapshot)) as db:
        db.execute('UPDATE reviews SET payload=?',(canonical(value).decode(),))
        if change!='event':db.execute('UPDATE events SET payload=?',(canonical(value).decode(),))
        else:db.execute('DELETE FROM events')
        db.commit()
    if change!='human_hash':t['human_event_sha256']=payload_hash(value)
    g['payload_sha256']=payload_hash(value)
    g['snapshot_sha256']=digest(snapshot) if change!='snapshot_hash' else 'forged'
    publish(gallery)
    assert app.detail(key)['mask_suggestion'] is None


@pytest.mark.parametrize('change',['target','template','template_delete','pose_revision'])
def test_gallery_templates_preserve_pose_guards(gallery,change):
    app,template,key,p,*_=gallery
    assert app.detail(key)['mask_suggestion']
    if change=='target':
        app.save(key,dict(binding=app.binding,expected_revision=0,polygon=p['polygon'],sensor=app.sensor(key),reviewer='human'))
    elif change=='pose_revision':
        p['template']['snapshot_revision']=2;publish(gallery)
    else:
        old=app.store.get(template)
        app.store.save(template,1,dict(old,state='deleted' if change=='template_delete' else old['state'],note='changed'))
    assert app.detail(key)['mask_suggestion'] is None


def test_absent_pose_template_allowed_only_when_expected_absent(gallery):
    app,template,key,p,*_=gallery
    with closing(app.store.connect()) as db:
        db.execute('DELETE FROM annotations WHERE target_key=?',(template,))
        db.execute('DELETE FROM events WHERE target_key=?',(template,))
    assert app.detail(key)['mask_suggestion'] is None
    p['template'].update(current_payload_sha256=None,snapshot_revision=0);publish(gallery)
    assert app.detail(key)['mask_suggestion']
    app.save(template,dict(binding=app.binding,expected_revision=0,polygon=p['polygon'],sensor=app.sensor(template),reviewer='human'))
    assert app.detail(key)['mask_suggestion'] is None


@pytest.mark.parametrize('field',['gallery_review_database','gallery_review_snapshot'])
def test_gallery_paths_cannot_escape_outputs(gallery,field,tmp_path):
    app,template,key,p,path,config,*_=gallery
    cfg=json.loads(config.read_text());cfg[field]=str(tmp_path/'outside.sqlite3');config.write_bytes(canonical(cfg))
    assert app.detail(key)['mask_suggestion'] is None
    assert not (tmp_path/'outside.sqlite3').exists()


def test_gallery_origin_requires_complete_explicit_config(gallery):
    app,template,key,p,path,config,*_=gallery
    cfg=json.loads(config.read_text())
    for name in ('gallery_review_database','gallery_review_snapshot','gallery_review_snapshot_sha256'):cfg.pop(name)
    config.write_bytes(canonical(cfg))
    assert app.detail(key)['mask_suggestion'] is None


def test_old_configuration_remains_compatible(suggestions):
    app,template,key,p,path,config=suggestions
    assert not any(k.startswith('gallery_review') for k in json.loads(config.read_text()))
    assert app.detail(key)['mask_suggestion']['template']==p['template']


def test_live_wal_edits_are_seen_without_writing_database(gallery):
    app,template,key,p,path,config,store,snapshot,value=gallery
    with closing(store.connect()) as writer:
        writer.execute('BEGIN IMMEDIATE')
        writer.execute('UPDATE reviews SET payload=payload WHERE target_key=?',(template,))
        writer.commit()
        assert app.detail(key)['mask_suggestion']
        store.save(template,1,dict(value,note='committed WAL edit'))
        files={f:f.read_bytes() for f in (store.path,type(path)(str(store.path)+'-wal'))}
        assert app.detail(key)['mask_suggestion'] is None
        assert all(f.read_bytes()==raw for f,raw in files.items())


def test_shared_memory_reader_slot_updates_do_not_revoke_valid_provenance(gallery):
    import os
    app,template,key,p,path,config,store,snapshot,value=gallery
    with closing(store.connect()) as writer:
        writer.execute('SELECT * FROM reviews').fetchall()
        shm=type(path)(str(store.path)+'-shm')
        persisted={f:f.read_bytes() for f in (store.path,type(path)(str(store.path)+'-wal'))}
        with app.masks.gallery_connect(store.path) as reader:
            reader.execute('SELECT * FROM reviews').fetchall()
            stamp=shm.stat();os.utime(shm,ns=(stamp.st_atime_ns,stamp.st_mtime_ns+1000000))
        assert app.detail(key)['mask_suggestion']
        assert all(f.read_bytes()==raw for f,raw in persisted.items())


def test_wal_without_index_is_not_opened_or_recovered(gallery):
    app,template,key,p,path,config,store,snapshot,value=gallery
    assert app.detail(key)['mask_suggestion']
    wal=type(path)(str(store.path)+'-wal');shm=type(path)(str(store.path)+'-shm')
    wal.write_bytes(b'unavailable WAL index')
    assert not shm.exists()
    assert app.detail(key)['mask_suggestion'] is None
    assert not shm.exists() and wal.read_bytes()==b'unavailable WAL index'


def test_legacy_proposals_with_explicit_gallery_config_fail_closed(gallery):
    app,template,key,p,path,config,store,snapshot,value=gallery
    for name in ('origin','gallery_review'):p['template'].pop(name)
    publish(gallery)
    assert app.detail(key)['mask_suggestion']
    store.path.unlink()
    assert app.detail(key)['mask_suggestion'] is None
    assert not store.path.exists()


def test_foreign_snapshot_binding_rejected_even_with_valid_file_hash(gallery):
    app,template,key,p,path,config,store,snapshot,value=gallery
    with closing(sqlite3.connect(snapshot)) as db:
        db.execute("UPDATE metadata SET value='foreign'");db.commit()
    p['template']['gallery_review']['snapshot_sha256']=digest(snapshot);publish(gallery)
    assert app.detail(key)['mask_suggestion'] is None


def test_gallery_revision_and_pose_revision_are_independent(gallery):
    app,template,key,p,path,config,store,snapshot,value=gallery
    value=store.save(template,1,dict(value,note='second gallery edit'))
    with closing(store.connect()) as live, closing(sqlite3.connect(snapshot)) as frozen:live.backup(frozen)
    p['template'].update(human_polygon_revision=2,human_event_sha256=payload_hash(value))
    p['template']['gallery_review'].update(revision=2,payload_sha256=payload_hash(value),snapshot_sha256=digest(snapshot))
    publish(gallery)
    result=app.detail(key)['mask_suggestion'];assert result
    assert result['template']['snapshot_revision']==1 and result['template']['human_polygon_revision']==2


def test_unresolved_live_rollback_journal_fails_closed(gallery):
    app,template,key,p,path,config,store,snapshot,value=gallery
    assert app.detail(key)['mask_suggestion']
    journal=type(path)(str(store.path)+'-journal');journal.write_bytes(b'unresolved journal')
    assert app.detail(key)['mask_suggestion'] is None
    assert journal.read_bytes()==b'unresolved journal'


def test_gallery_machine_proposal_cannot_claim_human_confirmation(gallery):
    app,template,key,p,*_=gallery
    p['human_mask_confirmed']=True;publish(gallery)
    assert app.detail(key)['mask_suggestion'] is None
