"""New direct tasks only; no real generation, live database, or outputs are used."""
import copy
import json
from pathlib import Path
import sqlite3

import numpy as np
from PIL import Image
import pytest

from scripts import build_mask_remaining_direct_requests as requests
from scripts.build_mask_template_requests import native_quality


def row(key, cls=4, frame=None, **extra):
    return dict(target_key=key, target_id='target-'+key, frame_id=frame or 'frame-'+key,
        final_class_id=cls, final_class=f'class-{cls}', split='train', group_id='group-'+key,
        box_index=0, policy_id='sensor', viewpoint_candidate='front', source_pcd_sha256='pcd',
        bbox=dict(x=4, y=4, width=60, height=20), size=[100, 40], image=key+'.png',
        appearance_status='ok', **extra)


def pose(r, revision=1, **extra):
    return dict(target_key=r['target_key'], source=r, revision=revision, state='draft',
        polygon=requests.rectangle(r), pose={'x': 1}, ruler={'length': 2}, sensor={'id': 3},
        selected_faces=['front'], exclusions=['back'], **extra)


def usable(virgin=True, human=0, area=2000, clarity=.8):
    return dict(no_pose_current_or_history=virgin, existing_exact_signature_human_sources=human,
        existing_class_group_human_sources=0,
        quality=dict(clarity_score=clarity, bbox_area_native_pixels=area))


def quotas(**values):
    return {c: values.get(str(c), 0) for c in requests.CLASSES}


def test_scope_is_only_five_direct_coverage_classes_not_class19():
    assert requests.CLASSES == (4, 5, 7, 14, 22)
    assert requests.PARENT.name == 'pallet_mask_remaining_expand_v1'
    assert requests.DEFAULT.name == 'pallet_mask_remaining_direct_requests_v1'
    assert not hasattr(requests, 'attempt_target')
    assert not hasattr(requests, 'snapshot_database')


def test_quotas_come_from_actual_cumulative_distinct_frames_not_assumed_fifty():
    values = []
    for cls, n in {4: 96, 5: 100, 7: 12, 14: 99, 22: 93, 19: 90}.items():
        values += [dict(target_key=f'{cls}-{i}', class_id=cls,
            source=dict(frame_id=f'{cls}-{i}')) for i in range(n)]
    assert requests.class_quotas(values) == {4: 4, 5: 0, 7: 10, 14: 1, 22: 7}
    assert sum(requests.class_quotas(values).values()) == 22
    assert requests.class_quotas(values, 3) == {4: 3, 5: 0, 7: 3, 14: 1, 22: 3}


@pytest.mark.parametrize('attack', ['frame', 'key', 'over_quota', 'class', 'limit'])
def test_bad_cumulative_identity_or_quota_is_not_used(attack):
    values = [dict(target_key='a', class_id=4, source=dict(frame_id='frame-a')),
        dict(target_key='b', class_id=5, source=dict(frame_id='frame-b'))]
    limit = 10
    if attack == 'frame':
        values[1]['source']['frame_id'] = 'frame-a'
    elif attack == 'key':
        values[1]['target_key'] = 'a'
    elif attack == 'over_quota':
        values = [dict(target_key=str(i), class_id=4, source=dict(frame_id=str(i))) for i in range(101)]
    elif attack == 'class':
        values[0]['class_id'] = 23
    else:
        limit = 11
    with pytest.raises(ValueError):
        requests.class_quotas(values, limit)


@pytest.mark.parametrize('kind', ['edited_restored', 'deleted', 'deferred', 'confirmed',
    'human_mask_confirmed', 'metric_pose_confirmed', 'human_confirmed', 'ground_truth_eligible',
    'automatic_training_eligible', 'robot_command_eligible', 'machine_draft', 'null_polygon'])
def test_any_edited_or_special_history_protects_key_and_global_frame_after_restore(kind):
    rows = {'a': row('a'), 'same-frame-other-class': row('same-frame-other-class', 5, frame='frame-a')}
    old = pose(rows['a'])
    if kind == 'edited_restored':
        old['polygon'][0][0] += .5
    elif kind in ('deleted', 'deferred', 'confirmed'):
        old['state'] = kind
    elif kind == 'null_polygon':
        old['polygon'] = None
    else:
        old[kind] = True
    current = {'a': pose(rows['a'], 2)}
    protected, frames, history = requests.protection(rows, current,
        [(1, 'a', 1, json.dumps(old))], (), [], [])
    assert protected == {'a'} and frames == {'frame-a'}
    assert rows['same-frame-other-class']['frame_id'] in frames
    assert history['a'][0]['original_pose_only'] is False


def test_original_rectangle_pose_only_history_is_allowed_but_not_virgin():
    r = row('a', 14); value = pose(r)
    value['polygon'] = value['polygon'][2:]+value['polygon'][:2]
    protected, frames, history = requests.protection({'a': r}, {'a': value},
        [(1, 'a', 1, json.dumps(value))], (), [], [])
    assert not protected and not frames
    assert history['a'][0]['original_rectangle'] is True
    assert history['a'][0]['payload_raw_sha256'] == requests.raw_sha(json.dumps(value))
    assert requests.protection({'a': r}, {}, [(1, 'a', 1, json.dumps(value))], (), [], [])[0] == {'a'}


def test_all_old_requests_gallery_current_events_quarantine_and_cumulative_frames_protected():
    names = ['parent-machine', 'old86', 'latest51', 'gallery-current', 'gallery-event', 'quarantine']
    rows = {k: row(k) for k in names}
    protected, frames, _ = requests.protection(rows, {}, [], names[3:5],
        [dict(target_key=names[0])], [dict(target_key=k) for k in names[1:3]], [names[-1]])
    assert protected == set(names)
    assert frames == {r['frame_id'] for r in rows.values()}


def test_unknown_protected_history_cannot_silently_lose_frame_identity():
    with pytest.raises(ValueError, match='Unknown protected'):
        requests.protection({}, {}, [], ['missing'], [], [])


def test_request_discovery_covers_all_new_historical_queues_but_not_this_output(tmp_path, monkeypatch):
    monkeypatch.setattr(requests, 'PROJECT', tmp_path)
    out = tmp_path/'outputs/pallet_mask_remaining_direct_requests_v1'
    out.mkdir(parents=True); (out/'requests.jsonl').write_text('private current output')
    before = requests.old_request_paths(out)
    extra = tmp_path/'outputs/pallet_mask_another_historical_queue_v1'
    extra.mkdir(); (extra/'requests.jsonl').write_text('historical input')
    assert extra/'requests.jsonl' in requests.old_request_paths(out)-before
    assert out/'requests.jsonl' not in requests.old_request_paths(out)
    assert len([p for p in before if p.parent.name in requests.OLD_REQUEST_DIRS]) == 6


def test_selection_prefers_virgin_known_view_and_exact_configuration_human_shortage():
    rows = {k: row(k) for k in ('virgin-known', 'virgin-unknown', 'old-pose', 'covered')}
    rows['virgin-unknown']['viewpoint_candidate'] = 'unknown'
    pool = {k: usable() for k in rows}
    pool['old-pose'] = usable(False, area=10000, clarity=1)
    pool['covered']['existing_exact_signature_human_sources'] = 20
    assert requests.select_tasks(rows, pool, quotas(**{'4': 1})) == ['virgin-known']


def test_selection_uses_known_split_sensor_view_group_variety_without_reference_wildcards():
    rows = {k: row(k) for k in ('a', 'b', 'c')}
    rows['b']['group_id'] = rows['a']['group_id']
    rows['c'].update(split='test', policy_id='other-sensor', viewpoint_candidate='back')
    pool = {k: usable() for k in rows}
    assert requests.select_tasks(rows, pool, quotas(**{'4': 2})) == ['a', 'c']
    assert requests.signature(rows['a']) != requests.signature(rows['c'])


def test_larger_clearer_sources_win_only_after_protection_and_variety_priorities():
    rows = {k: row(k) for k in ('a-small', 'b-large')}
    pool = {'a-small': usable(area=1000, clarity=.3), 'b-large': usable(area=5000, clarity=.95)}
    assert requests.select_tasks(rows, pool, quotas(**{'4': 1})) == ['b-large']


def test_class14_can_use_only_original_rectangle_history_and_never_repeat_a_frame():
    rows = {'scarce14': row('scarce14', 14, 'shared'), 'shared4': row('shared4', 4, 'shared'),
        'fresh4': row('fresh4', 4, 'different')}
    pool = {k: usable(k != 'scarce14') for k in rows}
    selected = requests.select_tasks(rows, pool, quotas(**{'4': 10, '14': 1}))
    assert set(selected) == {'scarce14', 'fresh4'}
    assert len({rows[k]['frame_id'] for k in selected}) == len(selected)


def test_original_native_quality_function_and_all_thresholds_are_frozen():
    assert requests.native_quality is native_quality
    assert requests.QUALITY_GATES == dict(min_width=50, min_height=14, min_area=1000, min_image_margin=1,
        min_p95_p05=35, min_brightness_fraction_above_48=.12,
        max_saturated_fraction_above_250=.65, min_sobel_magnitude_above_60_fraction=.025)


@pytest.mark.parametrize('box,reason', [
    (dict(x=2, y=2, width=49, height=30), 'bbox_too_small_for_manual_tracing'),
    (dict(x=2, y=2, width=80, height=13), 'bbox_too_small_for_manual_tracing'),
    (dict(x=2, y=2, width=50, height=14), 'bbox_too_small_for_manual_tracing'),
    (dict(x=0, y=2, width=60, height=20), 'incomplete_or_edge_touching_bbox'),
])
def test_no_dimension_or_margin_relaxation(box, reason):
    r = row('a'); r['bbox'] = box
    assert requests.native_quality(r, None) == (None, reason)


def test_complete_database_fingerprint_changes_on_raw_event_bytes_metadata_and_schema(tmp_path):
    path = tmp_path/'private.sqlite3'
    with sqlite3.connect(path) as db:
        db.executescript('CREATE TABLE events(id INTEGER, payload TEXT); CREATE TABLE metadata(key TEXT,value TEXT);')
        db.execute('INSERT INTO events VALUES (1,?)', ('{"x":1}',))
    first = requests.database_fingerprint(path)
    with sqlite3.connect(path) as db:
        db.execute('UPDATE events SET payload=?', ('{ "x": 1 }',))
    second = requests.database_fingerprint(path)
    assert first['table_counts'] == second['table_counts'] and first != second
    with sqlite3.connect(path) as db:
        db.execute('INSERT INTO metadata VALUES ("binding","changed")')
    third = requests.database_fingerprint(path)
    assert second != third
    with sqlite3.connect(path) as db:
        db.execute('CREATE TABLE extra(value TEXT)')
    assert requests.database_fingerprint(path)['schema_sha256'] != third['schema_sha256']


def test_review_does_not_require_parent_seal_but_build_does_and_self_check_is_not_seal(tmp_path):
    (tmp_path/'proposals.jsonl').write_text('{}\n')
    (tmp_path/'manifest.json').write_text('{}')
    (tmp_path/'generation_validation.json').write_text('{"state":"passed"}')
    manifest = dict(proposals=1)
    assert requests.parent_seal(tmp_path, manifest, False) == {}
    with pytest.raises(ValueError, match='Build requires'):
        requests.parent_seal(tmp_path, manifest, True)
    seal = dict(state='passed', publication_version=10, proposals_verified=1,
        manifest_sha256=requests.digest(tmp_path/'manifest.json'),
        proposals_sha256=requests.digest(tmp_path/'proposals.jsonl'))
    (tmp_path/'verification.json').write_text(json.dumps(seal))
    assert set(requests.parent_seal(tmp_path, manifest, True)) == {'verification.json'}
    (tmp_path/'proposals.jsonl').write_text('{"changed":true}\n')
    with pytest.raises(ValueError, match='matching passed'):
        requests.parent_seal(tmp_path, manifest, True)


def test_only_new_external_parent_audit_files_may_arrive_between_review_and_build():
    frozen = dict(parent_generation_inventory={'manifest.json': 'm'},
        parent_existing_audit_hashes={}, database_logical_fingerprints={'pose': 'p', 'gallery': 'g'})
    later = copy.deepcopy(frozen)
    later['parent_existing_audit_hashes']['verification.json'] = 'external-seal'
    requests.assert_frozen(frozen, later)
    for field in ('parent_generation_inventory', 'database_logical_fingerprints'):
        changed = copy.deepcopy(later); changed[field]['changed'] = 'x'
        with pytest.raises(ValueError, match='changed'):
            requests.assert_frozen(frozen, changed)
    with pytest.raises(ValueError):
        requests.assert_frozen(later, frozen)


def test_pose_raw_current_revision_geometry_and_latest_event_are_frozen(tmp_path):
    path = tmp_path/'pose.sqlite3'; r = row('a', 14); value = pose(r, 8)
    raw = json.dumps(value, indent=2)
    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 (?,?,?)', ('a', 8, raw))
        db.execute('INSERT INTO events VALUES (?,?,?,?)', (1, 'a', 8, raw))
    current, raws, events, _ = requests.pose_rows(path, {'a': r})
    binding = requests.pose_binding('a', dict(current=current, current_raw=raws, history={'a': events}))
    assert binding['existing_pose_revision'] == 8
    assert binding['existing_pose_payload_raw_sha256'] == requests.raw_sha(raw)
    assert binding['existing_pose_geometry_sha256'] == requests.sha({f: value[f] for f in requests.GEOMETRY})
    with sqlite3.connect(path) as db:
        # Same JSON and same row counts do not authorize silently replacing raw bytes.
        db.execute('UPDATE annotations SET payload=?', (json.dumps(value),))
    with pytest.raises(ValueError, match='latest raw event'):
        requests.pose_rows(path, {'a': r})


def make_parent(root, bad_quad=False):
    remaining = (3, 4, 5, 6, 7, 8, 11, 12, 13, 14, 16, 17, 18, 19, 20, 21, 22)
    def proposal(key, cls, manual=False):
        return dict(target_key=key, class_id=cls, source=dict(frame_id='frame-'+key),
            polygon=[[2, 2], [50, 1], [51, 20], [1, 21]], manual_four_point_source=manual,
            propagation_seed_eligible=not manual)
    old = [proposal(f'old-{c}-{i}', c) for c in (1, 2, 9, 10, 15) for i in range(100)]
    reused = [proposal(f'reused-{i}', remaining[i % 17], True) for i in range(141)]
    completed = [proposal(f'completed-{c}-{i}', c, True) for c in remaining for i in range(3)]
    if bad_quad:
        next(p for p in completed if p['class_id'] == 5)['propagation_seed_eligible'] = True
    machines = [proposal('machine-'+str(i), 4) for i in range(2)]
    all_values = old+reused+completed+machines
    (root/'parent_evidence').mkdir(parents=True)
    for name, values in (('parent_evidence/proposals.jsonl', old), ('reuse_old_manual_proposals.jsonl', reused),
            ('completed_request_manual_proposals.jsonl', completed), ('new_proposals.jsonl', machines),
            ('proposals.jsonl', all_values)):
        requests.write_jsonl(root/name, values)
    counts = requests.Counter(p['class_id'] for p in all_values)
    manifest = dict(publication_version=10, previous_proposals=500, reused_old_manual_proposals=141,
        completed_request_manual_proposals=51, manual_proposals=192, base_proposals=692,
        generation_templates=41, proposals=len(all_values), frozen_code_sha256={},
        proposals_sha256=requests.digest(root/'proposals.jsonl'), classes={str(c):
            dict(total=counts[c], distinct_frames=counts[c], missing=100-counts[c]) for c in range(1, 23)})
    requests.write_json(root/'manifest.json', manifest)
    requests.write_json(root/'generation_validation.json', dict(
        state='self_checks_passed_not_independent_verification', publication_version=10))
    requests.write_json(root/'artifact_hashes.json', requests.file_inventory(root))
    return manifest


def test_complete_parent_generation_can_stage_without_seal_but_cannot_build(tmp_path):
    manifest = make_parent(tmp_path)
    data = requests.load_parent(tmp_path, False)
    assert len(data['proposals']) == 694
    assert data['quotas'] == {c: 10 for c in requests.CLASSES}
    with pytest.raises(ValueError, match='Build requires'):
        requests.load_parent(tmp_path, True)
    requests.write_json(tmp_path/'verification.json', dict(state='passed', publication_version=10,
        proposals_verified=694, manifest_sha256=requests.digest(tmp_path/'manifest.json'),
        proposals_sha256=manifest['proposals_sha256'], artifact_hashes_sha256=requests.digest(tmp_path/'artifact_hashes.json')))
    assert requests.load_parent(tmp_path, True)['seals']


def test_parent_target_class_real_quads_cannot_be_relabelled_as_seeds(tmp_path):
    make_parent(tmp_path, bad_quad=True)
    with pytest.raises(ValueError, match='valid saved quads'):
        requests.load_parent(tmp_path)


@pytest.fixture
def staged(tmp_path, monkeypatch):
    """Small complete two-phase fixture; all files are pytest-owned temporary data."""
    formal = tmp_path/'formal'; formal.mkdir()
    rows = {}
    for cls in requests.CLASSES:
        for i in range(3):
            key = f'{cls:02x}{i:022x}'
            r = row(key, cls)
            rows[key] = r
            pixels = np.random.default_rng(cls+i).integers(0, 255, (40, 100), dtype=np.uint8)
            Image.fromarray(pixels).save(formal/r['image'])
    class Evidence:
        used = {}
        sources = {r['frame_id']: dict(image=r['image'], native=True) for r in rows.values()}
        def image(self, frame):
            r = next(r for r in rows.values() if r['frame_id'] == frame)
            return np.asarray(Image.open(formal/r['image']))
    limits = {4: 3, 5: 0, 7: 2, 14: 1, 22: 1}
    current, current_raw, history = {}, {}, {}
    old_key = next(k for k, r in rows.items() if r['final_class_id'] == 14)
    current[old_key] = pose(rows[old_key], 8)
    current_raw[old_key] = json.dumps(current[old_key], indent=2)
    history[old_key] = [dict(event_id=12, revision=8, original_rectangle=True, original_pose_only=True)]
    pool = {k: usable(k not in current) for k in rows}
    # Class14 has no virgin alternatives in this fixture.
    for k, r in rows.items():
        if r['final_class_id'] == 14 and k != old_key:
            del pool[k]
    classes = {str(c): dict(total=100-limits[c], distinct_frames=100-limits[c],
        missing=limits[c], saved_human=7, new_machine_pending=2) for c in requests.CLASSES}
    parent_manifest = dict(proposals=800, saved_human=335, new_proposals=108, classes=classes)
    parent = tmp_path/'parent'; parent.mkdir()
    for name in ('manifest.json', 'proposals.jsonl'):
        (parent/name).write_text('{}')
    frozen = dict(parent_directory='parent', parent_generation_inventory={'manifest.json': 'm'},
        parent_existing_audit_hashes={}, per_class=10, formal_manifest_sha256='formal',
        classification_sha256='classification', pose_public_url='https://example.test/pose',
        database_logical_fingerprints={'pose': 'pose-full', 'gallery': 'gallery-full'},
        configuration_sha256={'active_formal_dataset.json': 'cfg'}, protected_formal_files={'formal': 'freeze'},
        snapshots={'pose': {'sha256': 'p'}, 'gallery': {'sha256': 'g'}})
    data = dict(parent=dict(manifest=parent_manifest, proposals=[], seals={'verification.json': 'external'}, inventory={}),
        formal=formal, rows=rows, original_rows=copy.deepcopy(rows), evidence=Evidence(), current=current,
        current_raw=current_raw, history=history, protected=set(), protected_frames=set(), quotas=limits,
        usable=pool, populations={}, rejections={}, frozen=frozen)
    calls = []
    def prepare(out, parent, per_class, require_seal=False):
        calls.append(require_seal)
        return data
    monkeypatch.setattr(requests, 'prepare', prepare)
    monkeypatch.setattr(requests, 'finish_stability', lambda *a: None)
    monkeypatch.setattr(requests, 'protected_snapshot', lambda *a: {'formal': 'freeze'})
    # Paths in this fixture still need to be project-relative in the manifest.
    monkeypatch.setattr(requests, 'PROJECT', tmp_path)
    (tmp_path/'scripts').mkdir()
    (tmp_path/'scripts/build_mask_template_requests.py').write_text('# fixture helper fingerprint only\n')
    def contact(root, records, name, full=False):
        assert 1 <= len(records) <= 6
        Image.new('RGB', (100, 50)).save(root/name)
    monkeypatch.setattr(requests, 'contact', contact)
    def font(out, text):
        (out/'report-font.otf').write_bytes(b'fixture-font')
        (out/'FONT_LICENSE.txt').write_text('fixture-license')
    monkeypatch.setattr(requests, 'build_font', font)
    out = tmp_path/'worklist'
    requests.review(out, parent)
    return out, parent, data, calls


def approve(out, **override):
    decisions = {r['target_key']: dict(approved=True, crop_inspected=True, full_image_inspected=True,
        note_zh='原图与局部均清晰；真实轮廓由人工决定。', **override)
        for r in requests.read_jsonl(out/'internal/review/shortlist.jsonl')}
    requests.private_json(out/'internal/source_visual_decisions.json', decisions)
    return decisions


def test_review_is_fresh_private_montages_chunks_six_and_never_fabricates_visual_decisions(staged):
    out, parent, data, calls = staged
    assert calls == [False]
    assert not (out/'internal/source_visual_decisions.json').exists()
    assert not (out/'manifest.json').exists() and not (out/'requests.jsonl').exists()
    assert not list(out.rglob('*.sqlite*'))
    records = requests.read_jsonl(out/'internal/review/shortlist.jsonl')
    assert len(records) == 7
    assert {p.name for p in (out/'internal/review').glob('full_*.png')} == {'full_01.png', 'full_07.png'}
    assert requests.read_json(out/'input_manifest.json')['database_logical_fingerprints'] == data['frozen']['database_logical_fingerprints']
    with pytest.raises(ValueError, match='fresh'):
        requests.review(out, parent)


@pytest.mark.parametrize('attack', ['missing', 'crop', 'full', 'note'])
def test_build_requires_real_explicit_per_source_inspection(staged, attack):
    out, parent, _, calls = staged
    if attack != 'missing':
        decisions = approve(out)
        key = next(iter(decisions))
        decisions[key][dict(crop='crop_inspected', full='full_image_inspected', note='note_zh')[attack]] = ''
        requests.private_json(out/'internal/source_visual_decisions.json', decisions)
    with pytest.raises((ValueError, FileNotFoundError)):
        requests.build(out, parent)
    assert calls[-1] is True
    assert not (out/'requests.jsonl').exists()


def test_build_uses_actual_seven_not_fifty_private_raw_pose_and_exact_public_allowlist(staged):
    out, parent, data, calls = staged
    approve(out)
    result = requests.build(out, parent)
    assert calls == [False, True]
    assert result['request_count'] == 7 and result['public_assets'] == 17
    assert result['independent_verification_still_required'] is True
    manifest = requests.read_json(out/'manifest.json')
    records = requests.read_jsonl(out/'requests.jsonl')
    assert manifest['requested_class_counts']['5'] == 0
    assert manifest['class_counts'] == {'4': 3, '5': 0, '7': 2, '14': 1, '22': 1}
    assert len(manifest['public_assets']) == 3+2*len(records)
    assert 'requests.jsonl' not in manifest['public_assets']
    assert not (out/'requests.jsonl').stat().st_mode & 0o077
    assert not list(out.rglob('*.sqlite*'))
    assert not (out/'masks').exists() and not (out/'labelme').exists()
    for r in records:
        assert r['requested_required_vertex_count'] is None and r['minimum_manual_template_vertices'] == 5
        assert r['valid_four_point_manual_contour_allowed'] and r['valid_four_point_manual_contour_is_not_transfer_seed']
        assert r['extra_vertices_must_not_be_forced'] and not r['neighbor_propagation_promised']
        assert r['closest_human_reference_key'] is None and 'polygon' not in r
        assert all(r[f] is False for f in requests.FALSE_FLAGS)
        assert r['generated_polygons'] == 0 and not r['counts_as_completed_annotation']
        assert requests.digest(out/r['native_image']) == requests.digest(data['formal']/r['source']['image'])
    old = next(r for r in records if r['class_id'] == 14)
    assert old['existing_pose_revision'] == 8
    assert old['existing_pose_payload_raw_sha256'] == requests.raw_sha(old['existing_pose_current_payload_raw'])
    assert old['existing_pose_geometry_sha256'] == requests.sha({f: old['existing_pose_current_payload'][f] for f in requests.GEOMETRY})
    page = (out/'report_zh.html').read_text()
    assert old['existing_pose_payload_raw_sha256'] in page and old['existing_pose_geometry_sha256'] in page
    for forbidden in ('existing_pose_current_payload', 'current_payload_raw', '.sqlite', 'access_code', 'password'):
        assert forbidden not in page
    assert 'Class 5描错' in page and '不据此判定' in page
    assert 'table-layout:fixed' in page and 'overflow-wrap:anywhere' in page and 'max-width:100%' in page
    assert 'min-width:1090px' not in page and 'request-filter' in page
    assert not (out/'verification.json').exists()
    with pytest.raises(ValueError, match='Never overwrite'):
        requests.build(out, parent)


def test_rejected_sources_reduce_tasks_honestly_without_uninspected_refill(staged):
    out, parent, _, _ = staged
    decisions = approve(out)
    decisions[next(iter(decisions))]['approved'] = False
    requests.private_json(out/'internal/source_visual_decisions.json', decisions)
    assert requests.build(out, parent)['request_count'] == 6
    manifest = requests.read_json(out/'manifest.json')
    assert sum(manifest['unfilled_requested_class_counts'].values()) == 1


def test_changed_inspection_crop_is_rejected_not_silently_rerendered(staged):
    out, parent, _, _ = staged
    approve(out)
    crop = next((out/'internal/review/cases').glob('*.png'))
    crop.write_bytes(b'changed')
    with pytest.raises(ValueError, match='Review images'):
        requests.build(out, parent)


def test_source_changed_between_review_and_build_requires_fresh_output(staged):
    out, parent, data, _ = staged
    approve(out)
    data['frozen']['database_logical_fingerprints']['pose'] = 'new-payload-same-count'
    with pytest.raises(ValueError, match='fresh output'):
        requests.build(out, parent)
    assert not (out/'requests.jsonl').exists()


def test_verify_is_read_only_self_audit_and_never_writes_independent_seal(staged, monkeypatch):
    out, parent, _, _ = staged
    approve(out); requests.build(out, parent)
    from fontTools import ttLib
    class Font:
        def __init__(self, *args):
            pass
        def __enter__(self):
            return self
        def __exit__(self, *args):
            pass
        def getBestCmap(self):
            return set(range(0x3400, 0xa000))
    monkeypatch.setattr(ttLib, 'TTFont', Font)
    before = requests.file_inventory(out)
    result = requests.verify(out, parent)
    assert result['state'] == 'self_checks_passed_not_independent_verification'
    assert requests.file_inventory(out) == before
    assert not (out/'verification.json').exists() and not (out/'independent_verification.json').exists()
    (out/'cases/unlisted.png').write_bytes(b'not-allowlisted')
    with pytest.raises(ValueError, match='file inventory'):
        requests.verify(out, parent)


def test_unsafe_artifact_and_overlapping_output_paths_are_rejected(tmp_path):
    with pytest.raises(ValueError, match='Unsafe'):
        requests.member(tmp_path, '../private.sqlite3')
    with pytest.raises(ValueError):
        requests.valid_output(requests.PARENT/'pallet_mask_remaining_direct_requests_v1', requests.PARENT)
