"""Pose templates and manual-source gallery entries do not ignore newer edits."""
import hashlib
import json
import sqlite3
from pathlib import Path
import pytest

from pallet.mask_pose_dependency import current_pose_source
from pallet.pose_review_geometry import canonical


@pytest.fixture
def pose_source(tmp_path):
    path=tmp_path/'pose.sqlite3';polygon=[[0,0],[10,0],[10,10],[0,10]]
    value=dict(target_key='a'*24,revision=3,state='draft',polygon=polygon)
    sha=lambda v:hashlib.sha256(canonical(v)).hexdigest()
    with sqlite3.connect(path) as db:
        db.executescript('CREATE TABLE metadata(key TEXT,value TEXT);CREATE TABLE annotations(target_key TEXT,revision INTEGER,payload TEXT);')
        db.execute('INSERT INTO metadata VALUES(?,?)',('binding',json.dumps(dict(formal_manifest_sha256='formal'))))
        db.execute('INSERT INTO annotations VALUES(?,?,?)',(value['target_key'],3,canonical(value).decode()))
    template=dict(target_key=value['target_key'],snapshot_revision=3,current_payload_sha256=sha(value),
        pose_review=dict(target_key=value['target_key'],revision=3,payload_sha256=sha(value),polygon_sha256=sha(polygon)))
    return path,value,template


def test_read_only_source_binding_and_files_unchanged(pose_source):
    path,value,template=pose_source;before=path.read_bytes()
    assert current_pose_source(path,'formal',template)
    assert path.read_bytes()==before and set(path.parent.iterdir())=={path}


@pytest.mark.parametrize('change',['revision','polygon','deleted','missing','foreign','forged_polygon_hash'])
def test_new_or_unavailable_pose_source_revokes_dependency(pose_source,change):
    path,value,template=pose_source
    if change=='missing':path.unlink()
    elif change=='forged_polygon_hash':template['pose_review']['polygon_sha256']='f'*64
    else:
        if change=='revision':value['revision']+=1
        elif change=='polygon':value['polygon'][0][0]=1
        elif change=='deleted':value['state']='deleted'
        with sqlite3.connect(path) as db:
            if change=='foreign':db.execute('UPDATE metadata SET value=?',(json.dumps(dict(formal_manifest_sha256='other')),))
            else:db.execute('UPDATE annotations SET revision=?,payload=?',(value['revision'],canonical(value).decode()))
    assert not current_pose_source(path,'formal',template)
    if change=='missing':assert not path.exists()


def test_committed_wal_revision_change_seen_without_data_write(pose_source):
    path,value,template=pose_source
    db=sqlite3.connect(path);db.execute('PRAGMA journal_mode=WAL');db.execute('UPDATE annotations SET payload=payload');db.commit()
    try:
        assert current_pose_source(path,'formal',template)
        value['revision']+=1;db.execute('UPDATE annotations SET revision=?,payload=?',(value['revision'],canonical(value).decode()));db.commit()
        persisted={p:p.read_bytes() for p in (path,Path(str(path)+'-wal'))}
        assert not current_pose_source(path,'formal',template)
        assert all(p.read_bytes()==v for p,v in persisted.items())
    finally:db.close()
