"""Isolated continuation attacks: raw history, triple provenance and honest counts."""
import ast
import copy
import json
from pathlib import Path
import sqlite3

import pytest

from scripts import verify_mask_under50_requests_v2 as audit
from test_verify_mask_under50_requests import staged, draft, export, write, row, public_pack, count_fixture, KEY, POLYGON


def event(key=KEY, revision=1, marker='old'):
    return dict(target_key=key, revision=revision, polygon=POLYGON, marker=marker)


def gallery(path, values):
    with sqlite3.connect(path) as db:
        db.executescript('CREATE TABLE reviews(target_key TEXT,revision INTEGER,payload TEXT);'
            'CREATE TABLE events(id INTEGER,target_key TEXT,revision INTEGER,payload TEXT);'
            'CREATE TABLE metadata(key TEXT,value TEXT);')
        latest = {}
        for event_id, value in enumerate(values, 1):
            raw = json.dumps(value, ensure_ascii=False, indent=2)
            db.execute('INSERT INTO events VALUES (?,?,?,?)', (event_id, value['target_key'], value['revision'], raw))
            latest[value['target_key']] = (value['revision'], raw)
        for key, (revision, raw) in latest.items():
            db.execute('INSERT INTO reviews VALUES (?,?,?)', (key, revision, raw))
        db.execute('INSERT INTO metadata VALUES (?,?)', ('formal_manifest_sha256', 'f'*64))
    return audit.sources.read_store(path, 'gallery', True)


@pytest.fixture
def extension(tmp_path):
    first = event(marker='原始人工保存')
    next_value = event(revision=2, marker='真实后续人工修订')
    old = gallery(tmp_path/'old.sqlite3', [first])
    fresh = gallery(tmp_path/'fresh.sqlite3', [first, next_value])
    return old, fresh


def test_v2_never_imports_producer_or_builder_or_mutates_v1_globals():
    tree = ast.parse(Path(audit.__file__).read_text())
    for node in ast.walk(tree):
        if isinstance(node, ast.ImportFrom):
            assert 'mask_review_continuation' not in (node.module or '')
            assert 'build_mask' not in (node.module or '')
            assert not any('build_mask' in value.name or value.name == 'mask_review_continuation' for value in node.names)
        if isinstance(node, ast.Assign):
            assert not any(isinstance(target, ast.Attribute) and isinstance(target.value, ast.Name)
                and target.value.id in ('previous', 'sources') for target in node.targets)
        if isinstance(node, ast.Call) and isinstance(node.func, ast.Attribute):
            assert node.func.attr not in ('save_review', 'save_annotation', 'backup')


def test_real_later_revisions_preserve_raw_prefix_without_claiming_current_unchanged(extension):
    old, fresh = extension
    result = audit.check_revision_extension(old, fresh)
    assert result['baseline_gallery_raw_event_prefix_preserved'] == 1
    assert result['appended_gallery_events'] == 1
    assert result['changed_baseline_current_keys'] == [KEY]
    assert result['new_distinct_saved_keys'] == []
    assert result['baseline_current_revisions_preserved_in_history']
    assert result['baseline_gallery_current_unchanged'] is False
    assert old['current'][KEY][1] != fresh['current'][KEY][1]


def test_exact_expected_new_saved_keys_can_extend_without_laundering_old_current_changes(tmp_path):
    old = gallery(tmp_path/'baseline.sqlite3', [event()])
    new_key = 'b'*24
    fresh = gallery(tmp_path/'fresh.sqlite3', [event(), event(new_key, marker='new actual human save')])
    result = audit.check_revision_extension(old, fresh, [new_key])
    assert result['new_distinct_saved_keys'] == [new_key] and result['changed_baseline_current_keys'] == []
    assert result['appended_gallery_events'] == 1
    with pytest.raises(ValueError, match='exact prior ten tasks'):
        audit.check_revision_extension(old, fresh, ['c'*24])


def test_no_change_is_not_fabricated_as_completed_new_work(extension):
    old, _ = extension
    result = audit.check_revision_extension(old, copy.deepcopy(old))
    assert result['appended_gallery_events'] == 0 and result['changed_baseline_current_keys'] == []
    assert result['new_distinct_saved_keys'] == [] and result['baseline_gallery_current_unchanged']


@pytest.mark.parametrize('attack', ['prefix_raw_format', 'prefix_id', 'prefix_revision', 'prefix_order',
    'lost_old_current_raw', 'old_current_semantic_only', 'new_distinct', 'deleted_current', 'orphan_history',
    'metadata', 'schema', 'stale_latest'])
def test_history_or_current_tampering_cannot_be_excused_as_normal_human_continuation(extension, attack):
    old, fresh = copy.deepcopy(extension)
    if attack.startswith('prefix_'):
        entry = list(fresh['events'][0])
        if attack == 'prefix_raw_format':
            entry[3] = json.dumps(json.loads(entry[3]), ensure_ascii=False)
        elif attack == 'prefix_id':
            entry[0] = 999
        elif attack == 'prefix_revision':
            entry[2] = 999
        else:
            fresh['events'].reverse()
        if attack != 'prefix_order':
            fresh['events'][0] = tuple(entry)
    elif attack == 'lost_old_current_raw':
        fresh['histories'][KEY].pop(0)
    elif attack == 'old_current_semantic_only':
        first = list(fresh['histories'][KEY][0]); first[2] = json.dumps(json.loads(first[2]))
        fresh['histories'][KEY][0] = tuple(first)
    elif attack == 'new_distinct':
        fresh['current']['b'*24] = fresh['current'][KEY]
        fresh['histories']['b'*24] = fresh['histories'][KEY]
    elif attack == 'deleted_current':
        fresh['current'].clear(); fresh['histories'].clear()
    elif attack == 'orphan_history':
        fresh['histories']['orphan'] = []
    elif attack == 'metadata':
        fresh['metadata']['formal_manifest_sha256'] = 'changed'
    elif attack == 'schema':
        fresh['fingerprint']['schema_sha256'] = 'changed'
    else:
        fresh['current'][KEY] = old['current'][KEY]
    with pytest.raises(ValueError):
        audit.check_revision_extension(old, fresh)


def test_raw_unicode_event_hashes_are_not_replaced_by_canonical_json_hashes(extension):
    old, fresh = extension
    raw = fresh['events'][-1][3]
    canonical = audit.canonical(audit.sources.loads(raw)).decode()
    assert audit.sources.raw_sha(raw) != audit.sources.raw_sha(canonical)
    audit.check_revision_extension(old, fresh)


def test_event_registry_resolves_exact_publication_hash_target_not_latest_task_key():
    key = KEY
    old = dict(target_key=key, polygon=POLYGON)
    newer = dict(target_key=key, polygon=[[x+1, y] for x, y in POLYGON])
    pubs = {15: dict(path=Path('publication15'), proposals={key: newer})}
    registry = {(15, audit.sha(old), key): dict(kind='independent_preannotation', namespace='v3', proposal=old, path=Path('old-v3'))}
    value = dict(target_key=key, proposal_publication=15, base_proposal_id=audit.sha(old))
    assert audit.sources.resolve_event(value, pubs, registry)['namespace'] == 'v3'
    value['base_proposal_id'] = audit.sha(newer)
    assert audit.sources.resolve_event(value, pubs, registry)['kind'] == 'canonical_publication'
    value['base_proposal_id'] = 'a'*64
    with pytest.raises(ValueError, match='triple'):
        audit.sources.resolve_event(value, pubs, registry)


@pytest.mark.parametrize('field', ['target_key', 'proposal_publication', 'base_proposal_id'])
def test_registry_triple_component_changes_never_fall_back_to_target_key(field):
    proposal = dict(target_key=KEY, polygon=POLYGON)
    registry = {(15, audit.sha(proposal), KEY): dict(kind='independent_preannotation', namespace='v3', proposal=proposal)}
    pubs = {15: dict(proposals={})}
    value = dict(target_key=KEY, proposal_publication=15, base_proposal_id=audit.sha(proposal))
    value[field] = 14 if field == 'proposal_publication' else 'b'*24 if field == 'target_key' else 'b'*64
    with pytest.raises(ValueError):
        audit.sources.resolve_event(value, pubs, registry)


@pytest.fixture
def catalog_case(tmp_path, monkeypatch):
    rows, baseline, catalog = {}, [], []
    pose = dict(current={}, histories={}); fresh = dict(current={}, histories={}, events=[])
    registry = {}; event_audit = []; publications = {15: dict(proposals={}, path=tmp_path/'canonical')}
    for n in range(1494):
        key = f'{n+1:024x}'; source = row(key, cls=11)
        rows[key] = source
        value = dict(target_key=key, revision=1, polygon=copy.deepcopy(POLYGON))
        raw = json.dumps(value, ensure_ascii=False, indent=2)
        if n < 482:
            record = dict(target_key=key, row=source, polygon=copy.deepcopy(POLYGON), origin='saved_pose', revision=1,
                payload_sha256=audit.sha(value), event_raw_sha256=audit.sources.raw_sha(raw), initial_polygon=None,
                batch='pose_manual_no_machine_pair')
            baseline.append(record); catalog.append(copy.deepcopy(record))
            pose['current'][key] = (1, raw, value); pose['histories'][key] = [(n+1, 1, raw, value)]
            continue
        proposal = dict(target_key=key, polygon=copy.deepcopy(POLYGON))
        value.update(proposal_publication=15, base_proposal_id=audit.sha(proposal), proposal_polygon=copy.deepcopy(POLYGON))
        raw = json.dumps(value, ensure_ascii=False, indent=2); event_id = n-481
        reference = dict(kind='independent_preannotation', namespace='v3', proposal=proposal, path=tmp_path/'v3')
        registry[15, audit.sha(proposal), key] = reference
        fresh['current'][key] = (1, raw, value); fresh['histories'][key] = [(event_id, 1, raw, value)]
        fresh['events'].append((event_id, key, 1, raw))
        record = dict(target_key=key, row=source, polygon=copy.deepcopy(POLYGON), origin='saved_gallery', revision=1,
            payload_sha256=audit.sha(value), event_raw_sha256=audit.sources.raw_sha(raw), initial_polygon=copy.deepcopy(POLYGON),
            batch='v3', history_revisions=1, actual_saved_research_reference_not_GT=True)
        baseline.append(copy.deepcopy(record)); catalog.append(record)
        event_audit.append(dict(event_id=event_id, target_key=key, revision=1, payload_raw_sha256=audit.sources.raw_sha(raw),
            proposal_publication=15, base_proposal_id=value['base_proposal_id'], namespace='v3', event_specific_source_verified=True))
    snapshot = tmp_path/'snapshot'
    write(snapshot/'private/source_catalog.jsonl', catalog, True)
    write(snapshot/'private/event_binding_audit.jsonl', event_audit, True)
    checked = []
    def check_event(value, source, reference, publication, formal_sha, evidence):
        assert reference['proposal']['target_key'] == source['target_key'] == value['target_key']
        assert value['base_proposal_id'] == audit.sha(reference['proposal'])
        checked.append(source['target_key'])
    monkeypatch.setattr(audit.sources, 'check_gallery_event', check_event)
    return dict(snapshot=snapshot, baseline=baseline, pose=pose, gallery=fresh, rows=rows,
        publications=publications, registry=registry, catalog=catalog, event_audit=event_audit, checked=checked)


def check_catalog(case):
    return audit.check_fresh_catalog(case['snapshot'], case['baseline'], case['pose'], case['gallery'], case['rows'],
        case['publications'], case['registry'], 'f'*64, None)


def test_fresh_catalog_checks_all1012_events_and1494_actual_sources_not_machine_coverage(catalog_case):
    catalog, references = check_catalog(catalog_case)
    assert len(catalog) == 1494 and len(references) == 1012 and len(catalog_case['checked']) == 1012


@pytest.mark.parametrize('attack', ['catalog_stale_revision', 'catalog_wrong_polygon', 'catalog_raw_hash_canonicalized',
    'event_wrong_base', 'event_wrong_publication', 'event_raw_hash_canonicalized', 'first_polygon', 'pose_polygon', 'frame_duplicate'])
def test_fresh_catalog_and_every_event_raw_hash_are_independently_recomputed(catalog_case, attack):
    case = catalog_case; catalog = case['catalog']; last = catalog[-1]
    if attack == 'catalog_stale_revision':
        last['revision'] = 999
    elif attack == 'catalog_wrong_polygon':
        last['polygon'][0][0] += 1
    elif attack == 'catalog_raw_hash_canonicalized':
        value = case['gallery']['current'][last['target_key']][2]
        last['event_raw_sha256'] = audit.sha(value)
    elif attack in ('event_wrong_base', 'event_wrong_publication'):
        value = copy.deepcopy(case['gallery']['current'][last['target_key']][2])
        value['base_proposal_id' if attack == 'event_wrong_base' else 'proposal_publication'] = 'bad' if attack == 'event_wrong_base' else 14
        entry = list(case['gallery']['events'][-1]); entry[3] = json.dumps(value)
        case['gallery']['events'][-1] = tuple(entry)
    elif attack == 'event_raw_hash_canonicalized':
        entry = case['gallery']['events'][-1]
        case['event_audit'][-1]['payload_raw_sha256'] = audit.sha(audit.sources.loads(entry[3]))
    elif attack == 'first_polygon':
        last['initial_polygon'][0][0] += 1
    elif attack == 'pose_polygon':
        catalog[0]['polygon'][0][0] += 1
    else:
        last['row']['frame_id'] = catalog[-2]['row']['frame_id']
    write(case['snapshot']/'private/source_catalog.jsonl', catalog, True)
    write(case['snapshot']/'private/event_binding_audit.jsonl', case['event_audit'], True)
    with pytest.raises(ValueError):
        check_catalog(case)


def test_registered_old_v3_and_new_under50_proposal_hashes_are_not_interchangeable(catalog_case):
    case = catalog_case; key = case['catalog'][-1]['target_key']
    value = case['gallery']['current'][key][2]
    reference = case['registry'].pop((15, value['base_proposal_id'], key))
    reference = dict(reference, namespace='pallet_mask_under50_requests_v1')
    different = dict(reference['proposal'], polygon=[[x+1, y] for x, y in POLYGON])
    case['registry'][15, audit.sha(different), key] = dict(reference, proposal=different)
    with pytest.raises(ValueError, match='triple'):
        check_catalog(case)


def test_current_latest_catalog_uses_latest_event_namespace_not_first_batch(catalog_case):
    case = catalog_case; key = case['catalog'][-1]['target_key']; old = case['gallery']['current'][key]
    value = copy.deepcopy(old[2]); value['revision'] = 2
    proposal = dict(target_key=key, polygon=[[x+1, y] for x, y in POLYGON]); value['base_proposal_id'] = audit.sha(proposal)
    raw = json.dumps(value, ensure_ascii=False, indent=2); event_id = 1013
    reference = dict(kind='independent_preannotation', namespace='pallet_mask_under50_requests_v1', proposal=proposal, path=Path('new-task'))
    case['registry'][15, audit.sha(proposal), key] = reference
    case['gallery']['current'][key] = (2, raw, value)
    case['gallery']['histories'][key].append((event_id, 2, raw, value))
    case['gallery']['events'].append((event_id, key, 2, raw))
    case['catalog'][-1].update(revision=2, payload_sha256=audit.sha(value), event_raw_sha256=audit.sources.raw_sha(raw),
        history_revisions=2, batch='pallet_mask_under50_requests_v1')
    case['event_audit'].append(dict(event_id=event_id, target_key=key, revision=2, payload_raw_sha256=audit.sources.raw_sha(raw),
        proposal_publication=15, base_proposal_id=value['base_proposal_id'], namespace='pallet_mask_under50_requests_v1', event_specific_source_verified=True))
    write(case['snapshot']/'private/source_catalog.jsonl', case['catalog'], True)
    write(case['snapshot']/'private/event_binding_audit.jsonl', case['event_audit'], True)
    catalog, references = check_catalog(case)
    assert catalog[-1]['batch'] == references[event_id]['namespace'] == 'pallet_mask_under50_requests_v1'
    assert catalog[-1]['initial_polygon'] == POLYGON


@pytest.fixture
def completed_case(tmp_path):
    old_values = [event(f'{n+1:024x}') for n in range(14)]
    additions = [event(f'{n+1:024x}', revision=2, marker='old v3 revision') for n in range(14)]
    additions += [event(f'{n+1:024x}', revision=3, marker='second old v3 revision') for n in range(3)]
    tasks = {f'{n+101:024x}' for n in range(10)}
    registry, refs = {}, {}
    for key in sorted(tasks):
        proposal = dict(target_key=key, polygon=[[x+1, y] for x, y in POLYGON])
        value = event(key, marker='actual completed under50-v1 human save')
        value.update(base_proposal_id=audit.sha(proposal), proposal_publication=15, human_edited=True,
            event_kind='human_mask_gallery_revision')
        additions.append(value)
        registry[15, audit.sha(proposal), key] = dict(kind='independent_preannotation', namespace=audit.PREVIOUS.name, proposal=proposal)
    baseline = gallery(tmp_path/'old.sqlite3', old_values)
    fresh = gallery(tmp_path/'fresh.sqlite3', old_values+additions)
    for event_id, key, _, _ in fresh['events']:
        if key in tasks:
            value = fresh['current'][key][2]
            refs[event_id] = registry[15, value['base_proposal_id'], key]
        else:
            refs[event_id] = dict(kind='independent_preannotation', namespace='v3')
    return fresh, baseline, tasks, registry, refs


def test_all10_real_first_saves_and17_old_revision_events_are_separated_by_registry(completed_case):
    audit.check_completed_previous_tasks(*completed_case)
    fresh, baseline, tasks, _, _ = completed_case
    extension = audit.check_revision_extension(baseline, fresh, tasks)
    assert len(extension['new_distinct_saved_keys']) == 10
    assert len(extension['changed_baseline_current_keys']) == 14
    assert extension['appended_gallery_events'] == 27


@pytest.mark.parametrize('attack', ['copy_draft', 'not_human', 'wrong_event_kind', 'first_revision2', 'two_saves',
    'wrong_namespace', 'wrong_registry_hash', 'wrong_old_namespace', 'missing_completed_key'])
def test_reported10_completions_need_real_changed_human_saves_not_only_same_target_ids(completed_case, attack):
    fresh, baseline, tasks, registry, refs = copy.deepcopy(completed_case)
    key = sorted(tasks)[0]; history = fresh['histories'][key]
    event_id = history[0][0]; value = history[0][3]
    if attack == 'copy_draft':
        value['polygon'] = refs[event_id]['proposal']['polygon']
    elif attack == 'not_human':
        value['human_edited'] = False
    elif attack == 'wrong_event_kind':
        value['event_kind'] = 'assistant_draft'
    elif attack == 'first_revision2':
        history[0] = (event_id, 2, history[0][2], value)
    elif attack == 'two_saves':
        history.append(history[0])
    elif attack == 'wrong_namespace':
        refs[event_id]['namespace'] = 'v3'
    elif attack == 'wrong_registry_hash':
        value['base_proposal_id'] = 'bad'
    elif attack == 'wrong_old_namespace':
        old_event = fresh['events'][len(baseline['events'])]
        refs[old_event[0]]['namespace'] = audit.PREVIOUS.name
    else:
        fresh['current'].pop(key)
    with pytest.raises(ValueError):
        audit.check_completed_previous_tasks(fresh, baseline, tasks, registry, refs)


def test_trained_reference_new_revisions_are_reported_without_replacing_old_training_labels(tmp_path):
    source = dict(target_key=KEY, row=row(), polygon=POLYGON, payload_sha256='a'*64, event_raw_sha256='b'*64)
    record = dict(target_key=KEY, formal_split='train', frame_id=source['row']['frame_id'], class_id=11,
        polygon=POLYGON, source_payload_sha256='a'*64, source_event_raw_sha256='b'*64, development_split='validation')
    path = tmp_path/'frozen_training_records.jsonl'; write(path, [record], True); before = path.read_bytes()
    assert audit.check_trained_revisions(path, [source], [KEY]) == {KEY: 'validation'}
    assert path.read_bytes() == before
    assert audit.check_trained_revisions(path, [source], []) == {}


@pytest.mark.parametrize('field,value', [('formal_split', 'test'), ('source_payload_sha256', 'changed'),
    ('source_event_raw_sha256', 'changed'), ('polygon', [[1, 1], [2, 1], [2, 2]]), ('development_split', '')])
def test_frozen_training_reference_cannot_silently_become_latest_or_cross_formal_split(tmp_path, field, value):
    source = dict(target_key=KEY, row=row(), polygon=POLYGON, payload_sha256='a'*64, event_raw_sha256='b'*64)
    record = dict(target_key=KEY, formal_split='train', frame_id=source['row']['frame_id'], class_id=11,
        polygon=POLYGON, source_payload_sha256='a'*64, source_event_raw_sha256='b'*64, development_split='train')
    record[field] = value
    path = tmp_path/'training.jsonl'; write(path, [record], True)
    with pytest.raises(ValueError):
        audit.check_trained_revisions(path, [source], [KEY])


def test_fresh_source_audit_binding_is_explicit_not_a_faked_old_independent_seal(tmp_path, monkeypatch):
    snapshot = tmp_path/'snapshot'; write(snapshot/'audit.json', dict(state='producer_only'))
    digest = audit.digest(snapshot/'audit.json'); monkeypatch.setattr(audit, 'SOURCE_AUDIT_SHA256', digest)
    audit.check_source_binding(dict(source_audit_sha256=digest), {}, snapshot)
    audit.check_source_binding(dict(source_audit_sha256=digest, source_quality_audit_sha256=audit.previous.QUALITY_SEAL_SHA256), {}, snapshot)
    with pytest.raises(KeyError):
        audit.check_source_binding(dict(source_quality_audit_sha256=audit.previous.QUALITY_SEAL_SHA256), {}, snapshot)
    with pytest.raises(ValueError):
        audit.check_source_binding(dict(source_audit_sha256=audit.previous.QUALITY_SEAL_SHA256), {}, snapshot)
    with pytest.raises(ValueError):
        audit.check_source_binding(dict(source_audit_sha256=digest, source_quality_audit_sha256=digest), {}, snapshot)


def source_claims_case():
    catalog = [dict(row=dict(final_class_id=11)) for _ in range(1494)]
    pose = dict(fingerprint={'schema_sha256': 'pose', 'tables': {'annotations': 'raw'}})
    gallery = dict(fingerprint={'schema_sha256': 'gallery', 'tables': {'events': 'raw'}})
    extension = dict(changed_baseline_current_keys=['old-key'], new_distinct_saved_keys=[f'{n:024x}' for n in range(10)])
    manifests = dict(v1='a', v2='b', v3='c', pallet_mask_under50_requests_v1='d')
    trained = {'old-key': 'train'}
    summary = dict(state='passed_event_provenance_and_distinct_saved_count_not_contour_accuracy',
        total_contours=1494, gallery_contours=1012, gallery_events=1115, pose_contours=482,
        old_raw_event_prefix_preserved=1088, production_annotation_writes=0,
        pose_fingerprint=copy.deepcopy(pose['fingerprint']), gallery_fingerprint=copy.deepcopy(gallery['fingerprint']),
        class_counts={'11': 1494}, changed_baseline_current_keys=['old-key'], new_distinct_saved_keys=copy.deepcopy(extension['new_distinct_saved_keys']),
        actual_changed_baseline_revisions_not_new_distinct_images=True, baseline_current_revisions_preserved_in_history=True,
        frozen_training_dataset_modified=False, source_registry_task_manifests=copy.deepcopy(manifests),
        trained_reference_keys_with_newer_human_revision=copy.deepcopy(trained))
    return summary, catalog, pose, gallery, extension, manifests, trained


def test_producer_source_claims_are_recomputed_not_treated_as_an_independent_seal():
    audit.check_source_claims(*source_claims_case())


@pytest.mark.parametrize('attack', ['new_completed10', 'wrong_events', 'wrong_prefix', 'duplicate_changed_keys',
    'training_rewritten', 'wrong_training_reference', 'wrong_namespace', 'old_fingerprint', 'bool_writes', 'accuracy_claim'])
def test_wrong_source_audit_counts_current_hashes_training_or_accuracy_claims_fail(attack):
    args = source_claims_case(); summary = args[0]
    if attack == 'new_completed10':
        summary['new_distinct_saved_keys'] = []
        summary['total_contours'] = 1484
    elif attack == 'wrong_events':
        summary['gallery_events'] = 1088
    elif attack == 'wrong_prefix':
        summary['old_raw_event_prefix_preserved'] = 1105
    elif attack == 'duplicate_changed_keys':
        summary['changed_baseline_current_keys'] *= 2
    elif attack == 'training_rewritten':
        summary['frozen_training_dataset_modified'] = True
    elif attack == 'wrong_training_reference':
        summary['trained_reference_keys_with_newer_human_revision']['old-key'] = 'validation'
    elif attack == 'wrong_namespace':
        summary['source_registry_task_manifests']['v3'] = 'current-key-not-triple'
    elif attack == 'old_fingerprint':
        summary['gallery_fingerprint']['tables']['events'] = 'old1088'
    elif attack == 'bool_writes':
        summary['production_annotation_writes'] = False
    else:
        summary['state'] = 'passed_contour_accuracy'
    with pytest.raises(ValueError):
        audit.check_source_claims(*args)


def refreshed_count_fixture():
    catalog, inputs, manifest = count_fixture()
    for cls in (11, 16, 17, 19, 20):
        for n in range(2):
            key = f'{cls+100:022x}{n:02x}'
            catalog.append(dict(target_key=key, row=row(key, cls)))
    counts = {str(cls): n for cls, n in audit.Counter(r['row']['final_class_id'] for r in catalog).items()}
    inputs.update(actual_counted_saved_basis=1494, actual_class_counts=counts)
    manifest['actual_human_saved_counts_before'] = copy.deepcopy(counts)
    return catalog, inputs, manifest


def test_actual_counts_refresh_to1494_with_real10_unique_human_saves_without_old_helper_mutation():
    counts = audit.check_count_basis(*refreshed_count_fixture())
    assert sum(counts.values()) == 1494 and {c: counts[c] for c in audit.CLASSES} == audit.EXPECTED_COUNTS
    assert audit.previous.EXPECTED_COUNTS[11] == 17 and audit.EXPECTED_COUNTS[11] == 19


@pytest.mark.parametrize('attack', ['old1484', 'machine1550', 'old_class_counts', 'duplicate_new_frame', 'class50', 'old_manifest_counts'])
def test_refreshed_count_basis_rejects_stale_or_machine_counts_and_duplicate_new_saved_images(attack):
    catalog, inputs, manifest = refreshed_count_fixture()
    if attack == 'old1484':
        inputs['actual_counted_saved_basis'] = 1484
    elif attack == 'machine1550':
        inputs['actual_counted_saved_basis'] = 1550
    elif attack == 'old_class_counts':
        inputs['actual_class_counts']['11'] = 17
    elif attack == 'duplicate_new_frame':
        catalog[-1]['row']['frame_id'] = catalog[-2]['row']['frame_id']
    elif attack == 'class50':
        inputs['actual_class_counts']['20'] = 50
    else:
        manifest['actual_human_saved_counts_before']['11'] = 17
    with pytest.raises(ValueError):
        audit.check_count_basis(catalog, inputs, manifest)


def test_v2_public_report_requires_refreshed_counts_not_stale_v1_counts(public_pack, monkeypatch):
    root, manifest, proposals, _ = public_pack
    monkeypatch.setattr(audit, 'PROJECT', audit.previous.PROJECT)
    with pytest.raises(ValueError, match='stale counts'):
        audit.check_public(root, manifest, proposals)
    page = (root/'report_zh.html').read_text()
    for cls in audit.CLASSES:
        page = page.replace(f'Class {cls}：{audit.previous.EXPECTED_COUNTS[cls]}份', f'Class {cls}：{audit.EXPECTED_COUNTS[cls]}份')
    (root/'report_zh.html').write_text(page); manifest['public_assets']['report_zh.html'] = audit.digest(root/'report_zh.html')
    assert audit.check_public(root, manifest, proposals) == set(manifest['public_assets'])


def test_refresh_preserves_pre_completion_receipt_and_all_staged_sources(tmp_path):
    root = tmp_path/'pack'
    old = dict(actual_counted_saved_basis=1484, continuation_source_audit_sha256=audit.EARLIER_AUDIT_SHA256,
        formal_manifest_sha256='formal', formal_protected={}, configuration_sha256={}, shortlist_sha256='shortlist18',
        prior_request_inventories_sha256={}, shortlisted_classes=list(audit.CLASSES), maximum_issued_per_class=2,
        class_scope=audit.previous.CLASS_SCOPE)
    backup = root/'internal/input_manifest_before_real10_completion.json'; write(backup, old)
    inputs = dict(old, previous_staging_evidence_sha256=audit.digest(backup), actual_counted_saved_basis=1494,
        previous10_actual_completed_saves_at_refresh=10, continuation_source_audit_sha256=audit.SOURCE_AUDIT_SHA256)
    audit.check_refresh_receipt(root, inputs)
    inputs['shortlist_sha256'] = 'changed_staged_selection'
    with pytest.raises(ValueError):
        audit.check_refresh_receipt(root, inputs)


def test_previous18_staged_sources_including_unsaved10_and8_rejected_remain_global_exclusions(tmp_path):
    own = tmp_path/'outputs/pallet_mask_under50_requests_v2'; old = tmp_path/'outputs/pallet_mask_under50_requests_v1'
    rows = {f'{n+1:024x}': row(f'{n+1:024x}') for n in range(18)}
    write(old/'internal/shortlist.jsonl', [dict(target_key=key, approved=False) for key in rows], True)
    write(old/'requests.jsonl', [dict(target_key=key) for key in list(rows)[:10]], True)
    write(own/'internal/shortlist.jsonl', [dict(target_key='f'*24)], True)
    hashes, keys = audit.previous.prior_inspections(tmp_path, own, rows)
    assert keys == set(rows) and len(keys) == 18 and len(hashes) == 2


def test_reused_native_draft_and_export_helpers_do_not_claim_human_or_accuracy(staged):
    proposal, task = draft(staged)
    image_sha = audit.digest(staged['formal']/staged['row']['image'])
    audit.previous.check_draft(proposal, task, staged['record'], staged['decision'], 'e'*64, 'f'*64, image_sha)
    exported = export(staged)
    audit.previous.check_exports(staged['root'], exported, staged['record'], image_sha)
    assert proposal['counts_as_completed_annotation'] is False and proposal['propagation_seed_eligible'] is False
    task['preserve_existing_pose_until_intentional_human_edit'] = False
    with pytest.raises(ValueError):
        audit.previous.check_draft(proposal, task, staged['record'], staged['decision'], 'e'*64, 'f'*64, image_sha)


@pytest.fixture
def seal_root(tmp_path, monkeypatch):
    monkeypatch.setattr(audit, 'PROJECT', tmp_path)
    root = tmp_path/'outputs/pallet_mask_under50_requests_v2'; root.mkdir(parents=True)
    write(root/'manifest.json', {})
    return root


def test_unfinished_v2_never_audited_or_polled_without_completion(seal_root):
    def forbidden(_):
        pytest.fail('unfinished staging was audited')
    with pytest.raises(ValueError, match='completion'):
        audit.seal(seal_root, auditor=forbidden)
    assert set(audit.inventory(seal_root)) == {'manifest.json'}


def test_only_passed_audit_creates_identical_exclusive_private_v2_twins(seal_root):
    result = dict(state='passed', request_count=10, semantic_contour_accuracy_established=False)
    audit.seal(seal_root, producer_complete=True, auditor=lambda _: result)
    assert (seal_root/audit.SEALS[0]).read_bytes() == (seal_root/audit.SEALS[1]).read_bytes() == audit.canonical(result)+b'\n'
    assert all((seal_root/name).stat().st_mode & 0o777 == 0o600 for name in audit.SEALS)
    with pytest.raises(ValueError, match='Never overwrite'):
        audit.seal(seal_root, producer_complete=True, auditor=lambda _: result)


@pytest.mark.parametrize('state', ['pending', 'failed', 'passed_event_provenance'])
def test_nonpassing_task_audit_cannot_be_masqueraded_as_independent_seal(seal_root, state):
    with pytest.raises(ValueError, match='did not pass'):
        audit.seal(seal_root, producer_complete=True, auditor=lambda _: dict(state=state))
    assert set(audit.inventory(seal_root)) == {'manifest.json'}


def test_audit_failure_leaves_no_passed_seal_or_extra_failure_file(seal_root):
    def failure(_):
        raise ValueError('synthetic changed live store')
    with pytest.raises(ValueError):
        audit.seal(seal_root, producer_complete=True, auditor=failure)
    assert set(audit.inventory(seal_root)) == {'manifest.json'}


def test_second_seal_race_never_deletes_other_writers_work(seal_root):
    def raced(root):
        (root/'independent_verification.json').write_bytes(b'other writer')
        return dict(state='passed')
    with pytest.raises(FileExistsError):
        audit.seal(seal_root, producer_complete=True, auditor=raced)
    assert not (seal_root/'verification.json').exists()
    assert (seal_root/'independent_verification.json').read_bytes() == b'other writer'


def test_v1_output_or_symlink_cannot_receive_v2_seals(seal_root):
    old = seal_root.parent/'pallet_mask_under50_requests_v1'; old.mkdir(); write(old/'manifest.json', {})
    with pytest.raises(ValueError, match='exact new v2'):
        audit.seal(old, producer_complete=True, auditor=lambda _: dict(state='passed'))
    linked = seal_root.parent/'alias'; linked.symlink_to(seal_root, target_is_directory=True)
    with pytest.raises(ValueError):
        audit.seal(linked, producer_complete=True, auditor=lambda _: dict(state='passed'))
