"""Known-warp recovery and adversarial consensus/support checks for research."""
import cv2
import numpy as np

from pallet.mask_template_transfer import patch_matrix, transform, transfer as original_transfer
from pallet.mask_transfer_multiscale import consensus, local_support, transfer


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


def test_known_subpixel_translation_recovered_with_two_window_agreement():
    rng = np.random.default_rng(83)
    source = cv2.GaussianBlur(rng.integers(0, 256, (112, 256), dtype=np.uint8), (7, 7), 1.8)
    warp = np.array([[1, 0, .8], [0, 1, -.6]], 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)
    inverse = cv2.invertAffineTransform(patch_matrix(row('a')))
    result, metrics = transfer(source, target, transform(p, inverse).tolist(), row('a'), row('b'))
    assert result is not None, metrics
    np.testing.assert_allclose(result, transform(transform(p, warp), inverse), atol=.15)
    assert len(result) == len(p)
    assert metrics['cross_window_support']
    assert all(s['window'] != metrics['selected_configuration']['window'] for s in metrics['cross_window_support'])
    assert max(metrics['forward_backward_error_patch_pixels']) <= 1.5
    assert metrics['local_image_support']['passed']
    _, original = original_transfer(source, target, transform(p, inverse).tolist(), row('a'), row('b'))
    for field in ('ecc', 'initial_ncc', 'boundary_ncc', 'affine_patch_transform'):
        np.testing.assert_array_equal(metrics[field], original[field])
    baseline = next(c for c in metrics['configurations'] if c['baseline'])
    np.testing.assert_array_equal(baseline['metrics']['forward_backward_error_patch_pixels'],
        original['forward_backward_error_patch_pixels'])


def config(window, level, points, rejection=None, fb=0):
    return dict(window=window, max_level=level, forward_patch_vertices=points,
        metrics=dict(rejection=rejection, forward_backward_error_patch_pixels=[fb]*len(points)))


def test_low_fb_or_same_window_pyramids_cannot_replace_independent_agreement():
    points = [[10., 10.], [20., 10.], [20., 20.], [10., 20.]]
    shifted = (np.array(points)+[0, 2]).tolist()
    a = config(15, 0, points, fb=.5)
    b = config(15, 1, points, fb=0)
    c = config(25, 0, shifted, fb=0)
    assert consensus([a, b, c])[0] is None
    d = config(31, 0, points, rejection='weak_local_photometric_or_edge_support')
    assert consensus([a, b, c, d])[0] is None
    e = config(31, 1, points, fb=.8)
    chosen, support = consensus([a, b, c, d, e])
    assert chosen is a  # Fixed priority, not the smaller FB of b/c.
    assert support[0]['window'] == 31


def test_flat_and_unrelated_local_support_is_rejected():
    rng = np.random.default_rng(7)
    flat = np.full((112, 256), 128, np.uint8)
    a = rng.integers(0, 256, flat.shape, dtype=np.uint8)
    b = rng.integers(0, 256, flat.shape, dtype=np.uint8)
    points = np.array([[30, 30], [100, 60]], np.float32)
    affine = np.eye(2, 3, dtype=np.float32)
    assert not local_support(flat, flat, points, points, affine)['passed']
    assert not local_support(a, b, points, points, affine)['passed']


def test_initial_similarity_gate_cannot_be_bypassed_by_config_search():
    rng = np.random.default_rng(98)
    a = rng.integers(0, 256, (112, 256), dtype=np.uint8)
    b = rng.integers(0, 256, (112, 256), dtype=np.uint8)
    result, metrics = transfer(a, b, [[20, 30], [140, 30], [140, 90], [20, 90]], row('a'), row('b'))
    assert result is None
    assert metrics['rejection'] == 'initial_similarity_below_gate'
    assert metrics['configurations'] == []
