"""Adversarial publication-6 checks without importing its generator or live writes."""
import copy
import hashlib
import json
import sqlite3

import pytest

from scripts import verify_mask_quota_completion as audit


POLYGON = [[1, 1], [20, 1], [20, 10], [15, 10], [15, 5], [5, 5], [5, 10], [1, 10]]


def row(key='manual', cls=2):
    return dict(target_key=key, target_id=key+'::box:0000', frame_id='frame-'+key,
        final_class_id=cls, split='train', policy_id='camera', viewpoint_candidate='front',
        group_id='group', box_index=0, bbox=dict(x=1, y=1, width=19, height=9),
        size=[24, 16], source_pcd_sha256='pcd')


def store(current, events):
    return dict(path=audit.Path('read-only.sqlite3'), metadata={}, current=current,
                events=events, history_keys={e[1] for e in events})


@pytest.fixture
def manual_fixture():
    r = row()
    human = dict(target_key='manual', source=r, polygon=copy.deepcopy(POLYGON), revision=4,
                 state='draft', human_mask_confirmed=False, human_pose_confirmed=False,
                 automatic_training_eligible=False, robot_command_eligible=False)
    current = dict(human, revision=5, event_kind='unit_normalization')
    raw = json.dumps(human, indent=2)  # Deliberately not canonical: event hashes bind raw SQLite bytes.
    pose = store({'manual': current}, [(1, 'manual', 4, raw), (2, 'manual', 5, json.dumps(current))])
    direct = audit.independent_pose_templates(pose, {'manual': r})
    template = direct['manual']
    request = dict(target_key='manual', class_id=2, pose_annotation_url='https://example.test/?target=manual',
                   source=dict(r, formal_manifest_sha256='formal'))
    binding = dict(target_key='manual', class_id=2, split='train', snapshot_revision=5,
        current_payload_sha256=audit.sha(current), human_polygon_revision=4,
        human_event_sha256=hashlib.sha256(raw.encode()).hexdigest(), vertex_count=8,
        template_human_confirmed=False, origin=audit.POSE_ORIGIN,
        pose_review=audit.pose_provenance(template, 'snapshot'))
    proposal = dict(target_key='manual', class_id=2, source=r, polygon=copy.deepcopy(POLYGON), vertex_count=8,
        status='human_edited_draft_pending_confirmation', human_edited=True,
        origin=audit.POSE_ORIGIN, schema='saved_pose_mask_gallery_entry_v1',
        formal_manifest_sha256='formal', class_assignments_sha256='classes',
        manual_request_sha256=audit.sha(request), original_pose_url=request['pose_annotation_url'],
        rendering_id='quota_generation:manual', source_label_kind='human_mask_source_manual_template_draft',
        pose_snapshot_saved=True, pose_store_written=False, gallery_store_written=False,
        snapshot_sha256='snapshot', target_expected_revision=5, target_snapshot_payload_sha256=audit.sha(current),
        template=binding, metrics={}, **dict.fromkeys(audit.FALSE_FLAGS, False))
    args = (proposal, request, pose, direct, r, 'snapshot', 'formal', 'classes')
    return args


def test_manual_completion_is_exact_latest_human_polygon_not_a_transfer(manual_fixture):
    audit.check_manual(*manual_fixture)
    proposal, _, pose, direct, *_ = manual_fixture
    assert proposal['template']['target_key'] == proposal['target_key']
    assert proposal['template']['human_event_sha256'] != audit.sha(json.loads(pose['events'][0][3]))
    assert direct['manual']['human_polygon_revision'] == 4
    assert direct['manual']['revision'] == 5


@pytest.mark.parametrize('attack', ['polygon', 'vertex_count', 'source', 'split', 'class', 'machine_status',
    'not_human', 'confirmation', 'event_hash', 'current_hash', 'revision', 'snapshot', 'transfer_metrics',
    'continuation', 'machine_origin', 'different_source', 'request_hash', 'store_write', 'source_confirmed'])
def test_manual_cannot_claim_stale_transferred_or_confirmed_work(manual_fixture, attack):
    p, request, pose, direct, *_ = manual_fixture
    if attack == 'polygon':
        p['polygon'][0][0] += 1
    elif attack == 'vertex_count':
        p['vertex_count'] += 1
    elif attack == 'source':
        p['source'] = dict(p['source'], frame_id='different-frame')
    elif attack == 'split':
        request['source'] = dict(request['source'], split='test')
    elif attack == 'class':
        p['class_id'] = 10
    elif attack == 'machine_status':
        p['status'] = 'machine_draft_pending_visual_review'
    elif attack == 'not_human':
        p['human_edited'] = False
    elif attack == 'confirmation':
        p['ground_truth_eligible'] = True
    elif attack == 'event_hash':
        p['template']['human_event_sha256'] = 'canonical-rather-than-raw'
    elif attack == 'current_hash':
        p['target_snapshot_payload_sha256'] = 'stale'
    elif attack == 'revision':
        p['target_expected_revision'] -= 1
    elif attack == 'snapshot':
        p['snapshot_sha256'] = 'stale'
    elif attack == 'transfer_metrics':
        p['metrics'] = {'ecc': 1.0}
    elif attack == 'continuation':
        p['continuation'] = {'batch': 6}
    elif attack == 'machine_origin':
        p['template']['origin'] = 'machine_draft'
    elif attack == 'different_source':
        p['template']['target_key'] = 'other'
    elif attack == 'request_hash':
        p['manual_request_sha256'] = 'changed'
    elif attack == 'store_write':
        p['gallery_store_written'] = True
    else:
        pose['current']['manual']['human_mask_confirmed'] = True
    with pytest.raises(ValueError):
        audit.check_manual(*manual_fixture)


def test_pose_seed_inventory_excludes_machine_deleted_deferred_and_stale_human():
    keys = ('human', 'machine', 'deleted', 'deferred', 'stale')
    rows = {k: row(k) for k in keys}
    events, current = [], {}
    for event_id, key in enumerate(keys, 1):
        value = dict(target_key=key, revision=1, state='draft', polygon=copy.deepcopy(POLYGON))
        if key in ('deleted', 'deferred'):
            value['state'] = key
        if key == 'machine':
            value['event_kind'] = 'mask_template_proposal'
        current[key] = value
        events.append((event_id, key, 1, json.dumps(value)))
    changed = dict(current['stale'], revision=2, event_kind='axes_normalization', polygon=POLYGON[:-1])
    current['stale'] = changed
    events.append((6, 'stale', 2, json.dumps(changed)))
    assert set(audit.independent_pose_templates(store(current, events), rows)) == {'human'}


def test_partition_rejects_counting_manual_self_source_as_accepted_transfer():
    manual = {'m': {'target_key': 'm'}}
    audit.check_partition({}, manual, {}, manual, {})
    with pytest.raises(ValueError, match='treated as accepted transfer'):
        audit.check_partition({}, manual, {}, manual, manual)
    with pytest.raises(ValueError, match='overlap'):
        audit.check_partition(manual, manual, {}, manual, {})
    with pytest.raises(ValueError, match='canonical object'):
        audit.check_partition({}, manual, {}, {'m': dict(manual['m'], changed=True)}, {})


def candidate(key, cls=1, frame=None):
    source = row(key, cls)
    if frame is not None:
        source['frame_id'] = frame
    return dict(target_key=key, source=source, class_id=cls, metrics=dict(boundary_ncc=.9, ecc=.95))


def test_manual_frames_consume_quota_and_block_duplicate_machine_frames():
    old = {str(i): candidate(str(i)) for i in range(48)}
    manual = {k: candidate(k) for k in ('human-a', 'human-b')}
    accepted = {'dup': candidate('dup', frame='frame-human-a'), 'fresh': candidate('fresh')}
    outcomes = {k: dict(reason=r) for k, r in
                (('dup', 'accepted_duplicate_frame_not_selected'), ('fresh', 'accepted_quota_full_not_selected'))}
    audit.check_diversity({**old, **manual}, accepted, {}, outcomes)
    with pytest.raises(ValueError, match='Diversity disposition'):
        audit.check_diversity(old, accepted, {}, outcomes)


def test_distinct_frame_counter_separates_old_manual_and_machine():
    old, manual, new = ({'o': candidate('o', 2)}, {'m': candidate('m', 2)}, {'n': candidate('n', 2)})
    classes, counts = audit.expected_counts(old, manual, new, {'current': {'o': {'polygon': POLYGON}}})
    assert classes['2']['old_total'] == classes['2']['manual_added'] == classes['2']['new_candidates'] == 1
    assert classes['2']['saved_human'] == 2 and classes['2']['prior_machine_pending'] == 0
    assert counts['2'] == dict(proposals=3, distinct_frames=3, shortfall=47)
    new['n']['source']['frame_id'] = 'frame-m'
    with pytest.raises(ValueError, match='Repeated frame'):
        audit.expected_counts(old, manual, new, {'current': {}})


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

    def image(self, frame):
        return frame


@pytest.fixture
def attempt_fixture(tmp_path, monkeypatch):
    r = row('target')
    template = dict(row=row('seed'), polygon=POLYGON)
    trial = dict(target_key='target', template_key='seed', class_id=2,
                 metrics=dict(initial_ncc=.9, rejection='affine_registration_failed'))
    (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'])))
    outcome = dict(target_key='target', class_id=2, reason='registration_or_boundary_rejected')
    args = (tmp_path, {'target': r}, {'target': 'eligible'}, {'history_keys': set()}, {}, {},
            {'seed': template}, {}, {'target': outcome}, Evidence())
    return args, trial


def test_failed_attempt_metrics_are_recomputed(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_success_is_detected(attempt_fixture, monkeypatch):
    args, _ = attempt_fixture
    monkeypatch.setattr(audit, 'transfer', lambda *_: (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_manual_protected_target_must_never_be_attempted(attempt_fixture):
    args, _ = attempt_fixture
    args[5]['target'] = {'target_key': 'target'}
    args[-2]['target']['reason'] = 'saved_manual_source_counted'
    with pytest.raises(ValueError, match='Protected outcome/attempt'):
        audit.audit_attempts(*args)


def test_attempt_inventory_requires_every_compatible_template_in_rank_order(attempt_fixture):
    args, _ = attempt_fixture
    args[6]['second'] = dict(args[6]['seed'], row=row('second'))
    with pytest.raises(ValueError, match='coverage/order'):
        audit.audit_attempts(*args)


def test_false_no_compatible_template_cannot_hide_accepted_candidate(attempt_fixture):
    args, _ = attempt_fixture
    args[6]['seed']['row']['split'] = 'test'
    args[7]['target'] = dict(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'):
        audit.audit_attempts(*args)


def test_current_manual_or_seed_change_blocks_publication(manual_fixture):
    _, _, pose, _, r, *_ = manual_fixture
    gallery = store({}, [])
    frozen = dict(pose=pose, gallery=gallery)
    live = copy.deepcopy(frozen)
    audit.check_live_dependencies(frozen, live, {'manual': {}}, {}, {'manual': {}}, {'manual': r})
    live['pose']['current']['manual']['note'] = 'new human note'
    with pytest.raises(ValueError, match='human dependency changed'):
        audit.check_live_dependencies(frozen, live, {'manual': {}}, {}, {'manual': {}}, {'manual': r})


def test_event_rewrite_blocks_publication_even_when_current_looks_unchanged(manual_fixture):
    _, _, pose, _, r, *_ = manual_fixture
    frozen = dict(pose=pose, gallery=store({}, []))
    live = copy.deepcopy(frozen)
    event_id, key, rev, raw = live['pose']['events'][0]
    live['pose']['events'][0] = event_id, key, rev, raw+' '
    with pytest.raises(ValueError, match='event changed or disappeared'):
        audit.check_live_dependencies(frozen, live, {}, {}, {}, {'manual': r})


def test_failed_main_never_creates_seal(tmp_path, monkeypatch):
    out = tmp_path/'candidate'
    out.mkdir()
    (out/'manifest.json').write_text('{}')
    monkeypatch.setattr(audit, 'OUTPUT', out)
    def fail(*_):
        raise ValueError('unverified polygon')
    monkeypatch.setattr(audit, 'audit', fail)
    with pytest.raises(ValueError, match='unverified polygon'):
        audit.main(['--output', str(out)])
    assert not (out/'verification.json').exists()
    assert json.loads((out/'validation_report.json').read_text())['state'] == 'failed'


def test_success_seal_is_exclusive_and_contains_gallery_contract(tmp_path, monkeypatch):
    out = tmp_path/'candidate'
    out.mkdir()
    (out/'manifest.json').write_text('{}')
    monkeypatch.setattr(audit, 'OUTPUT', out)
    result = dict(state='passed', publication_version=6, proposals_sha256='frozen', proposals_verified=164,
                  extra_public_images=['vertex2_before_after.png'])
    monkeypatch.setattr(audit, 'audit', lambda *_: dict(result))
    audit.main(['--output', str(out)])
    sealed = json.loads((out/'verification.json').read_text())
    assert sealed['publication_version'] == 6 and sealed['proposals_verified'] == 164
    assert sealed['validation_report_sha256'] == audit.digest(out/'validation_report.json')
    before = (out/'verification.json').read_bytes()
    with pytest.raises(ValueError, match='overwrite a frozen verification'):
        audit.main(['--output', str(out)])
    assert (out/'verification.json').read_bytes() == before


def test_exact_sqlite_manual_source_record_rejects_event_raw_change(tmp_path, manual_fixture):
    p, _, pose, *_ = manual_fixture
    snapshot = tmp_path/'snapshot.sqlite3'
    raw = json.dumps(pose['current']['manual'])
    event_id, _, event_revision, event_raw = pose['events'][0]
    with sqlite3.connect(snapshot) as db:
        db.executescript('CREATE TABLE annotations(target_key TEXT,revision INTEGER,payload TEXT);'
                         'CREATE TABLE events(id INTEGER,target_key TEXT,revision INTEGER,payload TEXT);')
        db.execute('INSERT INTO annotations VALUES (?,?,?)', ('manual', 5, raw))
        db.execute('INSERT INTO events VALUES (?,?,?,?)', (event_id, 'manual', event_revision, event_raw))
    record = dict(schema='saved_pose_mask_source_freeze_v1', target_key='manual', snapshot_sha256='snapshot',
        current_revision=5, current_payload_sha256=audit.sha(json.loads(raw)), current_payload_raw=raw,
        current_payload=json.loads(raw), current_payload_raw_sha256=hashlib.sha256(raw.encode()).hexdigest(),
        human_event_id=event_id, human_polygon_revision=event_revision,
        human_event_sha256=hashlib.sha256(event_raw.encode()).hexdigest(), human_event_payload_raw=event_raw,
        human_event_payload=json.loads(event_raw), polygon_sha256=audit.sha(p['polygon']))
    path = tmp_path/'manual_source_records.jsonl'
    path.write_text(json.dumps(record)+'\n')
    audit.check_manual_records(tmp_path, {'manual': p}, snapshot, 'snapshot')
    record['human_event_payload_raw'] = json.dumps(json.loads(event_raw))
    path.write_text(json.dumps(record)+'\n')
    with pytest.raises(ValueError, match='exact SQLite payload/event freeze'):
        audit.check_manual_records(tmp_path, {'manual': p}, snapshot, 'snapshot')


def test_rendering_keeps_all_historical_namespaces_and_manual_self_source(tmp_path):
    source = dict(row=row('seed'), polygon=POLYGON, origin=audit.POSE_ORIGIN)
    inherited = [dict(source, rendering_id=namespace+':seed', polygon=[[1, 1]])
                 for namespace in ('historical', 'refined', 'generation')]
    parent = dict(templates=inherited, rendering_by_target={'old': 'generation:seed'})
    latest = dict(source, rendering_id='quota_generation:seed')
    inventory = dict(templates=copy.deepcopy(inherited)+[latest],
        rendering_by_target={'old': 'generation:seed', 'seed': 'quota_generation:seed'},
        historical_templates=3, generation_template_namespace='quota_generation', generation_templates=1,
        generation_template_keys=['seed'], generation_templates_by_origin={audit.POSE_ORIGIN: 1})
    path = tmp_path/'quota_generation/templates'
    path.mkdir(parents=True)
    (path/'seed.json').write_text(json.dumps(source))
    old = {'old': dict(template={'target_key': 'seed'})}
    manual = {'seed': dict(template={'target_key': 'seed'})}
    args = (tmp_path, inventory, parent, {'seed': source}, old, manual, {})
    audit.check_rendering(*args)
    inventory['rendering_by_target']['old'] = 'quota_generation:seed'
    with pytest.raises(ValueError, match='rendering/source mapping'):
        audit.check_rendering(*args)
    inventory['rendering_by_target']['old'] = 'generation:seed'
    inventory['templates'][1]['polygon'] = ['silently replaced historical polygon']
    with pytest.raises(ValueError, match='Historical rendering namespace/payload'):
        audit.check_rendering(*args)


def test_gallery_save_during_audit_invalidates_saved_pending_counts(manual_fixture):
    _, _, pose, _, r, *_ = manual_fixture
    frozen = dict(pose=pose, gallery=store({}, []))
    live = copy.deepcopy(frozen)
    live['gallery']['current']['old-pending'] = {'revision': 1}
    with pytest.raises(ValueError, match='Gallery saved inventory changed'):
        audit.check_live_dependencies(frozen, live, {}, {}, {}, {'manual': r})


def test_candidate_directory_symlink_cannot_overwrite_historical_report(tmp_path, monkeypatch):
    parent = tmp_path/'parent'
    parent.mkdir()
    (parent/'manifest.json').write_text('{}')
    (parent/'validation_report.json').write_text('historical original')
    link = tmp_path/'candidate'
    link.symlink_to(parent, target_is_directory=True)
    monkeypatch.setattr(audit, 'OUTPUT', link)
    with pytest.raises(ValueError, match='publication-6 outputs directory only'):
        audit.main(['--output', str(link)])
    assert (parent/'validation_report.json').read_text() == 'historical original'
