"""Gallery/pose provenance separation and non-destructive cumulative selection."""
import copy
import json
import sqlite3

import pytest

from pallet.mask_template_continue import sha
from pallet.mask_template_refined import (CLASSES, EDITOR_VERSION, gallery_templates,
    preserve_parent_assets, protected_pose_keys, select_diverse, snapshot_database,
    readonly, write_jsonl)
from pallet.cluster_targets import digest
from pallet.pose_review_geometry import canonical


def proposal(key, frame, group='group-a', cls=1, quality=.9):
    return dict(target_key=key, class_id=cls, source=dict(frame_id=frame, group_id=group),
                metrics=dict(boundary_ncc=quality, ecc=quality))


def test_diversity_is_frame_distinct_cumulative_and_group_balanced():
    previous = [proposal('old', 'old')]
    candidates = [proposal('same-frame', 'old', 'new-group'),
                  proposal('strong', 'strong', quality=.99),
                  proposal('diverse', 'diverse', 'new-group', quality=.85),
                  proposal('duplicate', 'diverse', 'other-group', quality=.8)]
    chosen, reasons = select_diverse(previous, candidates, goal=2)
    assert [p['target_key'] for p in chosen] == ['diverse']
    assert reasons['same-frame'] == reasons['duplicate'] == 'accepted_duplicate_frame_not_selected'
    assert reasons['strong'] == 'accepted_quota_full_not_selected'
    assert previous == [proposal('old', 'old')]


def test_pose_only_rectangle_saves_remain_eligible_after_automatic_revision():
    db = sqlite3.connect(':memory:')
    db.executescript('CREATE TABLE annotations(target_key TEXT,payload TEXT);'
                    'CREATE TABLE events(id INTEGER,target_key TEXT,revision INTEGER,payload TEXT);')
    row = dict(bbox=dict(x=0,y=0,width=20,height=10), size=[30,20])
    rectangle = [[0,0],[20,0],[20,10],[0,10]]
    human = dict(polygon=rectangle,revision=1,state='draft')
    automatic = dict(human,revision=2,event_kind='unit_normalization')
    db.execute('INSERT INTO events VALUES(1,?,?,?)', ('human',1,json.dumps(human)))
    db.execute('INSERT INTO events VALUES(2,?,?,?)', ('human',2,json.dumps(automatic)))
    db.execute('INSERT INTO annotations VALUES(?,?)', ('human',json.dumps(automatic)))
    db.execute('INSERT INTO events VALUES(3,?,?,?)', ('auto',1,json.dumps(dict(automatic,revision=1))))
    current, status, protected = protected_pose_keys(db, {'human':row,'auto':row,'empty':row})
    assert status == {'human':'eligible','auto':'eligible','empty':'eligible'}
    assert protected == set() and current['human']['revision'] == 2
    db.close()


@pytest.mark.parametrize('condition,expected', [
    ('restored_rectangle','human_mask_history_protected'),
    ('deleted','deleted'), ('deferred','deferred_or_confirmed_protected'),
    ('human_mask_confirmed','deferred_or_confirmed_protected'),
    ('human_pose_confirmed','deferred_or_confirmed_protected')])
def test_mask_history_and_existing_noneligible_states_stay_protected(condition, expected):
    db = sqlite3.connect(':memory:')
    db.executescript('CREATE TABLE annotations(target_key TEXT,payload TEXT);'
                    'CREATE TABLE events(id INTEGER,target_key TEXT,revision INTEGER,payload TEXT);')
    row = dict(bbox=dict(x=0,y=0,width=20,height=10), size=[30,20])
    rectangle = [[0,0],[20,0],[20,10],[0,10]]
    old = dict(polygon=rectangle,revision=1,state='draft')
    latest = dict(old,revision=2)
    if condition == 'restored_rectangle':
        old['polygon'] = [[1,1],[19,1],[19,9],[1,9]]
    elif condition in ('deleted','deferred'):
        latest['state'] = condition
    else:
        latest[condition] = True
    db.execute('INSERT INTO events VALUES(1,?,?,?)', ('target',1,json.dumps(old)))
    db.execute('INSERT INTO events VALUES(2,?,?,?)', ('target',2,json.dumps(latest)))
    db.execute('INSERT INTO annotations VALUES(?,?)', ('target',json.dumps(latest)))
    before = list(db.execute('SELECT * FROM events'))
    _, status, protected = protected_pose_keys(db, {'target':row})
    assert status == {'target':expected} and protected == {'target'}
    assert list(db.execute('SELECT * FROM events')) == before
    db.close()


@pytest.fixture
def gallery_fixture(tmp_path):
    parent = tmp_path/'parent'; (parent/'images').mkdir(parents=True)
    rows = {}; previous = []; reviews = {}; polygon = [[1,1],[20,1],[20,10],[15,10],[15,5],[5,5],[5,10],[1,10]]
    for i in range(56):
        key = f'{i:024x}'
        row = dict(target_key=key, frame_id=f'frame-{i}', split='train', box_index=0,
            bbox=dict(x=1,y=1,width=19,height=9),size=[24,16],source_pcd_sha256='pcd', final_class_id=CLASSES[i%5])
        rows[key] = row
        (parent/'images'/f'{key}.png').write_bytes(b'image')
        p = dict(target_key=key,source=row,class_id=row['final_class_id'],formal_manifest_sha256='formal')
        previous.append(p)
        identity = {k:row[k] for k in ('target_key','frame_id','split','box_index','bbox','size','source_pcd_sha256')}
        identity.update(formal_manifest_sha256='formal',image_sha256=digest(parent/'images'/f'{key}.png'))
        reviews[key] = dict(target_key=key,source=identity,source_binding=sha(identity),base_proposal_id=sha(p),
            revision=7,polygon=polygon,vertex_count=8,event_kind='human_mask_gallery_revision',human_edited=True)
    write_jsonl(parent/'proposals.jsonl',previous)
    binding = sha(dict(formal='formal',proposals=digest(parent/'proposals.jsonl'),editor_version=EDITOR_VERSION))
    for r in reviews.values():
        r['binding'] = binding
    return parent,rows,previous,reviews


def test_gallery_revision_does_not_fabricate_pose_current_revision(gallery_fixture):
    parent,rows,previous,reviews = gallery_fixture
    first,second = list(rows)[:2]; pose = dict(revision=19,polygon=[[0,0],[1,0],[1,1],[0,1]])
    templates = gallery_templates(previous,reviews,list(reviews.values()),{first:pose},rows,parent,'formal','snapshot')
    assert templates[first]['revision'] == 19
    assert templates[first]['current_payload_sha256'] == sha(pose)
    assert templates[first]['human_polygon_revision'] == 7
    assert templates[first]['human_event_sha256'] == sha(reviews[first])
    assert templates[second]['revision'] == 0 and templates[second]['current_payload_sha256'] is None
    assert templates[first]['gallery_review'] == dict(target_key=first,revision=7,payload_sha256=sha(reviews[first]),
        source_binding=reviews[first]['source_binding'],polygon_sha256=sha(reviews[first]['polygon']),snapshot_sha256='snapshot')
    assert not templates[first]['human_mask_confirmed']


@pytest.mark.parametrize('attack', ['source','binding','proposal','latest','vertices'])
def test_gallery_templates_reject_identity_and_staleness_attacks(gallery_fixture, attack):
    parent,rows,previous,reviews = gallery_fixture
    events = copy.deepcopy(list(reviews.values())); first = next(iter(reviews)); r = reviews[first]
    if attack == 'source': r['source']['frame_id'] = 'other'
    elif attack == 'binding': r['source_binding'] = 'invalid'
    elif attack == 'proposal': r['base_proposal_id'] = 'invalid'
    elif attack == 'latest': events.append(dict(r,revision=8))
    else: r['polygon'] = r['polygon'][:4]
    with pytest.raises(ValueError):
        gallery_templates(previous,reviews,events,{},rows,parent,'formal','snapshot')


def test_historical_assets_survive_template_key_conflict(tmp_path):
    parent = tmp_path/'parent'; out = tmp_path/'out'
    for root in (parent,out):
        for name in ('cases','images','masks','labelme','templates'):
            (root/name).mkdir(parents=True)
    for folder,ext in (('cases','png'),('images','png'),('masks','png'),('labelme','json')):
        (parent/folder/f'old.{ext}').write_bytes(b'historical-asset')
    (parent/'templates/shared.json').write_bytes(canonical(dict(polygon='historical')))
    (out/'templates/shared.json').write_bytes(canonical(dict(polygon='refined')))
    hashes = preserve_parent_assets(parent,out,[dict(target_key='old')])
    assert (out/'templates/shared.json').read_bytes() == (parent/'templates/shared.json').read_bytes()
    assert json.loads((out/'refined/templates/shared.json').read_text())['polygon'] == 'refined'
    assert all(digest(out/path) == value for path,value in hashes.items())


def test_database_snapshot_and_backup_include_committed_wal(tmp_path):
    live = tmp_path/'live.sqlite3'; destination = tmp_path/'snapshot.sqlite3'
    db = sqlite3.connect(live); db.execute('PRAGMA journal_mode=WAL')
    db.execute('CREATE TABLE reviews(value TEXT)'); db.execute("INSERT INTO reviews VALUES('fine edit')"); db.commit()
    before = digest(live); frozen_sha = snapshot_database(live,destination)
    frozen = readonly(destination,True)
    assert frozen.execute('SELECT value FROM reviews').fetchone()[0] == 'fine edit'
    assert digest(tmp_path/'backups/snapshot.sqlite3') == frozen_sha and digest(live) == before
    frozen.close(); db.close()
