"""Isolated fourth-batch attacks; no staging audit, live save or service access."""
import ast
import copy
import json
from pathlib import Path

import pytest

from scripts import verify_mask_under50_requests_v4 as audit
from test_verify_mask_under50_requests import staged, public_pack, draft, export, write, row, KEY, POLYGON
from test_verify_mask_under50_requests_v2 import catalog_case, gallery, event
from test_verify_mask_under50_requests_v3 import (
    completed_batches as previous_completed, fresh_catalog as previous_catalog,
    count_case as previous_count_case, source_claims_case as previous_source_claims_case,
)


def test_no_producer_builder_import_helper_global_mutation_or_real_save():
    tree = ast.parse(Path(audit.__file__).read_text())
    for node in ast.walk(tree):
        if isinstance(node, (ast.Import, ast.ImportFrom)):
            names = [value.name for value in node.names] + [getattr(node, 'module', '') or '']
            assert not any('build_mask' in name or 'mask_review_continuation' in name for name in names)
        if isinstance(node, (ast.Assign, ast.AnnAssign, ast.AugAssign)):
            targets = node.targets if isinstance(node, ast.Assign) else [node.target]
            assert not any(isinstance(target, ast.Attribute) and isinstance(target.value, ast.Name)
                and target.value.id in ('geometry', 'continuation', 'previous', 'sources') for target in targets)
        if isinstance(node, ast.Call) and isinstance(node.func, ast.Attribute):
            assert node.func.attr not in ('save_review', 'save_annotation', 'backup', 'setup')
            if isinstance(node.func.value, ast.Name) and node.func.value.id in ('geometry', 'previous', 'continuation'):
                assert node.func.attr not in ('audit', 'check_count_basis', 'check_issued_inventory', 'check_sources')


def test_direct_audit_cannot_read_unready_output(tmp_path, monkeypatch):
    monkeypatch.setattr(audit, 'inventory', lambda _: pytest.fail('unfinished staging read'))
    with pytest.raises(ValueError, match='READY'):
        audit.audit(tmp_path/'does-not-exist')
    monkeypatch.setattr(audit, 'SOURCE_AUDIT_SHA256', None)
    with pytest.raises(ValueError, match='not pinned'):
        audit.audit(tmp_path/'does-not-exist', producer_complete=True)


@pytest.fixture
def sealed_roots(tmp_path, monkeypatch):
    outputs = tmp_path/'outputs'; pins = {}
    for number in (1, 2, 3):
        namespace = f'pallet_mask_under50_requests_v{number}'; root = outputs/namespace
        write(root/'manifest.json', dict(number=number))
        for name in audit.SEALS:
            write(root/name, dict(state='passed', number=number))
        pins[namespace] = dict(manifest_sha256=audit.digest(root/'manifest.json'), verification_sha256=audit.digest(root/'verification.json'))
    monkeypatch.setattr(audit, 'SEALED_PACK_PINS', pins)
    return outputs, outputs/'pallet_mask_under50_requests_v4', pins


def test_registry_requires_three_pinned_prior_packs_and_never_own_partial_pack(sealed_roots):
    outputs, own, pins = sealed_roots; write(own/'verification.json', {})
    assert set(audit.discover_sealed_packs(outputs, own)) == set(pins)


@pytest.mark.parametrize('attack', ['missing', 'half', 'manifest', 'twins', 'unknown', 'symlink'])
def test_registry_rejects_missing_altered_unpinned_or_symlink_evidence(sealed_roots, attack):
    outputs, own, _ = sealed_roots; root = outputs/'pallet_mask_under50_requests_v3'
    if attack == 'missing':
        for name in audit.SEALS:
            (root/name).unlink()
    elif attack == 'half':
        (root/'independent_verification.json').unlink()
    elif attack == 'manifest':
        write(root/'manifest.json', dict(altered=True))
    elif attack == 'twins':
        write(root/'independent_verification.json', dict(altered=True))
    elif attack == 'unknown':
        for name in audit.SEALS:
            write(outputs/'pallet_mask_under50_requests_v5'/name, dict(state='passed'))
    else:
        (root/'manifest.json').rename(root/'real_manifest.json')
        (root/'manifest.json').symlink_to(root/'real_manifest.json')
    with pytest.raises(ValueError):
        audit.discover_sealed_packs(outputs, own)


@pytest.fixture
def completed_batches(previous_completed, tmp_path):
    old_fresh, baseline, task_keys, registry, refs = previous_completed
    namespace = 'pallet_mask_under50_requests_v3'; task_keys[namespace] = {f'{n+301:024x}' for n in range(7)}
    values = [audit.sources.loads(raw) for _, _, _, raw in old_fresh['events']]
    for key in sorted(task_keys[namespace]):
        proposal = dict(target_key=key, polygon=[[x+1, y] for x, y in POLYGON])
        value = event(key, marker='真实完成第三批保存')
        value.update(base_proposal_id=audit.sha(proposal), proposal_publication=15,
            human_edited=True, event_kind='human_mask_gallery_revision')
        values.append(value)
        registry[15, audit.sha(proposal), key] = dict(kind='independent_preannotation', namespace=namespace, proposal=proposal)
    fresh = gallery(tmp_path/'current-v4.sqlite3', values)
    for event_id, key, _, raw in fresh['events']:
        if key in task_keys[namespace]:
            value = audit.sources.loads(raw); refs[event_id] = registry[15, value['base_proposal_id'], key]
    return fresh, baseline, task_keys, registry, refs


def test26_completed_images_have28_saves_plus17_old_revisions_not45_new_labels(completed_batches):
    extension, completed = audit.check_saved_batches(*completed_batches)
    assert list(completed.values()) == [10, 9, 7]
    assert extension['appended_gallery_events'] == 45 and len(extension['new_distinct_saved_keys']) == 26
    assert len(extension['changed_baseline_current_keys']) == 14
    assert extension['baseline_gallery_current_unchanged'] is False
    assert extension['baseline_current_revisions_preserved_in_history']


@pytest.mark.parametrize('attack', ['raw_prefix', 'new_key', 'missing_v3_save', 'namespace', 'hash', 'draft_copy',
    'assistant_event', 'first_revision', 'route', 'old_raw_revision', 'missing_pack', 'wrong_publication'])
def test_real_completions_require_all_exact_history_package_triples_and_changed_polygons(completed_batches, attack):
    fresh, baseline, tasks, registry, refs = copy.deepcopy(completed_batches)
    namespace = 'pallet_mask_under50_requests_v3'; key = sorted(tasks[namespace])[0]
    history = fresh['histories'][key]; event_id = history[-1][0]
    if attack == 'raw_prefix':
        entry = list(fresh['events'][0]); entry[3] = json.dumps(json.loads(entry[3])); fresh['events'][0] = tuple(entry)
    elif attack == 'new_key':
        fresh['current']['unknown'] = fresh['current'][key]; fresh['histories']['unknown'] = history
    elif attack == 'missing_v3_save':
        fresh['current'].pop(key); fresh['histories'].pop(key)
    elif attack == 'namespace':
        refs[event_id]['namespace'] = 'pallet_mask_under50_requests_v2'
    elif attack == 'hash':
        history[-1][3]['base_proposal_id'] = 'bad'
    elif attack == 'draft_copy':
        history[-1][3]['polygon'] = refs[event_id]['proposal']['polygon']
        fresh['current'][key][2]['polygon'] = refs[event_id]['proposal']['polygon']
    elif attack == 'assistant_event':
        history[-1][3]['human_edited'] = False
    elif attack == 'first_revision':
        entry = list(history[0]); entry[1] = 2; history[0] = tuple(entry)
    elif attack == 'route':
        refs[fresh['events'][len(baseline['events'])][0]]['namespace'] = namespace
    elif attack == 'old_raw_revision':
        old_key = next(iter(baseline['current'])); first = list(fresh['histories'][old_key][0])
        first[2] = json.dumps(json.loads(first[2])); fresh['histories'][old_key][0] = tuple(first)
    elif attack == 'missing_pack':
        tasks.pop('pallet_mask_under50_requests_v1')
    else:
        proposal_sha = history[-1][3]['base_proposal_id']
        registry[14, proposal_sha, key] = registry.pop((15, proposal_sha, key))
    with pytest.raises(ValueError):
        audit.check_saved_batches(fresh, baseline, tasks, registry, refs)


@pytest.fixture
def fresh_catalog(previous_catalog):
    case = previous_catalog
    for n in range(1503, 1510):
        key = f'{n+1:024x}'; source = row(key); proposal = dict(target_key=key, polygon=copy.deepcopy(POLYGON))
        value = event(key, marker='真实第三批来源')
        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
        case['rows'][key] = source; case['gallery']['current'][key] = (1, raw, value)
        case['gallery']['histories'][key] = [(event_id, 1, raw, value)]; case['gallery']['events'].append((event_id, key, 1, raw))
        case['registry'][15, audit.sha(proposal), key] = dict(kind='independent_preannotation', namespace='pallet_mask_under50_requests_v3',
            proposal=proposal, path=Path('synthetic-v3'))
        case['catalog'].append(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='pallet_mask_under50_requests_v3', history_revisions=1, actual_saved_research_reference_not_GT=True))
        case['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='pallet_mask_under50_requests_v3', event_specific_source_verified=True))
    # Distinct current sources are1028 while all1133 raw events still need checks.
    key = case['catalog'][-1]['target_key']; record = case['catalog'][-1]
    for revision in range(2, 107):
        value = copy.deepcopy(case['gallery']['current'][key][2]); value['revision'] = revision
        value['marker'] = f'后续修订{revision}'; value['polygon'][0][0] = 21+revision/1000
        raw = json.dumps(value, ensure_ascii=False, indent=2); event_id = 1027+revision
        case['gallery']['current'][key] = (revision, raw, value)
        case['gallery']['histories'][key].append((event_id, revision, raw, value)); case['gallery']['events'].append((event_id, key, revision, raw))
        case['event_audit'].append(dict(event_id=event_id, target_key=key, revision=revision, payload_raw_sha256=audit.sources.raw_sha(raw),
            proposal_publication=15, base_proposal_id=value['base_proposal_id'], namespace='pallet_mask_under50_requests_v3', event_specific_source_verified=True))
        record.update(polygon=copy.deepcopy(value['polygon']), revision=revision, payload_sha256=audit.sha(value),
            event_raw_sha256=audit.sources.raw_sha(raw), history_revisions=revision)
    write(case['snapshot']/'private/source_catalog.jsonl', case['catalog'], True)
    write(case['snapshot']/'private/event_binding_audit.jsonl', case['event_audit'], True)
    return case


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 test1510_sources_are482_pose1028_gallery_and_all1133_events_are_checked(fresh_catalog):
    catalog, refs = check_catalog(fresh_catalog)
    assert len(catalog) == 1510 and len(fresh_catalog['gallery']['current']) == 1028
    assert len(refs) == len(fresh_catalog['checked']) == 1133


@pytest.mark.parametrize('attack', ['stale_polygon', 'canonical_raw_hash', 'namespace', 'duplicate_frame', 'original_box',
    'event_raw_hash', 'event_target', 'event_revision', 'event_publication', 'event_hash', 'duplicate_event_id', 'stale_current'])
def test_catalog_cannot_recount_stale_or_forged_latest_raw_event_evidence(fresh_catalog, attack):
    case = fresh_catalog; record = case['catalog'][-1]; key = record['target_key']
    if attack == 'stale_polygon':
        record['polygon'][0][0] += 1
    elif attack == 'canonical_raw_hash':
        record['event_raw_sha256'] = audit.sha(case['gallery']['current'][key][2])
    elif attack == 'namespace':
        record['batch'] = 'pallet_mask_under50_requests_v2'
    elif attack == 'duplicate_frame':
        record['row']['frame_id'] = case['catalog'][-2]['row']['frame_id']
    elif attack == 'original_box':
        case['gallery']['current'][key][2]['polygon'] = [[20, 30], [80, 30], [80, 50], [20, 50]]
    elif attack == 'event_raw_hash':
        case['event_audit'][-1]['payload_raw_sha256'] = audit.sha(case['gallery']['current'][key][2])
    elif attack.startswith('event_'):
        entry = list(case['gallery']['events'][-1]); value = audit.sources.loads(entry[3])
        if attack == 'event_target':
            entry[1] = case['catalog'][-2]['target_key']
        elif attack == 'event_revision':
            entry[2] = 999
        else:
            value['proposal_publication' if attack == 'event_publication' else 'base_proposal_id'] = 14 if attack == 'event_publication' else 'bad'
            entry[3] = json.dumps(value)
        case['gallery']['events'][-1] = tuple(entry)
    elif attack == 'duplicate_event_id':
        entry = list(case['gallery']['events'][-1]); entry[0] = 1; case['gallery']['events'][-1] = tuple(entry)
    else:
        history = case['gallery']['histories'][key]; earlier = history[-2]
        case['gallery']['current'][key] = earlier[1:]
    write(case['snapshot']/'private/source_catalog.jsonl', case['catalog'], True)
    write(case['snapshot']/'private/event_binding_audit.jsonl', case['event_audit'], True)
    with pytest.raises((ValueError, AssertionError)):
        check_catalog(case)


def count_case():
    catalog, inputs, manifest = previous_count_case()
    for cls, count in {11: 2, 16: 2, 17: 2, 20: 1}.items():
        for n in range(count):
            key = f'{cls+400:022x}{n:02x}'; catalog.append(dict(target_key=key, row=row(key, cls)))
    counts = audit.Counter(r['row']['final_class_id'] for r in catalog)
    inputs.update(actual_counted_saved_basis=1510, actual_class_counts={str(c): n for c, n in counts.items()}, shortlisted_classes=list(audit.CLASSES))
    manifest.update(actual_human_saved_counts_before=copy.deepcopy(inputs['actual_class_counts']), filter_classes=list(audit.CLASSES))
    return catalog, inputs, manifest


def test_actual1510_counts_leave_five_classes_and_exclude_class20_without_mutating_old_scopes():
    counts = audit.check_count_basis(*count_case())
    assert sum(counts.values()) == 1510 and counts[20] == 50 and counts[17] == 49
    assert tuple(c for c in sorted(counts) if counts[c] < 50) == (11, 12, 16, 17, 19)
    assert audit.geometry.CLASSES == audit.previous.CLASSES == (11, 12, 16, 17, 19, 20)
    assert audit.previous.EXPECTED_COUNTS[20] == 49 and audit.geometry.EXPECTED_COUNTS[20] == 45


@pytest.mark.parametrize('attack', ['stale1503', 'machine1550', 'old6scope', 'class20under50', 'class17old', 'duplicate_frame', 'duplicate_key', 'bool_count'])
def test_wrong_saved_denominator_or_five_class_scope_fails(attack):
    catalog, inputs, manifest = count_case()
    if attack == 'stale1503':
        inputs['actual_counted_saved_basis'] = 1503
    elif attack == 'machine1550':
        inputs['actual_counted_saved_basis'] = 1550
    elif attack == 'old6scope':
        manifest['filter_classes'].append(20)
    elif attack == 'class20under50':
        inputs['actual_class_counts']['20'] = 49
    elif attack == 'class17old':
        inputs['actual_class_counts']['17'] = 47
    elif attack == 'duplicate_frame':
        catalog[-1]['row']['frame_id'] = catalog[-2]['row']['frame_id']
    elif attack == 'duplicate_key':
        catalog[-1]['target_key'] = catalog[-2]['target_key']
    else:
        inputs['actual_class_counts']['11'] = True
    with pytest.raises(ValueError):
        audit.check_count_basis(catalog, inputs, manifest)


def issued_case(classes=(11, 16, 17), count=2):
    staged_rows, proposals, decisions = [], [], {}
    for cls in classes:
        for n in range(1 if cls == 17 else 3):
            key = f'{cls:022x}{n:02x}'; record = dict(target_key=key, class_id=cls); staged_rows.append(record)
            decisions[key] = dict(approved=n < count)
            if n < count:
                proposals.append(copy.deepcopy(record))
    counts = audit.Counter(p['class_id'] for p in proposals)
    manifest = dict(request_count=len(proposals), class_counts={str(c): n for c, n in counts.items()}, classes=sorted(counts))
    return proposals, copy.deepcopy(proposals), staged_rows, decisions, manifest, audit.EXPECTED_COUNTS.copy()


def test_missing_dark_classes_can_all_be_withheld_and_five_valid_issues_are_not_forced_to9():
    args = issued_case(); counts, withheld = audit.check_issued_inventory(*args)
    assert counts == {11: 2, 16: 2, 17: 1} and len(withheld) == 2
    assert 12 not in counts and 19 not in counts
    full_stage = [dict(class_id=c) for c in audit.CLASSES for _ in range(1 if c == 17 else 3)]
    assert len(full_stage) == 13
    audit.check_staged_limits(full_stage, audit.EXPECTED_COUNTS)


@pytest.mark.parametrize('classes', [(17, 17), (20,), (11, 11, 11, 11), (22,)])
def test_staged_caps_are13_total3_per_class_class17only1_and_no_class20(classes):
    with pytest.raises(ValueError, match='Class17 permits only1; Class20 excluded'):
        audit.check_staged_limits([dict(class_id=c) for c in classes], audit.EXPECTED_COUNTS)


@pytest.mark.parametrize('attack', ['class17two', 'class20', 'third_per_class', 'unpaired', 'order', 'bool_approval', 'bool_count', 'foreign_key', 'approved_missing'])
def test_issue_gap_caps_pairing_decisions_and_scope_cannot_be_relaxed(attack):
    args = list(issued_case()); proposals, tasks, staged_rows, decisions, manifest, _ = args
    if attack in ('class17two', 'class20'):
        cls = 17 if attack == 'class17two' else 20
        for record in (proposals[0], tasks[0], staged_rows[0]):
            record['class_id'] = cls
        counts = audit.Counter(p['class_id'] for p in proposals)
        manifest.update(class_counts={str(c): n for c, n in counts.items()}, classes=sorted(counts))
    elif attack == 'third_per_class':
        args = list(issued_case(count=3))
    elif attack == 'unpaired':
        tasks.pop()
    elif attack == 'order':
        tasks.reverse()
    elif attack == 'bool_approval':
        decisions[proposals[0]['target_key']]['approved'] = 1
    elif attack == 'bool_count':
        manifest['request_count'] = True
    elif attack == 'foreign_key':
        proposals[0]['target_key'] = tasks[0]['target_key'] = 'f'*24
    else:
        decisions[staged_rows[2]['target_key']]['approved'] = True
    with pytest.raises(ValueError):
        audit.check_issued_inventory(*args)


def test_all52_previous_staged_sources_including_rejects_are_globally_excluded(tmp_path):
    own = tmp_path/'outputs/pallet_mask_under50_requests_v4'; rows = {}
    for version, staged_count, issued_count in ((1, 18, 10), (2, 18, 9), (3, 16, 7)):
        records = []
        for n in range(staged_count):
            key = f'{version:022x}{n:02x}'; rows[key] = row(key); records.append(dict(target_key=key, approved=False))
        root = tmp_path/f'outputs/pallet_mask_under50_requests_v{version}'
        write(root/'internal/shortlist.jsonl', records, True); write(root/'requests.jsonl', records[:issued_count], True)
    write(own/'internal/shortlist.jsonl', [dict(target_key='f'*24)], True)
    hashes, keys = audit.geometry.prior_inspections(tmp_path, own, rows)
    assert len(keys) == 52 and len(hashes) == 6
    assert [pins['staged_count'] for pins in audit.SEALED_PACK_PINS.values()] == [18, 18, 16]


@pytest.mark.parametrize('attack', ['key', 'frame', 'bytes'])
def test_global_key_frame_and_native_byte_dedup_still_uses_unchanged_geometry_helper(staged, attack):
    old = row('b'*24)
    if attack == 'frame':
        old['frame_id'] = staged['row']['frame_id']
    path = staged['formal']/old['image']; path.write_bytes((staged['formal']/staged['row']['image']).read_bytes())
    rows = {KEY: staged['row'], old['target_key']: old}; forbidden = {KEY if attack == 'key' else old['target_key']}
    with pytest.raises(ValueError, match='protected source|duplicate image bytes'):
        audit.geometry.check_staged(staged['root'], [staged['record']], {KEY: staged['decision']}, rows,
            staged['formal'], staged['evidence'], dict(current={}, histories={}), forbidden)


def test_public_page_requires_actual_five_counts_and_five_filters_not_old_six(public_pack, monkeypatch):
    root, manifest, proposals, _ = public_pack; monkeypatch.setattr(audit, 'PROJECT', audit.geometry.PROJECT)
    with pytest.raises(ValueError, match='count_table_scope'):
        audit.check_public(root, manifest, proposals)
    page = (root/'report_zh.html').read_text()
    for c in audit.CLASSES:
        page = page.replace(f'Class {c}：{audit.geometry.EXPECTED_COUNTS[c]}份', f'Class {c}：{audit.EXPECTED_COUNTS[c]}份')
    page = page.replace('、Class 20：45份', '').replace('<option value="20">20</option>', '')
    (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'])
    page += 'Class 20：50份'; (root/'report_zh.html').write_text(page)
    manifest['public_assets']['report_zh.html'] = audit.digest(root/'report_zh.html')
    with pytest.raises(ValueError, match='count_table_scope'):
        audit.check_public(root, manifest, proposals)


def test_explicit_v6_source_audit_and_catalog_bindings_are_not_historical_quality_seal(tmp_path, monkeypatch):
    monkeypatch.setattr(audit, 'PROJECT', tmp_path)
    snapshot = tmp_path/'outputs/pallet_mask_continuation_sources_v6'
    write(snapshot/'audit.json', dict(source='completed synthetic v6'))
    write(snapshot/'private/source_catalog.jsonl', [], True)
    value = audit.digest(snapshot/'audit.json'); monkeypatch.setattr(audit, 'SOURCE_AUDIT_SHA256', value)
    inputs = dict(source_audit_sha256=value, continuation_source_audit_sha256=value,
        continuation_source_directory='outputs/pallet_mask_continuation_sources_v6',
        continuation_source_catalog_sha256=audit.digest(snapshot/'private/source_catalog.jsonl'))
    manifest = dict(source_audit_sha256=value, continuation_source_audit_sha256=value)
    audit.check_source_binding(inputs, manifest, snapshot)
    for field in inputs:
        bad = dict(inputs); bad[field] = audit.geometry.QUALITY_SEAL_SHA256
        with pytest.raises(ValueError):
            audit.check_source_binding(bad, manifest, snapshot)
    with pytest.raises(KeyError):
        audit.check_source_binding(inputs, {}, snapshot)


def source_claims_case():
    summary, catalog, pose, gallery_store, extension, manifests, trained = previous_source_claims_case()
    catalog.extend(dict(row=dict(final_class_id=11)) for _ in range(7))
    extension['new_distinct_saved_keys'] = [f'{n:024x}' for n in range(26)]
    manifests['pallet_mask_under50_requests_v3'] = 'f'
    summary.update(total_contours=1510, gallery_contours=1028, gallery_events=1133, class_counts={'11': 1510},
        new_distinct_saved_keys=copy.deepcopy(extension['new_distinct_saved_keys']), source_registry_task_manifests=copy.deepcopy(manifests))
    return summary, catalog, pose, gallery_store, extension, manifests, trained


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


def test_historical_null_namespaces_and_new_pack_routes_form_canonical_json_keys():
    references = {1: dict(namespace=None), 2: dict(namespace='v3'), 3: dict(namespace='pallet_mask_under50_requests_v3')}
    counts = audit.event_namespace_counts(references)
    assert counts == {'historical_gallery': 1, 'v3': 1, 'pallet_mask_under50_requests_v3': 1}
    assert json.loads(audit.canonical(dict(gallery_event_namespace_counts=counts)))['gallery_event_namespace_counts'] == counts


@pytest.mark.parametrize('attack', ['stale1503', 'old1126', 'not26', 'training_changed', 'no_v3', 'fingerprint', 'accuracy', 'bool_writes'])
def test_false_source_summary_claims_are_rejected(attack):
    args = source_claims_case(); summary = args[0]
    if attack == 'stale1503':
        summary['total_contours'] = 1503
    elif attack == 'old1126':
        summary['gallery_events'] = 1126
    elif attack == 'not26':
        summary['new_distinct_saved_keys'].pop()
    elif attack == 'training_changed':
        summary['frozen_training_dataset_modified'] = True
    elif attack == 'no_v3':
        summary['source_registry_task_manifests'].pop('pallet_mask_under50_requests_v3')
    elif attack == 'fingerprint':
        summary['gallery_fingerprint']['schema_sha256'] = 'old'
    elif attack == 'accuracy':
        summary['state'] = 'passed_accuracy'
    else:
        summary['production_annotation_writes'] = False
    with pytest.raises(ValueError):
        audit.check_source_claims(*args)


def test_four_point_schema_and_independent_raster_exports_keep_false_eligibility_flags(staged):
    proposal, task = draft(staged); image_sha = audit.digest(staged['formal']/staged['row']['image'])
    audit.geometry.check_draft(proposal, task, staged['record'], staged['decision'], 'e'*64, 'f'*64, image_sha)
    audit.geometry.check_exports(staged['root'], export(staged), staged['record'], image_sha)
    assert len(proposal['polygon']) == 4 and all(proposal[field] is False for field in audit.geometry.FALSE_FLAGS)


@pytest.fixture
def frozen_training(tmp_path, monkeypatch):
    root = tmp_path/'frozen-training'; records = [dict(target_key=f'{n:024x}') for n in range(229)]
    write(root/'private/training_records.jsonl', records, True)
    for directory in ('dataset', 'dataset_rfdetr', 'private/native_masks'):
        path = root/directory/'synthetic.png'; path.parent.mkdir(parents=True); path.write_bytes(b'frozen native bytes')
    files = audit.inventory(root)
    manifest = dict(files=files, **dict.fromkeys(('automatic_training_eligible', 'ground_truth_eligible',
        'human_mask_confirmed', 'human_pose_confirmed', 'robot_command_eligible'), False))
    write(root/'dataset_manifest.json', manifest)
    monkeypatch.setattr(audit, 'TRAINING_PINS', {name: audit.digest(root/name) for name in ('dataset_manifest.json', 'private/training_records.jsonl')})
    return root


def test_frozen229_source_keys_and_dataset_labels_are_verified_read_only(frozen_training):
    before = audit.inventory(frozen_training); assert audit.check_frozen_training(frozen_training)
    assert audit.inventory(frozen_training) == before


@pytest.mark.parametrize('attack', ['add_label', 'change_label', 'add_source_key', 'change_source_key'])
def test_no_new_saved_source_is_automatically_added_to_frozen_training(frozen_training, attack):
    if attack == 'add_label':
        (frozen_training/'dataset/new-label.json').write_text('{}')
    elif attack == 'change_label':
        (frozen_training/'private/native_masks/synthetic.png').write_bytes(b'newer human revision')
    else:
        path = frozen_training/'private/training_records.jsonl'; records = audit.read_jsonl(path)
        if attack == 'add_source_key':
            records.append(dict(target_key='f'*24))
        else:
            records[0]['target_key'] = 'f'*24
        write(path, records, True)
    with pytest.raises(ValueError):
        audit.check_frozen_training(frozen_training)


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


def test_no_ready_notification_means_no_audit_or_seals(seal_root):
    with pytest.raises(ValueError, match='READY'):
        audit.seal(seal_root, auditor=lambda _: pytest.fail('unready staging audited'))
    assert set(audit.inventory(seal_root)) == {'manifest.json'}


def test_ready_success_creates_identical_private_exclusive_seals(seal_root):
    result = dict(state='passed', request_count=5, 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', ['failed', 'pending', 'passed_event_provenance'])
def test_failed_or_partial_audit_never_creates_passed_seals(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_race_on_second_seal_preserves_other_writer_and_rolls_back_only_own_file(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_old_output_or_alias_cannot_receive_v4_seals(seal_root):
    old = seal_root.parent/'pallet_mask_under50_requests_v3'; write(old/'manifest.json', {})
    alias = seal_root.parent/'alias'; alias.symlink_to(seal_root, target_is_directory=True)
    for root in (old, alias):
        with pytest.raises(ValueError, match='exact new v4'):
            audit.seal(root, producer_complete=True, auditor=lambda _: dict(state='passed'))
