"""Annotation-transfer invariants and recovery of known image displacement."""
import copy
import json
import sqlite3

import cv2
import numpy as np
import pytest

from pallet.mask_template_transfer import (annotation_inventory, compatible, patch_matrix,
    rectangle, transfer, transform)


def row(key='a'):
    return dict(target_key=key, frame_id=key, final_class_id=1, split='train', policy_id='camera',
        viewpoint_candidate='front', size=[300, 160], bbox=dict(x=20., y=30., width=120., height=60.))


def test_templates_cannot_cross_class_split_policy_or_known_view():
    a, b = row(), row('b')
    assert compatible(a, b)
    for name, value in [('final_class_id', 2), ('split', 'test'), ('policy_id', 'other'),
                        ('viewpoint_candidate', 'side'), ('frame_id', 'a')]:
        assert not compatible(a, dict(b, **{name: value}))
    assert compatible(a, dict(b, viewpoint_candidate='unknown'))


def test_history_protects_manual_four_vertex_and_reverted_masks_and_deleted_targets():
    rows = {k: row(k) for k in ('a', 'b', 'c', 'd', 'e')}
    db = sqlite3.connect(':memory:')
    db.executescript('CREATE TABLE events(id INTEGER PRIMARY KEY,target_key TEXT,revision INTEGER,payload TEXT);'
                    'CREATE TABLE annotations(target_key TEXT,revision INTEGER,payload TEXT);')
    rect = rectangle(rows['a']); moved = copy.deepcopy(rect); moved[0][0] += 2
    poly = [[20, 30], [140, 30], [140, 90], [100, 90], [100, 60], [60, 60], [60, 90], [20, 90]]
    seq = dict(a=[dict(polygon=rect), dict(polygon=moved), dict(polygon=rect)],
        b=[dict(polygon=poly), dict(polygon=poly, event_kind='unit_normalization')],
        c=[dict(polygon=rect)], d=[dict(polygon=poly), dict(polygon=poly, state='deleted')],
        e=[dict(polygon=poly, event_kind='mask_template_proposal')])
    for k, events in seq.items():
        for rev, value in enumerate(events, 1):
            payload = json.dumps(dict(state='draft', revision=rev, **value)) if 'state' not in value else json.dumps(dict(revision=rev, **value))
            db.execute('INSERT INTO events(target_key,revision,payload) VALUES (?,?,?)', (k, rev, payload))
        db.execute('INSERT INTO annotations VALUES (?,?,?)', (k, rev, payload))
    current, templates, status = annotation_inventory(db, rows)
    assert set(templates) == {'b'}
    assert templates['b']['human_polygon_revision'] == 1 and templates['b']['revision'] == 2
    assert not templates['b']['human_mask_confirmed']
    assert status['a'] == 'human_mask_history_protected'
    assert status['c'] == 'eligible' and status['d'] == 'deleted'
    assert status['e'] == 'human_mask_history_protected'


def test_transferred_vertices_follow_known_image_translation_not_bbox_copy():
    rng = np.random.default_rng(83)
    source = cv2.GaussianBlur(rng.integers(0, 256, (112, 256), dtype=np.uint8), (5, 5), .8)
    warp = np.array([[1, 0, 3.2], [0, 1, -2.4]], np.float32)
    target = cv2.warpAffine(source, warp, (256, 112), borderMode=cv2.BORDER_REFLECT_101)
    p = np.array([[30, 30], [220, 30], [220, 80], [170, 80], [170, 55], [80, 55], [80, 80], [30, 80]], float)
    a, b = row(), row('b'); inverse = cv2.invertAffineTransform(patch_matrix(a))
    polygon = transform(p, inverse)
    result, metrics = transfer(source, target, polygon.tolist(), a, b)
    assert result is not None, metrics
    assert len(result) == len(polygon) == 8
    expected = transform(transform(p, warp), inverse)
    np.testing.assert_allclose(result, expected, atol=.45)
    assert not np.allclose(result, polygon)
    assert metrics['boundary_ncc'] > .9


def test_unrelated_images_are_rejected_without_fabricating_fixed_vertices():
    rng = np.random.default_rng(98)
    a = cv2.GaussianBlur(rng.integers(0, 256, (112, 256), dtype=np.uint8), (3, 3), .6)
    b = cv2.GaussianBlur(rng.integers(0, 256, (112, 256), dtype=np.uint8), (3, 3), .6)
    polygon = [[20, 30], [140, 30], [140, 90], [100, 90], [100, 60], [60, 60], [60, 90], [20, 90]]
    result, metrics = transfer(a, b, polygon, row(), row('b'))
    assert result is None and metrics['rejection']
