"""Synthetic, isolated adversarial tests; never audit staging or save real events."""
import ast
import copy
import json
from pathlib import Path
import sqlite3

import numpy as np
from PIL import Image, ImageDraw
import pytest

from scripts import verify_mask_under50_requests as audit


KEY = 'a'*24
POLYGON = [[21, 32], [78, 31], [77, 48], [22, 49]]


def write(path, value, jsonl=False):
    path.parent.mkdir(parents=True, exist_ok=True)
    path.write_bytes(b''.join(audit.canonical(v)+b'\n' for v in value) if jsonl else audit.canonical(value)+b'\n')


def row(key=KEY, cls=11, frame=None):
    return dict(target_key=key, final_class_id=cls, frame_id=frame or 'frame-'+key, split='train', box_index=0,
        bbox=dict(x=20, y=30, width=60, height=20), size=[100, 80], image=f'images/{key}.png',
        appearance_status='ok', group_id='group-'+key, policy_id='synthetic', source_pcd_sha256='b'*64)


def empty_store():
    return dict(current={}, histories={})


@pytest.fixture
def staged(tmp_path):
    root, formal = tmp_path/'pack', tmp_path/'formal'
    source = row()
    yy, xx = np.mgrid[:80, :100]
    image = ((xx//3+yy//4) % 2*160+40).astype(np.uint8)

    class Evidence:
        def image(self, frame):
            assert frame == source['frame_id']
            return image

    evidence = Evidence()
    for path in (formal/source['image'], root/'internal/images'/f'{KEY}.png', root/'images'/f'{KEY}.png'):
        path.parent.mkdir(parents=True, exist_ok=True)
        Image.fromarray(image).save(path)
    bounds = audit.crop_bounds(source)
    left, top, right, bottom = bounds
    crop = Image.fromarray(image).convert('RGB').crop((left, top, right, bottom))
    ImageDraw.Draw(crop).rectangle((20-left, 30-top, 80-left, 50-top), outline=(255, 180, 40), width=1)
    path = root/'internal/cases'/f'{KEY}.png'; path.parent.mkdir(); crop.save(path)
    record = dict(target_key=KEY, class_id=11, source=source, request_order=1, native_image=f'images/{KEY}.png',
        contact_crop=f'cases/{KEY}.png', crop_native_bounds=bounds, image_quality=audit.native_quality(source, evidence),
        no_pose_current_or_history=True, existing_pose_revision=0, existing_pose_payload_sha256=None,
        existing_pose_current_payload=None, existing_pose_history_sha256=audit.sha([]))
    decision = dict(approved=True, full_image_inspected=True, crop_inspected=True, note_zh='仅为合成测试轮廓，不是人工或GT。', polygon=POLYGON)
    return dict(root=root, formal=formal, row=source, evidence=evidence, record=record, decision=decision)


def check_stage(fixture, staged=None, decisions=None, forbidden=None, pose=None, rows=None):
    f = fixture
    return audit.check_staged(f['root'], staged if staged is not None else [f['record']],
        decisions if decisions is not None else {KEY: f['decision']}, rows or {KEY: f['row']},
        f['formal'], f['evidence'], pose or empty_store(), forbidden or set())


def draft(fixture):
    f = fixture; record, decision = f['record'], f['decision']; source = record['source']
    proof = dict(method='assistant_direct_native_image_contour_not_template_transfer', author_role='AI_assistant',
        crop_inspected=True, full_image_inspected=True, note_zh=decision['note_zh'],
        image_sha256=audit.digest(f['formal']/source['image']), polygon_sha256=audit.sha(decision['polygon']),
        human_saved=False, counts_toward_coverage_before_real_human_save=False, input_manifest_sha256='f'*64)
    reference = dict(origin='assistant_visual_preannotation', target_key=KEY, snapshot_revision=record['existing_pose_revision'],
        current_payload_sha256=record['existing_pose_payload_sha256'])
    value = record['existing_pose_current_payload']
    if value:
        reference['pose_review'] = dict(target_key=KEY, revision=value['revision'], payload_sha256=audit.sha(value), polygon_sha256=audit.sha(value['polygon']))
    proposal = dict(schema='assistant_visual_preannotation_v1', origin='assistant_visual_preannotation', target_key=KEY,
        class_id=11, source=source, polygon=decision['polygon'], vertex_count=len(decision['polygon']),
        status='assistant_preannotated_draft_pending_human_review', formal_manifest_sha256='e'*64,
        preannotation=proof, draft_source=reference, target_expected_revision=record['existing_pose_revision'],
        target_snapshot_payload_sha256=record['existing_pose_payload_sha256'],
        mask_semantics='assistant_direct_visible_fork_face_contour_draft_not_GT', **dict.fromkeys(audit.FALSE_FLAGS, False))
    task = dict(target_key=KEY, class_id=11, source=source, status='preannotated_awaiting_human_review',
        assistant_polygon=decision['polygon'], preannotation=proof, existing_pose_revision=record['existing_pose_revision'],
        existing_pose_payload_sha256=record['existing_pose_payload_sha256'], existing_pose_record=value is not None,
        native_image=record['native_image'], contact_crop=record['contact_crop'], image_quality=record['image_quality'],
        valid_four_point_manual_contour_allowed=True, extra_vertices_must_not_be_forced=True,
        preserve_existing_pose_until_intentional_human_edit=True, counts_as_completed_annotation=False)
    return copy.deepcopy(proposal), copy.deepcopy(task)


def check_draft(fixture, proposal, task):
    audit.check_draft(proposal, task, fixture['record'], fixture['decision'], 'e'*64, 'f'*64,
        audit.digest(fixture['formal']/fixture['row']['image']))


def test_independent_verifier_never_imports_any_builder_or_calls_real_saves():
    tree = ast.parse(Path(audit.__file__).read_text())
    for node in ast.walk(tree):
        if isinstance(node, ast.ImportFrom):
            assert not any('build_mask' in name for name in [node.module or '', *(a.name for a in node.names)])
        if isinstance(node, ast.Import):
            assert not any('build_mask' in a.name for a in node.names)
        if isinstance(node, ast.Call) and isinstance(node.func, ast.Attribute):
            assert node.func.attr not in ('save_review', 'save_annotation', 'backup')


def test_staged_native_bytes_quality_and_full_crop_decision_are_verified(staged):
    before = audit.inventory(staged['root'])
    records, hashes = check_stage(staged)
    assert set(records) == {KEY} and len(hashes) == 1
    assert audit.inventory(staged['root']) == before


@pytest.mark.parametrize('field,value', [('crop_inspected', False), ('full_image_inspected', False), ('note_zh', ''), ('approved', 1)])
def test_withheld_sources_still_need_real_explicit_full_crop_decisions(staged, field, value):
    staged['decision']['approved'] = False
    staged['decision'][field] = value
    with pytest.raises(ValueError):
        check_stage(staged)


def test_proposal_must_not_escape_own_staged_decisions(staged):
    with pytest.raises(ValueError, match='exactly one decision'):
        check_stage(staged, decisions={})
    with pytest.raises(ValueError, match='exactly one decision'):
        check_stage(staged, decisions={KEY: staged['decision'], 'b'*24: staged['decision']})


@pytest.mark.parametrize('attack', ['bytes', 'bounds', 'crop', 'quality', 'formal_identity'])
def test_staged_image_crop_quality_or_identity_mutations_fail(staged, attack):
    if attack == 'bytes':
        (staged['root']/'internal/images'/f'{KEY}.png').write_bytes(b'changed bytes')
    elif attack == 'bounds':
        staged['record']['crop_native_bounds'][0] += 1
    elif attack == 'crop':
        Image.new('RGB', (2, 2)).save(staged['root']/'internal/cases'/f'{KEY}.png')
    elif attack == 'quality':
        staged['record']['image_quality']['clarity_score'] += .1
    else:
        staged['record']['source'] = dict(staged['row'], split='test')
    with pytest.raises(ValueError):
        check_stage(staged)


@pytest.mark.parametrize('attack', ['key', 'frame', 'bytes'])
def test_global_protected_key_frame_and_identical_image_bytes_all_block_staging(staged, attack):
    old = row('b'*24)
    if attack == 'frame':
        old['frame_id'] = staged['row']['frame_id']
    original = staged['formal']/staged['row']['image']
    path = staged['formal']/old['image']; path.parent.mkdir(exist_ok=True)
    path.write_bytes(original.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'):
        check_stage(staged, rows=rows, forbidden=forbidden)


def test_duplicate_own_staged_keys_are_rejected(staged):
    with pytest.raises(ValueError, match='Duplicate'):
        check_stage(staged, staged=[staged['record'], staged['record']])


def test_staging_a_fourth_image_for_one_class_is_rejected_before_image_io(staged):
    records = [dict(staged['record'], target_key=f'{n:024x}') for n in range(4)]
    with pytest.raises(ValueError, match='maximum3'):
        check_stage(staged, staged=records, decisions={r['target_key']: staged['decision'] for r in records})


def test_history_scans_exclude_only_exact_own_root_and_include_rejected_shortlists(tmp_path):
    own = tmp_path/'outputs/pallet_mask_under50_requests_v1'
    other = tmp_path/'outputs/another_pack'
    rejected = 'b'*24
    write(own/'internal/shortlist.jsonl', [dict(target_key=KEY)], True)
    write(own/'requests.jsonl', [dict(target_key=KEY)], True)
    write(other/'internal/shortlist.jsonl', [dict(target_key=rejected, rejected=True)], True)
    write(other/'requests.jsonl', [], True)
    write(tmp_path/'outputs/unrelated_training/metrics.json', dict(step=1))
    hashes, keys = audit.prior_inspections(tmp_path, own, {KEY: row(), rejected: row(rejected)})
    assert keys == {rejected} and len(hashes) == 2
    assert all('another_pack' in name for name in hashes)
    write(tmp_path/'outputs/unrelated_training/metrics.json', dict(step=2))
    assert audit.prior_inspections(tmp_path, own, {KEY: row(), rejected: row(rejected)})[0] == hashes
    roots = audit.old_evidence_roots(tmp_path, own, other, tmp_path/'outputs/quality', hashes)
    assert own not in roots and tmp_path/'outputs/unrelated_training' not in roots
    assert tmp_path/'outputs' not in roots and other in roots


def test_unknown_historical_target_fails_closed_instead_of_hiding_it(tmp_path):
    write(tmp_path/'outputs/old/shortlist.jsonl', [dict(target_key='unknown')], True)
    with pytest.raises(ValueError, match='Unknown previous'):
        audit.prior_inspections(tmp_path, tmp_path/'outputs/own', {})


@pytest.mark.parametrize('mutation', ['modified_then_box', 'deleted', 'deferred', 'confirmed', 'pose_confirmed', 'history_only'])
def test_pose_current_and_entire_history_are_protected_not_just_latest_box(mutation):
    source = row(); box = [[20, 30], [80, 30], [80, 50], [20, 50]]
    old = dict(target_key=KEY, revision=1, polygon=copy.deepcopy(box), state='draft')
    if mutation == 'modified_then_box':
        old['polygon'] = POLYGON
    elif mutation == 'pose_confirmed':
        old['pose'] = dict(human_pose_confirmed=True)
    elif mutation != 'history_only':
        old['state'] = mutation
    current = dict(target_key=KEY, revision=2, polygon=box, state='draft')
    pose = dict(current={} if mutation == 'history_only' else {KEY: (2, json.dumps(current), current)},
        histories={KEY: [(1, 1, json.dumps(old), old)]})
    assert KEY in audit.protected_keys({KEY: source}, pose, empty_store(), [], [], set(), set())


def test_old_canonical_gallery_quarantine_and_prior_withheld_sources_all_protected():
    keys = [f'{n:024x}' for n in range(5)]
    rows = {key: row(key) for key in keys}
    gallery = dict(current={keys[0]: None}, histories={keys[1]: []})
    protected = audit.protected_keys(rows, empty_store(), gallery, [], [dict(target_key=keys[2])], {keys[3]}, {keys[4]})
    assert protected == set(keys)


def test_all_existing_pose_fields_and_history_sha_are_exact_not_polygon_only(staged):
    value = dict(target_key=KEY, revision=4, polygon=[[20, 30], [80, 30], [80, 50], [20, 50]],
        pose=dict(selected_faces=['left'], sensor={'scale': .001}), ruler={'length': 18}, other_private='keep')
    record = staged['record']
    record.update(no_pose_current_or_history=False, existing_pose_revision=4,
        existing_pose_payload_sha256=audit.sha(value), existing_pose_current_payload=copy.deepcopy(value),
        existing_pose_history_sha256=audit.sha([value]))
    pose = dict(current={KEY: (4, json.dumps(value), value)}, histories={KEY: [(1, 4, json.dumps(value), value)]})
    check_stage(staged, pose=pose)
    record['existing_pose_current_payload']['ruler']['length'] = 19
    with pytest.raises(ValueError, match='all_preserved_pose_fields'):
        check_stage(staged, pose=pose)


def test_closed_four_point_contour_is_allowed_but_never_old_seed_or_accuracy_claim(staged):
    proposal, task = draft(staged)
    check_draft(staged, proposal, task)
    assert proposal['vertex_count'] == 4 and proposal['propagation_seed_eligible'] is False
    assert task['extra_vertices_must_not_be_forced'] and not task['counts_as_completed_annotation']


@pytest.mark.parametrize('field', audit.FALSE_FLAGS)
def test_each_false_human_gt_training_or_seed_claim_is_rejected(staged, field):
    proposal, task = draft(staged); proposal[field] = True
    with pytest.raises(ValueError):
        check_draft(staged, proposal, task)


@pytest.mark.parametrize('field,value', [('template', {}), ('metrics', {'iou': 1}), ('metrics', {}), ('human_confirmed', True)])
def test_even_empty_template_or_fabricated_metrics_are_not_permitted(staged, field, value):
    proposal, task = draft(staged); proposal[field] = value
    with pytest.raises(ValueError):
        check_draft(staged, proposal, task)


@pytest.mark.parametrize('attack', ['revision', 'sha', 'forced_vertices', 'polygon', 'proof', 'foreign_source', 'approved'])
def test_task_preconditions_and_proof_cannot_be_laundered(staged, attack):
    proposal, task = draft(staged)
    if attack == 'revision':
        proposal['target_expected_revision'] = 1
    elif attack == 'sha':
        proposal['target_snapshot_payload_sha256'] = 'a'*64
    elif attack == 'forced_vertices':
        task['extra_vertices_must_not_be_forced'] = False
    elif attack == 'polygon':
        task['assistant_polygon'][0][0] += 1
    elif attack == 'proof':
        proposal['preannotation']['human_saved'] = True
    elif attack == 'foreign_source':
        proposal['source']['class_id'] = 20
    else:
        staged['decision']['approved'] = False
    with pytest.raises(ValueError):
        check_draft(staged, proposal, task)


def test_original_box_cannot_be_relabelled_as_explicit_native_contour(staged):
    staged['decision']['polygon'] = [[20, 30], [80, 30], [80, 50], [20, 50]]
    proposal, task = draft(staged)
    with pytest.raises(ValueError, match='Original rectangle'):
        check_draft(staged, proposal, task)


def export(f):
    root = f['root']; proposal, task = draft(f)
    for folder in ('masks', 'labelme', 'cases'):
        (root/folder).mkdir(exist_ok=True)
    Image.fromarray(audit.sources.raster(proposal['polygon'], f['row']['size']).astype(np.uint8)*255).save(root/'masks'/f'{KEY}.png')
    write(root/'labelme'/f'{KEY}.json', dict(version='5.0.0', imagePath=f'../images/{KEY}.png', imageData=None,
        imageWidth=100, imageHeight=80, flags=dict(assistant_preannotation=True, human_confirmed=False, ground_truth_eligible=False),
        annotation_scope='single_target_not_full_frame', shapes=[dict(label='pallet', shape_type='polygon', points=POLYGON,
            group_id=0, flags=dict(human_confirmed=False))]))
    with Image.open(root/'images'/f'{KEY}.png') as image:
        image = image.convert('RGB')
    draw = ImageDraw.Draw(image); draw.line([tuple(p) for p in POLYGON]+[tuple(POLYGON[0])], fill='#55d5ff', width=1)
    for i, point in enumerate(POLYGON, 1):
        draw.text(tuple(point), str(i), fill='#ffce33')
    left, top, right, bottom = f['record']['crop_native_bounds']
    image.crop((left, top, right, bottom)).resize(((right-left)*3, (bottom-top)*3), Image.Resampling.NEAREST).save(root/'cases'/f'{KEY}.png')
    return proposal


def test_raster_labelme_and_native_coordinate_preview_replay_is_read_only(staged):
    proposal = export(staged); before = audit.inventory(staged['root'])
    audit.check_exports(staged['root'], proposal, staged['record'], audit.digest(staged['formal']/staged['row']['image']))
    assert audit.inventory(staged['root']) == before


@pytest.mark.parametrize('attack', ['raster', 'second_shape', 'image_path', 'human_flag', 'preview', 'image_bytes'])
def test_export_tampering_or_full_frame_labelme_fails(staged, attack):
    proposal = export(staged); root = staged['root']; path = root/'labelme'/f'{KEY}.json'
    if attack == 'raster':
        image = np.asarray(Image.open(root/'masks'/f'{KEY}.png')).copy(); image[0, 0] = 255
        Image.fromarray(image).save(root/'masks'/f'{KEY}.png')
    elif attack in ('second_shape', 'image_path', 'human_flag'):
        value = audit.read(path)
        if attack == 'second_shape':
            value['shapes'].append(copy.deepcopy(value['shapes'][0]))
        elif attack == 'image_path':
            value['imagePath'] = '../../private.png'
        else:
            value['flags']['human_confirmed'] = True
        write(path, value)
    elif attack == 'preview':
        Image.new('RGB', (3, 3)).save(root/'cases'/f'{KEY}.png')
    else:
        with (root/'images'/f'{KEY}.png').open('ab') as stream:
            stream.write(b'not byte identical')
    with pytest.raises(ValueError):
        audit.check_exports(root, proposal, staged['record'], audit.digest(staged['formal']/staged['row']['image']))


def count_fixture():
    counts = {c: n for c, n in audit.EXPECTED_COUNTS.items()}
    other = [c for c in range(1, 23) if c not in counts]
    counts.update({c: 80 for c in other[:-1]}); counts[other[-1]] = 1484-sum(counts.values())
    catalog = []; n = 0
    for cls, count in counts.items():
        for _ in range(count):
            n += 1; catalog.append(dict(target_key=f'{n:024x}', row=row(f'{n:024x}', cls)))
    inputs = dict(actual_class_counts={str(c): v for c, v in counts.items()}, actual_counted_saved_basis=1484,
        shortlisted_classes=list(audit.CLASSES), maximum_issued_per_class=2, target_per_class_this_pilot=50, class_scope=audit.CLASS_SCOPE)
    manifest = dict(actual_human_saved_counts_before=copy.deepcopy(inputs['actual_class_counts']), filter_classes=list(audit.CLASSES),
        maximum_issued_per_class=2, target_per_class_this_pilot=50, class_scope=audit.CLASS_SCOPE)
    return catalog, inputs, manifest


def test_actual_all22_class_counts_are_1484_distinct_sources_not_1550_machine_coverage():
    catalog, inputs, manifest = count_fixture()
    counts = audit.check_count_basis(catalog, inputs, manifest)
    assert sum(counts.values()) == 1484 and {c: counts[c] for c in audit.CLASSES} == audit.EXPECTED_COUNTS


@pytest.mark.parametrize('attack', ['1550', 'missing_class', 'class50', 'duplicate_frame', 'duplicate_key', 'class_max3', 'target100', 'filter', 'bool_count'])
def test_wrong_manual_denominator_scope_or_class_counts_are_rejected(attack):
    catalog, inputs, manifest = count_fixture()
    if attack == '1550':
        inputs['actual_counted_saved_basis'] = 1550
    elif attack == 'missing_class':
        del inputs['actual_class_counts']['1']
    elif attack == 'class50':
        inputs['actual_class_counts']['12'] = 50
    elif attack == 'duplicate_frame':
        catalog[1]['row']['frame_id'] = catalog[0]['row']['frame_id']
    elif attack == 'duplicate_key':
        catalog[1]['target_key'] = catalog[0]['target_key']
    elif attack == 'class_max3':
        manifest['maximum_issued_per_class'] = 3
    elif attack == 'target100':
        inputs['target_per_class_this_pilot'] = 100
    elif attack == 'bool_count':
        inputs['actual_class_counts']['11'] = True
    else:
        manifest['filter_classes'].append(22)
    with pytest.raises(ValueError):
        audit.check_count_basis(catalog, inputs, manifest)


def issued_fixture(per_class=2):
    staged, proposals, decisions = [], [], {}
    for cls in audit.CLASSES:
        for n in range(3):
            key = f'{cls:022x}{n:02x}'
            staged.append(dict(target_key=key, class_id=cls))
            decisions[key] = dict(approved=n < per_class)
            if n < per_class:
                proposals.append(dict(target_key=key, class_id=cls))
    manifest = dict(request_count=len(proposals), classes=list(audit.CLASSES),
        class_counts={str(c): per_class for c in audit.CLASSES})
    return proposals, copy.deepcopy(proposals), staged, decisions, manifest, audit.EXPECTED_COUNTS.copy()


def test_exact_small_pilot_can_issue12_and_protect_all6_withheld_own_staged_images():
    args = issued_fixture()
    counts, withheld = audit.check_issued_inventory(*args)
    assert sum(counts.values()) == 12 and len(withheld) == 6
    assert all(n == 2 for n in counts.values())
    assert all(v['decision']['approved'] is False for v in withheld)


@pytest.mark.parametrize('attack', ['3_per_class', 'over_50', 'foreign_key', 'withheld_issued', 'approved_missing',
    'order', 'unpaired', 'duplicate', 'count_bool', 'wrong_class_counts'])
def test_issue_caps_gap_pairing_and_own_staged_membership_all_fail_closed(attack):
    args = list(issued_fixture(per_class=1)); proposals, tasks, staged, decisions, manifest, counts = args
    if attack == '3_per_class':
        args = list(issued_fixture(per_class=3))
    elif attack == 'over_50':
        counts[11] = 50
    elif attack == 'foreign_key':
        proposals[0]['target_key'] = tasks[0]['target_key'] = 'f'*24
    elif attack == 'withheld_issued':
        decisions[proposals[0]['target_key']]['approved'] = False
    elif attack == 'approved_missing':
        decisions[staged[1]['target_key']]['approved'] = True
    elif attack == 'order':
        tasks.reverse()
    elif attack == 'unpaired':
        tasks.pop()
    elif attack == 'duplicate':
        proposals[1] = proposals[0]
    elif attack == 'count_bool':
        manifest['request_count'] = True
    else:
        manifest['class_counts']['11'] += 1
    with pytest.raises(ValueError):
        audit.check_issued_inventory(*args)


@pytest.fixture
def public_pack(staged, tmp_path, monkeypatch):
    import fontTools.ttLib
    proposal = export(staged); root = staged['root']
    project = tmp_path/'synthetic_project'; monkeypatch.setattr(audit, 'PROJECT', project)
    license_path = project/'pallet/assets/pose_review/FONT_LICENSE.txt'
    license_path.parent.mkdir(parents=True); license_path.write_text('Synthetic license fixture')
    (root/'FONT_LICENSE.txt').write_bytes(license_path.read_bytes())
    (root/'report-font.otf').write_bytes(b'synthetic font; cmap mocked for isolated glyph coverage test')
    page = ('少于50 · 真实人工轮廓 · 每类最多2张 · 第15版 · 已预标注 · 保存前不计覆盖 · '
        '不自动确认GT、训练或机器人资格 · 有效四点保持四点 · 不为传播模板强行增点\n'
        + '、'.join(f'Class {c}：{audit.EXPECTED_COUNTS[c]}份' for c in audit.CLASSES)
        + '<select id="request-filter"><option value="">全部</option>'
        + ''.join(f'<option value="{c}">{c}</option>' for c in audit.CLASSES) + '</select>'
        + f'<article id="target-{KEY}" data-class="11"><img src="cases/{KEY}.png">'
        + f'<a href="images/{KEY}.png">原图</a><a href="masks/{KEY}.png">掩膜</a>'
        + f'<a href="labelme/{KEY}.json">LabelMe</a></article>')
    (root/'report_zh.html').write_text(page)
    glyphs = {ord(c) for c in page}
    class Font:
        def __init__(self, path):
            assert path == root/'report-font.otf'
        def __enter__(self):
            return self
        def __exit__(self, *args):
            return False
        def getBestCmap(self):
            return {value: str(value) for value in glyphs}
    monkeypatch.setattr(fontTools.ttLib, 'TTFont', Font)
    manifest = dict(public_assets={name: audit.digest(root/name) for name in
        ('report_zh.html', 'report-font.otf', 'FONT_LICENSE.txt', *(f'{folder}/{KEY}.{ext}' for folder, ext in
        (('images', 'png'), ('cases', 'png'), ('masks', 'png'), ('labelme', 'json'))))})
    return root, manifest, [proposal], glyphs


def test_public_scope_class_filter_manual_counts_allowlist_and_chinese_glyphs(public_pack):
    root, manifest, proposals, _ = public_pack
    assert audit.check_public(root, manifest, proposals) == set(manifest['public_assets'])


@pytest.mark.parametrize('attack', ['third_batch', 'class22', 'wrong_manual_count', 'unsafe_link', 'private_payload',
    'missing_not_gt', 'font_missing_glyph', 'changed_asset'])
def test_report_semantics_assets_and_chinese_glyph_coverage_are_fail_closed(public_pack, attack):
    root, manifest, proposals, glyphs = public_pack; path = root/'report_zh.html'
    page = path.read_text()
    if attack == 'third_batch':
        page += '第三批'
    elif attack == 'class22':
        page = page.replace('</select>', '<option value="22">22</option></select>')
    elif attack == 'wrong_manual_count':
        page = page.replace('Class 11：17份', 'Class 11：50份')
    elif attack == 'unsafe_link':
        page += '<img src="internal/shortlist.jsonl">'
    elif attack == 'private_payload':
        page += 'current_payload_raw'
    elif attack == 'missing_not_gt':
        page = page.replace('不自动确认GT、训练或机器人资格', '')
    elif attack == 'font_missing_glyph':
        glyphs.remove(ord('少'))
    else:
        (root/'FONT_LICENSE.txt').write_bytes(b'changed')
    path.write_text(page); manifest['public_assets']['report_zh.html'] = audit.digest(path)
    with pytest.raises(ValueError):
        audit.check_public(root, manifest, proposals)


def sqlite_store(path, current_raw, event_raw):
    with sqlite3.connect(path) 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);'
            'CREATE TABLE metadata(key TEXT,value TEXT);')
        db.execute('INSERT INTO annotations VALUES (?,?,?)', (KEY, 1, current_raw))
        db.execute('INSERT INTO events VALUES (?,?,?,?)', (1, KEY, 1, event_raw))
        db.execute('INSERT INTO metadata VALUES (?,?)', ('binding', '{"synthetic":true}'))


def test_raw_utf8_event_hashes_are_not_canonicalized_before_hashing(tmp_path):
    value = dict(target_key=KEY, revision=1, note='人工轮廓', polygon=POLYGON)
    raw = json.dumps(value, ensure_ascii=False, indent=2)
    reformatted = json.dumps(value, ensure_ascii=False, separators=(',', ':'))
    path = tmp_path/'isolated.sqlite3'; sqlite_store(path, raw, raw)
    before = path.read_bytes(); fp = audit.database_fingerprint(path)
    assert audit.sources.raw_sha(raw) != audit.sources.raw_sha(reformatted)
    audit.sources.exact_latest(audit.sources.read_store(path, 'pose', True), KEY)
    assert path.read_bytes() == before
    with sqlite3.connect(path) as db:
        db.execute('UPDATE events SET payload=?', (reformatted,))
    assert audit.database_fingerprint(path) != fp
    with pytest.raises(ValueError, match='raw latest'):
        audit.sources.exact_latest(audit.sources.read_store(path, 'pose', True), KEY)


@pytest.mark.parametrize('raw', ['{"a":1,"a":2}', '{"a":NaN}', '{"a":Infinity}'])
def test_json_duplicate_keys_and_nonfinite_values_cannot_launder_claims(raw):
    with pytest.raises(ValueError):
        audit.sources.loads(raw)


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


def test_no_ready_notification_means_no_audit_reads_or_seals(seal_root):
    (seal_root/'manifest.json').unlink()
    def forbidden(_):
        pytest.fail('unfinished staging audited')
    with pytest.raises(ValueError, match='completion notification'):
        audit.seal(seal_root, auditor=forbidden)
    assert not list(seal_root.iterdir())


def test_seals_are_two_identical_exclusive_files_only_after_actual_auditor_success(seal_root):
    passed = dict(state='passed', request_count=1, semantic_contour_accuracy_established=False)
    def successful(root):
        assert not any((root/name).exists() for name in audit.SEALS)
        return passed
    assert audit.seal(seal_root, producer_complete=True, auditor=successful) == passed
    assert (seal_root/audit.SEALS[0]).read_bytes() == (seal_root/audit.SEALS[1]).read_bytes() == audit.canonical(passed)+b'\n'
    assert (seal_root/audit.SEALS[0]).stat().st_mode & 0o777 == 0o600
    with pytest.raises(ValueError, match='Never overwrite'):
        audit.seal(seal_root, producer_complete=True, auditor=successful)


@pytest.mark.parametrize('state', ['failed', 'pending'])
def test_nonpassing_audit_never_creates_any_verification_file(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_exception_never_writes_failed_or_passed_seals(seal_root):
    def failed(_):
        raise RuntimeError('synthetic source changed')
    with pytest.raises(RuntimeError):
        audit.seal(seal_root, producer_complete=True, auditor=failed)
    assert set(audit.inventory(seal_root)) == {'manifest.json'}


def test_existing_second_seal_is_never_overwritten_or_partially_published(seal_root):
    path = seal_root/'independent_verification.json'; path.write_bytes(b'user work')
    with pytest.raises(ValueError, match='Never overwrite'):
        audit.seal(seal_root, producer_complete=True, auditor=lambda _: dict(state='passed'))
    assert path.read_bytes() == b'user work' and not (seal_root/'verification.json').exists()


def test_seal_race_removes_only_own_first_file_and_keeps_other_writers_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_escaped_symlink_and_public_private_allowlist_are_rejected(tmp_path, staged):
    outside = tmp_path/'secret'; outside.write_bytes(b'secret')
    (staged['root']/'leak').symlink_to(outside)
    with pytest.raises(ValueError, match='Symlink'):
        audit.inventory(staged['root'])
    with pytest.raises(ValueError, match='Unsafe'):
        audit.member(staged['root'], '../secret')
    with pytest.raises(ValueError, match='allowlist'):
        audit.check_public(staged['root'], dict(public_assets={'internal/shortlist.jsonl': '0'*64}), [])
