"""Adversarial verifier checks for historical bindings and honest scan outcomes."""
import copy
import json

import pytest

from scripts import verify_mask_template_refined_next as audit
from pallet.mask_gallery_review import VERSION as EDITOR_VERSION


@pytest.mark.parametrize('version', [3, 4])
def test_review_uses_its_declared_historical_publication(version, tmp_path):
    proposal = dict(target_key='saved', polygon=[[1, 1]], template={'origin': 'old'})
    old = {'saved': proposal}
    publications = {v: dict(path=tmp_path/str(v), proposals=old) for v in (3, 4)}
    review = dict(target_key='saved', proposal_publication=version, base_proposal_id=audit.sha(proposal),
                  proposal_polygon=proposal['polygon'], template_provenance=proposal['template'],
                  binding=audit.sha(dict(formal='formal', proposals=audit.PUBLICATIONS[version][1]['proposals.jsonl'],
                                        editor_version=EDITOR_VERSION)))
    assert audit.review_publication(review, old, 'formal', publications) == tmp_path/str(version)
    review['proposal_publication'] = 7-version
    with pytest.raises(ValueError, match='publication binding differs'):
        audit.review_publication(review, old, 'formal', publications)


def test_overlapping_template_keys_keep_old_polygon_and_snapshot():
    original = dict(row={'target_key': 'seed'}, polygon=['old polygon'], rendering_id='historical:seed')
    previous = dict(original, origin=audit.ORIGIN, polygon=['prior refined polygon'],
                    gallery_review={'snapshot_sha256': 'old-snapshot'}, rendering_id='refined:seed')
    latest = dict(previous, polygon=['latest human polygon'], gallery_review={'snapshot_sha256': 'new-snapshot'},
                  rendering_id='generation:seed')
    parent = dict(templates=[original, previous], rendering_by_target={'seed': 'refined:seed'})
    proposal = dict(template={'target_key': 'seed'})
    inventory = dict(templates=[original, previous, latest], generation_template_keys=['seed'],
                     gallery_human_templates=1, historical_templates=2, conflicting_template_keys=['seed'],
                     rendering_by_target={'seed': 'refined:seed', 'new': 'generation:seed'})
    assert audit.rendering_inventory(inventory, parent, {'seed': proposal}, {'new': proposal}, 'new-snapshot') == {'seed': latest}
    inventory['rendering_by_target']['seed'] = 'generation:seed'
    with pytest.raises(ValueError, match='Historical rendering changed'):
        audit.rendering_inventory(inventory, parent, {'seed': proposal}, {'new': proposal}, 'new-snapshot')
    inventory['rendering_by_target']['seed'] = 'refined:seed'
    inventory = copy.deepcopy(inventory)
    inventory['templates'][1]['polygon'] = ['silently replaced old polygon']
    with pytest.raises(ValueError, match='payload inventory changed'):
        audit.rendering_inventory(inventory, parent, {'seed': proposal}, {'new': proposal}, 'new-snapshot')


class Evidence:
    def patch(self, key):
        return key

    def image(self, frame):
        return frame


@pytest.fixture
def attempt_fixture(tmp_path, monkeypatch):
    row = dict(final_class_id=1, frame_id='target-frame', split='train', policy_id='native')
    template = dict(row=dict(row, frame_id='seed-frame'), polygon=['polygon'])
    rows, templates = {'target': row}, {'seed': template}
    outcome = dict(target_key='target', class_id=1, reason='registration_or_boundary_rejected')
    trial = dict(target_key='target', template_key='seed', class_id=1,
                 metrics=dict(rejection='affine_registration_failed', initial_ncc=.9))
    (tmp_path/'registration_attempts.jsonl').write_text(json.dumps(trial)+'\n')
    monkeypatch.setattr(audit, 'correlate', lambda *_: .9)
    monkeypatch.setattr(audit, 'transfer', lambda *_: (None, copy.deepcopy(trial['metrics'])))
    args = (tmp_path, rows, {'target': 'eligible'}, {'history_keys': set()}, {}, templates, {}, {'target': outcome}, Evidence())
    return args, trial


def test_rejected_attempts_require_recomputed_metrics(attempt_fixture, monkeypatch):
    args, trial = attempt_fixture
    assert audit.audit_attempts(*args) == ({'target'}, 1)
    monkeypatch.setattr(audit, 'transfer', lambda *_: (None, dict(trial['metrics'], initial_ncc=.8)))
    with pytest.raises(ValueError, match='numeric mismatch'):
        audit.audit_attempts(*args)


def test_falsely_rejected_passing_attempt_is_detected(attempt_fixture, monkeypatch):
    args, trial = attempt_fixture
    monkeypatch.setattr(audit, 'transfer', lambda *_: (['passing polygon'], {}))
    monkeypatch.setattr(audit, 'affine_reference', lambda *_: None)
    monkeypatch.setattr(audit, 'beam_boundary_audit', lambda *_: {'state': 'passed'})
    with pytest.raises(ValueError, match='falsely rejected'):
        audit.audit_attempts(*args)


def test_accepted_disposition_without_candidate_is_rejected(attempt_fixture):
    args, _ = attempt_fixture
    args[-2]['target']['reason'] = 'accepted_quota_full_not_selected'
    with pytest.raises(ValueError, match='False rejection outcome'):
        audit.audit_attempts(*args)


def test_candidate_without_compatible_seed_cannot_claim_acceptance(attempt_fixture):
    args, _ = attempt_fixture
    args[5]['seed']['row']['split'] = 'test'
    args[6]['target'] = {'template': {'target_key': 'seed'}}
    args[-2]['target']['reason'] = 'no_compatible_template'
    (args[0]/'registration_attempts.jsonl').write_text('')
    with pytest.raises(ValueError, match='False no-compatible-template'):
        audit.audit_attempts(*args)


def test_pose_only_save_is_eligible_but_restored_mask_history_stays_protected():
    row = dict(bbox=dict(x=0, y=0, width=20, height=10), size=[30, 20])
    rectangle = [[0, 0], [20, 0], [20, 10], [0, 10]]
    value = dict(polygon=rectangle, revision=2, state='draft', pose={'saved': True})
    edited = dict(value, polygon=[[1, 1], [19, 1], [19, 9], [1, 9]], revision=1)
    store = dict(current={'pose': value, 'restored': value},
                 events=[(1, 'pose', 2, json.dumps(value)), (2, 'restored', 1, json.dumps(edited)),
                         (3, 'restored', 2, json.dumps(value))])
    assert audit.prior.pose_status(store, {'pose': row, 'restored': row}) == {
        'pose': 'eligible', 'restored': 'human_mask_history_protected'}
