"""Adversarial independent audits: no source/queue generator is trusted."""
import ast
from collections import Counter
import copy
import hashlib
import itertools
import json
import sqlite3

import numpy as np
from PIL import Image
import pytest

from scripts import verify_mask_remaining_classes as audit


FOUR = [[20, 20], [85, 21], [83, 43], [19, 42]]
FINE = [[20, 20], [85, 20], [85, 44], [65, 44], [65, 35], [40, 35], [40, 44], [20, 44]]


def row(key='human', cls=3, frame=None):
    return dict(target_key=key, target_id=key+'::box:0000', frame_id=frame or 'frame-'+key,
        final_class_id=cls, split='train', group_id='group', box_index=0,
        bbox=dict(x=18, y=18, width=70, height=28), size=[120, 80], policy_id='camera',
        source_pcd_sha256='pcd', image='images/'+key+'.png', viewpoint_candidate='front',
        appearance_status='ok')


def value(r, polygon=FOUR, revision=1, **extra):
    return dict(target_key=r['target_key'], revision=revision, source=copy.deepcopy(r),
        state='draft', polygon=copy.deepcopy(polygon), **extra)


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


def event(v, event_id=None):
    return (event_id or v['revision'], v['target_key'], v['revision'], json.dumps(v, indent=2))


def write_json(path, v):
    path.parent.mkdir(parents=True, exist_ok=True)
    path.write_bytes(audit.canonical(v)+b'\n')


def write_jsonl(path, values):
    path.parent.mkdir(parents=True, exist_ok=True)
    path.write_bytes(b''.join(audit.canonical(v)+b'\n' for v in values))


@pytest.fixture(params=[FOUR, FINE], ids=['four-point', 'fine'])
def human(request):
    r = row()
    v = value(r, request.param)
    pose = store({'human': v}, [event(v)])
    recovered = audit.recover_pose_sources(pose, {'human': r})
    p = dict(target_key='human', class_id=3, source=r, polygon=copy.deepcopy(request.param),
        vertex_count=len(request.param), manual_four_point_source=len(request.param) == 4,
        propagation_seed_eligible=len(request.param) > 4, human_edited=True)
    return r, pose, recovered, p


def test_exact17_classes_never_inherit_old_five():
    assert audit.CLASSES == (3, 4, 5, 6, 7, 8, 11, 12, 13, 14, 16, 17, 18, 19, 20, 21, 22)
    assert not set(audit.CLASSES) & {1, 2, 9, 10, 15}
    assert len(audit.CLASSES) == 17


def test_direct_human_recovery_is_readonly_and_preserves_actual_vertices(human):
    r, pose, recovered, p = human
    before = copy.deepcopy((pose, recovered, p))
    counts = audit.check_saved_sources({'human': p}, recovered, {'human': r}, set())
    assert counts['3']['saved_human'] == 1 and counts['3']['missing'] == 99
    assert counts['3']['seeds'] == (len(p['polygon']) > 4)
    assert counts['3']['four_point_manual'] == (len(p['polygon']) == 4)
    assert (pose, recovered, p) == before


@pytest.mark.parametrize('kind', ['unit_normalization', 'axes_normalization'])
def test_normalization_can_follow_human_but_never_invents_new_human_edit(human, kind):
    r, pose, recovered, _ = human
    current = dict(pose['current']['human'], revision=2, event_kind=kind)
    pose['current']['human'] = current
    pose['events'].append(event(current))
    source = audit.recover_pose_sources(pose, {'human': r})['human']
    assert source['human_polygon_revision'] == 1 and source['current_revision'] == 2
    assert source['human_event_sha256'] == recovered['human']['human_event_sha256']
    pose['events'] = [event(current)]
    assert not audit.recover_pose_sources(pose, {'human': r})


@pytest.mark.parametrize('attack', ['machine', 'machine_then_normalization', 'deleted', 'deferred', 'confirmed',
    'human_mask_confirmed', 'human_pose_confirmed', 'metric_pose_confirmed', 'ground_truth_eligible',
    'automatic_training_eligible', 'robot_command_eligible', 'rectangle', 'stale_polygon', 'too_few', 'invalid'])
def test_protected_or_machine_current_is_never_human_evidence(human, attack):
    r, pose, _, _ = human
    original = pose['current']['human']
    current = copy.deepcopy(original)
    if attack in ('machine', 'machine_then_normalization'):
        current.update(revision=2, event_kind='mask_template_proposal')
        pose['events'].append(event(current))
        if attack == 'machine_then_normalization':
            current = dict(current, revision=3, event_kind='axes_normalization')
            pose['events'].append(event(current))
    elif attack in ('deleted', 'deferred', 'confirmed'):
        current['state'] = attack
    elif attack in audit.FALSE_FLAGS:
        current[attack] = True
    elif attack == 'rectangle':
        current['polygon'] = audit.rectangle(r)
    elif attack == 'stale_polygon':
        current['polygon'][0][0] += .5
    elif attack == 'too_few':
        current['polygon'] = [[20, 20], [80, 20], [40, 35]]
    else:
        current['polygon'] = [[20, 20]]*5
        pose['events'] = [event(current)]
    pose['current']['human'] = current
    assert not audit.recover_pose_sources(pose, {'human': r})


@pytest.mark.parametrize('state', ['deleted', 'deferred', 'confirmed'])
def test_special_history_stays_protected_after_later_draft(human, state):
    r, pose, _, _ = human
    special = dict(pose['current']['human'], state=state, revision=2)
    current = dict(pose['current']['human'], revision=3)
    pose['events'] += [event(special), event(current)]
    pose['current']['human'] = current
    assert not audit.recover_pose_sources(pose, {'human': r})


@pytest.mark.parametrize('where', ['event', 'current'])
def test_source_identity_mismatch_is_an_error_not_silently_a_different_class(human, where):
    r, pose, _, _ = human
    changed = copy.deepcopy(pose['current']['human'])
    changed['source']['split'] = 'test'
    if where == 'event':
        pose['events'] = [event(changed)]
    else:
        pose['current']['human'] = changed
    with pytest.raises(ValueError, match='source identity'):
        audit.recover_pose_sources(pose, {'human': r})


def test_quarantine_never_counts_even_if_real_human(human):
    r, pose, _, _ = human
    assert not audit.recover_pose_sources(pose, {'human': r}, {'human'})


@pytest.mark.parametrize('attack', ['synthesized_vertex', 'seed', 'vertex_count', 'old_class', 'source_split',
    'nonhuman', 'confirmed', 'event_hash', 'stale_revision', 'machine_transfer', 'write', 'extra_template'])
def test_saved_sources_cannot_launder_provenance_topology_or_writes(human, attack):
    r, _, recovered, p = human
    if attack == 'synthesized_vertex':
        p['polygon'] += [[25, 30]]
    elif attack == 'seed':
        p['propagation_seed_eligible'] = not p['propagation_seed_eligible']
    elif attack == 'vertex_count':
        p['vertex_count'] += 1
    elif attack == 'old_class':
        p['class_id'] = 1
    elif attack == 'source_split':
        p['source'] = dict(r, split='test')
    elif attack == 'nonhuman':
        p['human_edited'] = False
    elif attack == 'confirmed':
        p['ground_truth_eligible'] = True
    elif attack == 'event_hash':
        p['human_source'] = dict(human_polygon_revision=1, human_event_sha256='fake')
    elif attack == 'stale_revision':
        p['target_expected_revision'] = 0
    elif attack == 'machine_transfer':
        p['machine_transfer_performed'] = True
    elif attack == 'write':
        p['pose_store_written'] = True
    else:
        p['template'] = dict(human_polygon_revision=1, human_event_sha256='fake')
    with pytest.raises(ValueError):
        audit.check_saved_sources({'human': p}, recovered, {'human': r}, set())


def test_baseline_reuse_and_omitted_available_humans_fail(human):
    r, _, recovered, p = human
    with pytest.raises(ValueError, match='omits'):
        audit.check_saved_sources({}, recovered, {'human': r}, set())
    with pytest.raises(ValueError):
        audit.check_saved_sources({'human': p}, recovered, {'human': r}, {r['frame_id']})


def test_multiple_boxes_one_frame_do_not_inflate_coverage(human):
    r, _, recovered, p = human
    other = row('other', 4, frame=r['frame_id'])
    recovered['other'] = dict(recovered['human'], row=other)
    other_p = dict(p, target_key='other', source=other, class_id=4)
    with pytest.raises(ValueError):
        audit.check_saved_sources({'human': p, 'other': other_p}, recovered, {'human': r, 'other': other}, set())
    assert sum(v['saved_human'] for v in audit.check_saved_sources({'human': p}, recovered,
        {'human': r, 'other': other}, set()).values()) == 1


def test_inventory_class19_107_boxes_are_only96_images_and_class17_near_cap():
    rows = {}
    for cls, frames, boxes in ((19, 96, 107), (17, 105, 105)):
        for i in range(boxes):
            key = f'{cls}-{i}'
            rows[key] = row(key, cls, frame=f'{cls}-frame-{i % frames}')
    result = audit.formal_inventory(rows)
    assert result['19']['boxes'] == 107 and result['19']['distinct_frames'] == 96
    assert result['19']['population_shortfall'] == result['19']['capacity_shortfall'] == 4
    assert result['17']['distinct_frames'] == 105 and result['17']['globally_unique_capacity'] == 100


def test_b_matching_recovers_capacity_a_greedy_cross_class_choice_would_lose():
    rows = {k: row(k, c, f) for k, c, f in (
        ('a', 3, 'shared'), ('b', 3, 'only3'), ('c', 4, 'shared'), ('d', 4, 'only4'),
        ('e', 5, 'only4'))}
    assigned = audit.maximum_assignment(rows, cap=1)
    assert len(assigned) == 3 and {v['final_class_id'] for v in assigned.values()} == {3, 4, 5}
    assert len({v['frame_id'] for v in assigned.values()}) == len(assigned)


def test_b_matching_matches_bruteforce_all_small_graphs():
    edges = list(itertools.product((3, 4, 5), ('a', 'b', 'c')))
    for bits in range(1 << len(edges)):
        rows = {f'{c}{f}': row(f'{c}{f}', c, f) for i, (c, f) in enumerate(edges) if bits & (1 << i)}
        best = 0
        values = list(rows.values())
        for chosen in itertools.product((False, True), repeat=len(values)):
            subset = [r for r, select in zip(values, chosen) if select]
            if len({r['frame_id'] for r in subset}) == len(subset) and all(
                    n <= 1 for n in Counter(r['final_class_id'] for r in subset).values()):
                best = max(best, len(subset))
        assert len(audit.maximum_assignment(rows, cap=1)) == best


def test_cross_class_and_baseline_conflicts_reduce_capacity_honestly():
    rows = {'a': row('a', 19, 'shared'), 'b': row('b', 17, 'shared'),
        'c': row('c', 17, 'baseline')}
    result = audit.formal_inventory(rows, {'baseline'})
    assert sum(v['globally_unique_capacity'] for v in result.values()) == 1
    assert result['17']['baseline_disjoint_frames'] == 1
    assert result['19']['distinct_frames'] == 1


def test_protection_is_frame_global_and_retains_returned_rectangles():
    rows = {k: row(k, 3 if i % 2 else 4, frame='f'+str(i//2)) for i, k in enumerate(('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'))}
    edited = value(rows['a'], FINE)
    rectangle = value(rows['a'], audit.rectangle(rows['a']), revision=2)
    deferred = value(rows['c'], audit.rectangle(rows['c']))
    deferred['state'] = 'deferred'
    pose = store({'a': rectangle, 'c': deferred}, [event(edited), event(rectangle), event(deferred, 3)])
    gallery = store({}, [(1, 'e', 1, '{}')])
    keys, frames, history = audit.protection(rows, pose, gallery, {'g': {}}, {})
    assert keys == {'a', 'c', 'e', 'g'} and frames == {'f0', 'f1', 'f2', 'f3'}
    assert len(history['a']) == 2


@pytest.fixture
def raw_source(tmp_path, human):
    r, pose, recovered, p = human
    snapshot = tmp_path/'snapshot.sqlite3'
    v = pose['current']['human']
    raw = json.dumps(v, indent=1)
    with sqlite3.connect(snapshot) as db:
        db.executescript('CREATE TABLE annotations(target_key TEXT,revision INTEGER,payload TEXT);'
            'CREATE TABLE events(id INTEGER,target_key TEXT,revision INTEGER,payload TEXT);')
        db.execute('INSERT INTO annotations VALUES (?,?,?)', ('human', 1, raw))
        db.execute('INSERT INTO events VALUES (?,?,?,?)', event(v))
    source = recovered['human']
    record = dict(target_key='human', snapshot_sha256=audit.digest(snapshot), current_revision=1,
        current_payload_raw=raw, current_payload=v, current_payload_sha256=audit.sha(v),
        current_payload_raw_sha256=hashlib.sha256(raw.encode()).hexdigest(),
        human_event_id=source['human_event_id'], human_polygon_revision=source['human_polygon_revision'],
        human_event_payload_raw=source['human_event_payload_raw'], human_event_payload=source['human_event_payload'],
        human_event_sha256=source['human_event_sha256'], polygon_sha256=audit.sha(v['polygon']))
    return {'human': record}, {'human': p}, recovered, snapshot


def test_raw_sqlite_bytes_are_compared_read_only(raw_source):
    before = raw_source[-1].read_bytes()
    audit.check_source_records(*raw_source)
    assert raw_source[-1].read_bytes() == before


@pytest.mark.parametrize('field', ['snapshot_sha256', 'current_revision', 'current_payload_raw',
    'current_payload_raw_sha256', 'human_event_id', 'human_polygon_revision', 'human_event_payload_raw',
    'human_event_sha256', 'polygon_sha256'])
def test_raw_source_tampering_including_whitespace_cannot_pass(raw_source, field):
    record = raw_source[0]['human']
    record[field] = record[field]+1 if isinstance(record[field], int) else record[field]+' '
    with pytest.raises(ValueError, match='binding differs'):
        audit.check_source_records(*raw_source)


def test_logical_fingerprint_preserves_raw_whitespace_and_schema(tmp_path):
    db_path = tmp_path/'db.sqlite3'
    with sqlite3.connect(db_path) as db:
        db.execute('CREATE TABLE payloads(raw TEXT)')
        db.execute('INSERT INTO payloads VALUES (?)', ('{"x": 1}',))
    original = db_path.read_bytes()
    before = audit.logical_fingerprint(db_path)
    assert db_path.read_bytes() == original
    with sqlite3.connect(db_path) as db:
        db.execute('UPDATE payloads SET raw=?', ('{"x":1}',))
    assert audit.logical_fingerprint(db_path) != before
    with sqlite3.connect(db_path) as db:
        db.execute('ALTER TABLE payloads ADD COLUMN other TEXT')
    assert audit.logical_fingerprint(db_path)['schema_sha256'] != before['schema_sha256']


@pytest.fixture
def request_case(tmp_path):
    from scripts.build_mask_template_requests import render_case
    r = row('a'*24)
    image = np.tile(np.arange(120, dtype=np.uint8)*2, (80, 1))
    image[:, ::3] = 0
    formal, output = tmp_path/'formal', tmp_path/'output'
    for root in (formal, output):
        (root/'images').mkdir(parents=True)
    Image.fromarray(image).save(formal/r['image'])
    Image.fromarray(image).save(output/r['image'])
    sources = {r['frame_id']: dict(image=r['image'], size=r['size'], files={r['image']: audit.digest(formal/r['image'])})}
    evidence = audit.ImageEvidence(formal, {r['target_key']: r}, sources)
    (output/'cases').mkdir()
    bounds = render_case(r, evidence, output/'cases'/f'{r["target_key"]}.png')
    quality, reason = audit.native_quality(r, evidence)
    assert reason is None
    req = dict(target_key=r['target_key'], class_id=3, request_order=1,
        source=dict(r, image_sha256=audit.digest(formal/r['image'])), original_rectangle=audit.rectangle(r),
        source_label_kind='ORIGINAL_RECTANGLE', status='needs_manual_tracing', minimum_manual_template_vertices=5,
        valid_four_point_manual_contour_allowed=True, extra_vertices_must_not_be_forced=True,
        topology_must_be_manually_determined=True, existing_pose_record=False, pose_history_present=False,
        existing_pose_revision=0, existing_pose_payload_sha256=None, image_quality=quality,
        native_image=f'images/{r["target_key"]}.png', contact_crop=f'cases/{r["target_key"]}.png', crop_native_bounds=bounds,
        pose_annotation_url='https://pose.example/?target='+r['target_key'])
    return req, r, store({}), {}, set(), evidence, output, 'https://pose.example', {}


def test_request_only_contains_source_rect_not_completed_polygon(request_case):
    audit.check_request(*request_case)


@pytest.mark.parametrize('attack', ['old_class', 'protected_frame', 'class', 'split', 'view', 'rect',
    'polygon', 'completed', 'seed_minimum', 'force_vertices', 'four_disallowed', 'quality', 'native_bytes',
    'crop_pixels', 'crop_bounds', 'url_target', 'url_authority', 'confirmation', 'training', 'robot',
    'saved', 'pose_revision', 'reference'])
def test_request_tampering_cannot_bypass_source_quality_or_honesty(request_case, attack):
    req, r, pose, history, protected, _, output, _, recovered = request_case
    if attack == 'old_class':
        req['class_id'] = r['final_class_id'] = 1
    elif attack == 'protected_frame':
        protected.add(r['frame_id'])
    elif attack == 'class':
        req['class_id'] = 4
    elif attack == 'split':
        req['source']['split'] = 'test'
    elif attack == 'view':
        req['source']['viewpoint_candidate'] = 'top'
    elif attack == 'rect':
        req['original_rectangle'][0][0] += 1
    elif attack == 'polygon':
        req['polygon'] = FINE
    elif attack == 'completed':
        req['counts_as_completed_annotation'] = True
    elif attack == 'seed_minimum':
        req['minimum_manual_template_vertices'] = 4
    elif attack == 'force_vertices':
        req['extra_vertices_must_not_be_forced'] = False
    elif attack == 'four_disallowed':
        req['valid_four_point_manual_contour_allowed'] = False
    elif attack == 'quality':
        req['image_quality']['clarity_score'] += .01
    elif attack == 'native_bytes':
        (output/req['native_image']).write_bytes(b'changed')
    elif attack == 'crop_pixels':
        Image.new('RGB', (96, 72), 'black').save(output/req['contact_crop'])
    elif attack == 'crop_bounds':
        req['crop_native_bounds'][0] += 1
    elif attack in ('url_target', 'url_authority'):
        req['pose_annotation_url'] = ('https://pose.example/?target=other' if attack == 'url_target'
            else 'https://other.example/?target='+r['target_key'])
    elif attack in ('confirmation', 'training', 'robot', 'saved'):
        req[dict(confirmation='human_mask_confirmed', training='automatic_training_eligible',
            robot='robot_command_eligible', saved='production_saved')[attack]] = True
    elif attack == 'pose_revision':
        req['existing_pose_revision'] = 10
    else:
        req['closest_human_reference_key'] = 'unsaved-machine'
    with pytest.raises(ValueError):
        audit.check_request(*request_case)


def test_native_quality_boundary_is_not_relaxed(request_case):
    req, r, *_ = request_case
    r['bbox']['height'] = 13.99
    req['source']['bbox'] = copy.deepcopy(r['bbox'])
    req['original_rectangle'] = audit.rectangle(r)
    with pytest.raises(ValueError, match='native-quality'):
        audit.check_request(*request_case)


@pytest.fixture
def existing_pose(request_case):
    req, r, pose, history, *_ = request_case
    old = value(r, audit.rectangle(r), revision=9, pose={'x': 1}, ruler={'w': .4},
        sensor={'scale_to_m': .001}, selected_faces=[0, 1], exclusions=[5])
    pose['current'][r['target_key']] = old
    history[r['target_key']] = [event(old)]
    req.update(existing_pose_record=True, pose_history_present=True, existing_pose_revision=9,
        existing_pose_payload_sha256=audit.sha(old), existing_pose_current_payload=old,
        existing_pose_geometry_sha256=audit.sha({f: old.get(f) for f in audit.GEOMETRY}),
        preserve_existing_pose_until_intentional_human_edit=True,
        preserve_current_selected_ruler_sensor_faces_and_revision=True,
        existing_pose_revision_is_expected_not_overwrite_authorization=True)
    return request_case


def test_saved_ruler_and_pose_remain_eligible_only_with_full_explicit_protection(existing_pose):
    before = copy.deepcopy(existing_pose[:5])
    audit.check_request(*existing_pose)
    assert before == existing_pose[:5]


@pytest.mark.parametrize('attack', ['geometry', 'payload', 'revision', 'preserve', 'faces', 'overwrite',
    'history_edited_then_rect', 'history_deferred_then_rect'])
def test_existing_pose_request_never_silently_overwrites_or_reuses_mask_history(existing_pose, attack):
    req, r, _, history, *_ = existing_pose
    if attack == 'geometry':
        req['existing_pose_geometry_sha256'] = 'fake'
    elif attack == 'payload':
        req['existing_pose_current_payload'] = {}
    elif attack == 'revision':
        req['existing_pose_revision'] = 8
    elif attack in ('preserve', 'faces', 'overwrite'):
        req[dict(preserve='preserve_existing_pose_until_intentional_human_edit',
            faces='preserve_current_selected_ruler_sensor_faces_and_revision',
            overwrite='existing_pose_revision_is_expected_not_overwrite_authorization')[attack]] = False
    else:
        old = value(r, FINE if attack == 'history_edited_then_rect' else audit.rectangle(r))
        if attack == 'history_deferred_then_rect':
            old['state'] = 'deferred'
        history[r['target_key']].insert(0, event(old))
    with pytest.raises(ValueError):
        audit.check_request(*existing_pose)


@pytest.mark.parametrize('field', ['split', 'policy_id', 'viewpoint_candidate', 'final_class_id', 'frame_id'])
def test_references_cannot_cross_exact_signature_or_reuse_same_frame(request_case, field):
    req, r, *_, recovered = request_case
    reference = row('ref')
    if field == 'frame_id':
        reference[field] = r[field]
    elif field == 'final_class_id':
        reference[field] = 4
    else:
        reference[field] = 'other'
    req['closest_human_reference_key'] = 'ref'
    recovered['ref'] = dict(row=reference, polygon=FINE)
    with pytest.raises(ValueError, match='crosses'):
        audit.check_request(*request_case)


def test_seed_inventory_rejects_a_four_point_saved_source(tmp_path, human):
    _, _, recovered, p = human
    write_json(tmp_path/'template_inventory.json', dict(templates=[dict(row=p['source'], polygon=p['polygon'])]))
    if len(p['polygon']) == 4:
        with pytest.raises(ValueError, match='four-point'):
            audit.check_seed_inventory(tmp_path, recovered)
    else:
        audit.check_seed_inventory(tmp_path, recovered)


@pytest.fixture
def public_page(tmp_path, monkeypatch):
    import fontTools.ttLib
    key = 'a'*24
    request = dict(native_image=f'images/{key}.png', contact_crop=f'cases/{key}.png', existing_pose_record=False)
    page = f'<article id="{key}">待描绘，未激活。四点可以保存，不强加点数。<img src="images/{key}.png"><img src="cases/{key}.png"></article>'
    (tmp_path/'report_zh.html').write_text(page)
    for name in ('report-font.otf', 'FONT_LICENSE.txt', request['native_image'], request['contact_crop']):
        path = tmp_path/name
        path.parent.mkdir(parents=True, exist_ok=True)
        path.write_bytes(b'public bytes')
    class FakeFont:
        def __enter__(self):
            return self
        def __exit__(self, *_):
            pass
        def getBestCmap(self):
            return dict.fromkeys(range(0x3400, 0xa000))
    monkeypatch.setattr(fontTools.ttLib, 'TTFont', lambda _: FakeFont())
    manifest = dict(public_assets=audit.file_inventory(tmp_path))
    return tmp_path, manifest, {key: request}


def test_public_assets_are_only_three_plus_two_per_request(public_page):
    assert len(audit.check_public(*public_page)) == 5


@pytest.mark.parametrize('attack', ['database', 'raw_events', 'payload', 'credential', 'image', 'duplicate',
    'hidden', 'hash', 'symlink', 'missing_image', 'missing_four_policy', 'private_inventory'])
def test_public_allowlist_and_html_cannot_expose_private_evidence_or_hide_tasks(public_page, attack):
    root, manifest, requests = public_page
    page = (root/'report_zh.html').read_text()
    if attack in ('database', 'private_inventory'):
        name = 'reviews_snapshot.sqlite3' if attack == 'database' else 'manual_source_records.jsonl'
        (root/name).write_bytes(b'private')
        manifest['public_assets'][name] = audit.digest(root/name)
    elif attack in ('raw_events', 'payload', 'credential'):
        page += dict(raw_events='human_event_payload_raw', payload='existing_pose_current_payload', credential='password')[attack]
    elif attack == 'image':
        page += '<img src="internal/history.png">'
    elif attack == 'duplicate':
        page += '<article id="'+next(iter(requests))+'"></article>'
    elif attack == 'hidden':
        page = page.replace('<article ', '<article hidden ')
    elif attack == 'hash':
        manifest['public_assets']['FONT_LICENSE.txt'] = 'fake'
    elif attack == 'symlink':
        (root/'FONT_LICENSE.txt').unlink()
        (root/'FONT_LICENSE.txt').symlink_to(root/'report-font.otf')
    elif attack == 'missing_image':
        page = page.replace('<img src="cases/'+next(iter(requests))+'.png">', '')
    else:
        page = page.replace('四点', '很多点')
    (root/'report_zh.html').write_text(page)
    manifest['public_assets']['report_zh.html'] = audit.digest(root/'report_zh.html')
    with pytest.raises(ValueError):
        audit.check_public(root, manifest, requests)


@pytest.mark.parametrize('attack', [None, 'crop', 'full', 'approved', 'note', 'binding'])
def test_visual_review_requires_per_target_crop_and_full_source_decisions(tmp_path, attack):
    decision = dict(approved=True, crop_inspected=True, full_image_inspected=True, note_zh='原生边界清晰')
    if attack in ('crop', 'full', 'approved'):
        decision[dict(crop='crop_inspected', full='full_image_inspected', approved='approved')[attack]] = False
    elif attack == 'note':
        decision['note_zh'] = ''
    path = tmp_path/'internal/source_visual_decisions.json'
    write_json(path, {'key': decision})
    manifest = dict(source_visual_decisions_sha256='fake' if attack == 'binding' else audit.digest(path))
    requests = {'key': dict(source_visual_review_zh='原生边界清晰')}
    if attack:
        with pytest.raises(ValueError):
            audit.visual_decisions(tmp_path, requests, manifest)
    else:
        audit.visual_decisions(tmp_path, requests, manifest)


def honest_manifest():
    return dict(production_database_writes=0, configuration_writes=0, service_writes=0,
        generated_polygons=0, ground_truth_eligible=False, automatic_training_eligible=False,
        human_confirmation_inferred=False)


@pytest.mark.parametrize('field', ['production_database_writes', 'configuration_writes', 'service_writes',
    'generated_polygons', 'ground_truth_eligible', 'automatic_training_eligible', 'robot_command_eligible',
    'human_confirmation_inferred', 'activated', 'all_classes_complete', 'thresholds_relaxed', 'forced_fill',
    'machine_transfer_performed'])
def test_manifest_cannot_claim_writes_activation_fill_or_gt(field):
    manifest = honest_manifest()
    audit.check_claims(manifest)
    manifest[field] = 1 if field.endswith('writes') or field == 'generated_polygons' else True
    with pytest.raises(ValueError):
        audit.check_claims(manifest)


def source_schema_manifest():
    return dict(production_database_writes=0, configuration_writes=0, service_writes=0,
        new_machine_proposals=0, machine_transfer_performed=False, new_human_edits_created=0,
        automatic_human_confirmation=False, classification_is_candidate_not_truth=True,
        automatic_training_eligible=False, ground_truth_eligible=False,
        manual_proposals=141, actual_human_labels_reused=141)


def test_actual_source_schema_aliases_mean_no_new_contours_not_no_inherited_humans():
    manifest = source_schema_manifest()
    before = copy.deepcopy(manifest)
    audit.check_claims(manifest)
    assert manifest == before and manifest['actual_human_labels_reused'] == 141
    assert 'generated_polygons' not in manifest and 'human_confirmation_inferred' not in manifest


@pytest.mark.parametrize('field,value', [('new_machine_proposals', 1), ('new_machine_proposals', False),
    ('new_machine_proposals', '0'), ('new_human_edits_created', 1), ('machine_transfer_performed', True),
    ('automatic_human_confirmation', True), ('classification_is_candidate_not_truth', False),
    ('generated_polygons', 1), ('human_confirmation_inferred', True), ('duplicate_fill', True)])
def test_source_aliases_never_override_malicious_or_conflicting_claims(field, value):
    manifest = source_schema_manifest()
    manifest[field] = value
    with pytest.raises(ValueError):
        audit.check_claims(manifest)


@pytest.mark.parametrize('field', ['new_machine_proposals', 'machine_transfer_performed',
    'new_human_edits_created', 'automatic_human_confirmation', 'classification_is_candidate_not_truth'])
def test_source_schema_aliases_require_the_entire_equivalent_safety_claim(field):
    manifest = source_schema_manifest()
    del manifest[field]
    with pytest.raises(ValueError):
        audit.check_claims(manifest)


@pytest.mark.parametrize('field', ['automatic_human_confirmation', 'machine_transfer_performed'])
def test_direct_request_claim_does_not_hide_a_conflicting_legacy_alias(field):
    manifest = honest_manifest()
    manifest[field] = True
    with pytest.raises(ValueError):
        audit.check_claims(manifest)


def test_population_capacity_and_protected_capacity_are_separate_not_weakened_thresholds():
    rows = {str(i): row(str(i), 19, frame='frame'+str(i)) for i in range(96)}
    baseline = {'frame'+str(i) for i in range(4)}
    protected = {'frame4', 'frame5'}
    formal = audit.formal_inventory(rows, baseline)['19']
    eligible = {k: r for k, r in rows.items() if r['frame_id'] not in baseline | protected}
    capacity = audit.maximum_assignment(eligible)
    assert formal['distinct_frames'] == 96 and formal['globally_unique_capacity'] == 92
    assert len(capacity) == 90
    assert 100-len(capacity) == 10  # Neither 92 nor 90 claims completed labels.


@pytest.mark.parametrize('reverse,rotate', [(False, 1), (False, 2), (True, 0), (True, 2)])
def test_reordered_original_rectangles_are_not_human_sources(reverse, rotate):
    r = row()
    corners = audit.rectangle(r)
    if reverse:
        corners.reverse()
    corners = corners[rotate:]+corners[:rotate]
    v = value(r, corners)
    assert not audit.recover_pose_sources(store({'human': v}, [event(v)]), {'human': r})


@pytest.mark.parametrize('attack', ['machine_draft', 'machine_generated', 'machine_transfer_performed',
    'automatic_generated', 'human_edited_false', 'other_origin', 'unchanged_machine_then_human'])
def test_human_source_proof_rejects_machine_flags_and_unchanged_machine_save(human, attack):
    r, pose, _, _ = human
    v = copy.deepcopy(pose['current']['human'])
    if attack == 'human_edited_false':
        v['human_edited'] = False
    elif attack == 'other_origin':
        v['origin'] = 'machine'
    elif attack == 'unchanged_machine_then_human':
        machine = dict(v, event_kind='mask_template_proposal')
        v['revision'] = 2
        pose['events'] = [event(machine), event(v)]
    else:
        v[attack] = True
    if attack != 'unchanged_machine_then_human':
        pose['events'] = [event(v)]
    pose['current']['human'] = v
    assert not audit.recover_pose_sources(pose, {'human': r})


def test_changed_human_edit_after_machine_can_count_but_is_bound_to_latest_edit(human):
    r, pose, _, _ = human
    machine = dict(pose['current']['human'], event_kind='mask_template_proposal')
    current = copy.deepcopy(pose['current']['human'])
    current['revision'] = 2
    current['polygon'][0][0] += 1
    pose['events'] = [event(machine), event(current)]
    pose['current']['human'] = current
    recovered = audit.recover_pose_sources(pose, {'human': r})
    assert recovered['human']['human_polygon_revision'] == 2


def test_artifact_inventory_must_cover_all_files_and_hashes(tmp_path):
    write_json(tmp_path/'manifest.json', {})
    hashes = audit.file_inventory(tmp_path)
    write_json(tmp_path/'artifact_hashes.json', hashes)
    audit.check_declared_hashes(tmp_path, {})
    (tmp_path/'unexpected.txt').write_text('unbound')
    with pytest.raises(ValueError, match='cover every'):
        audit.check_declared_hashes(tmp_path, {})


def test_configuration_freeze_is_required_and_compared(tmp_path, monkeypatch):
    project, root = tmp_path/'project', tmp_path/'output'
    (project/'configs').mkdir(parents=True)
    root.mkdir()
    (project/'configs/active.json').write_text('original')
    monkeypatch.setattr(audit, 'PROJECT', project)
    with pytest.raises(ValueError, match='configuration freeze'):
        audit.check_configuration(root, {})
    expected = audit.file_inventory(project/'configs')
    assert audit.check_configuration(root, dict(configuration_sha256=expected)) == expected
    (project/'configs/active.json').write_text('changed')
    with pytest.raises(ValueError, match='configuration changed'):
        audit.check_configuration(root, dict(configuration_sha256=expected))


def test_no_generator_imports_and_no_assert_statements():
    tree = ast.parse(audit.Path(audit.__file__).read_text())
    forbidden = {'pallet.mask_remaining_classes', 'scripts.build_mask_remaining_requests'}
    for node in ast.walk(tree):
        assert not isinstance(node, ast.Assert)
        if isinstance(node, ast.ImportFrom):
            assert node.module not in forbidden
        elif isinstance(node, ast.Import):
            assert not forbidden & {n.name for n in node.names}


@pytest.fixture
def seal_output(tmp_path, monkeypatch):
    project = tmp_path/'project'
    output = project/'outputs/pallet_mask_remaining_classes_v1'
    output.mkdir(parents=True)
    write_json(output/'manifest.json', {})
    monkeypatch.setattr(audit, 'PROJECT', project)
    return output


def test_failed_audit_writes_report_but_no_success_seal(seal_output):
    def fail(_):
        raise ValueError('invalid raw source')
    with pytest.raises(ValueError, match='invalid raw source'):
        audit.seal(seal_output, 'sources', fail)
    assert not (seal_output/audit.SEAL).exists()
    assert audit.read_json(seal_output/audit.REPORT)['state'] == 'failed'


def test_success_seal_is_exclusive_and_hash_binds_report(seal_output):
    audit.seal(seal_output, 'sources', lambda _: dict(state='passed'))
    sealed = (seal_output/audit.SEAL).read_bytes()
    assert audit.read_json(seal_output/audit.SEAL)['validation_report_sha256'] == audit.digest(seal_output/audit.REPORT)
    with pytest.raises(ValueError, match='overwrite'):
        audit.seal(seal_output, 'sources', lambda _: dict(state='passed'))
    assert (seal_output/audit.SEAL).read_bytes() == sealed


def test_output_symlink_cannot_write_parent_or_baseline(seal_output):
    link = seal_output.parent/'pallet_mask_remaining_classes_v2'
    link.symlink_to(seal_output, target_is_directory=True)
    with pytest.raises(ValueError, match='Only the new'):
        audit.seal(link, 'sources', lambda _: dict(state='passed'))
    assert not (seal_output/audit.REPORT).exists()


def test_report_symlink_is_never_written_even_on_failure(seal_output):
    protected = seal_output.parent/'historical.json'
    protected.write_text('immutable')
    (seal_output/audit.REPORT).symlink_to(protected)
    with pytest.raises(ValueError, match='Unsafe'):
        audit.seal(seal_output, 'sources', lambda _: dict(state='passed'))
    assert protected.read_text() == 'immutable'


def test_dual_cli_dispatch_is_independent_and_source_only_or_requests_only_work(monkeypatch, tmp_path):
    calls = []
    monkeypatch.setattr(audit, 'audit_sources', lambda root: dict(state='passed', root=str(root)))
    monkeypatch.setattr(audit, 'audit_requests', lambda root, sources: dict(state='passed', source=str(sources)))
    def fake_seal(root, kind, operation):
        calls.append((root, kind))
        return operation(root)
    monkeypatch.setattr(audit, 'seal', fake_seal)
    sources, requests = tmp_path/'sources', tmp_path/'requests'
    result = audit.main(['--sources', str(sources), '--requests', str(requests)])
    assert set(result) == {'sources', 'requests'} and result['requests']['source'] == str(sources.resolve())
    assert [kind for _, kind in calls] == ['sources', 'requests']
    assert set(audit.main(['--sources', str(sources)])) == {'sources'}
    assert set(audit.main(['--requests', str(requests), '--source-output', str(sources)])) == {'requests'}
    with pytest.raises(ValueError, match='Specify'):
        audit.main([])
