"""Publication14 contracts; only temporary stores, never production writes."""
import copy
import hashlib
import json
import sqlite3
from collections import Counter

import numpy as np
from PIL import Image
import pytest

from pallet import mask_remaining_round4 as round4
from pallet import mask_saved_preannotations as saved
from pallet.mask_template_transfer import rectangle
from pallet.pose_review_geometry import canonical, raster_mask

QUAD = [[1.1, 1.5], [20, 1], [20.1, 9], [1, 10]]
EDIT = [[1.2, 1.6], [20, 1], [20.1, 9], [1, 10]]
POLYGON = [[1, 1], [20, 1], [20, 10], [15, 10], [15, 5], [5, 5], [5, 10], [1, 10]]


def row(key='saved', cls=4, frame=None):
    return dict(target_key=key, target_id='target-'+key, frame_id=frame or 'frame-'+key,
        final_class_id=cls, split='train', group_id='group-'+key, box_index=0,
        policy_id='camera', viewpoint_candidate='front', source_pcd_sha256='pcd',
        bbox=dict(x=1, y=1, width=19, height=9), size=[24, 16])


def proposal(key, cls=4, frame=None):
    return dict(target_key=key, class_id=cls, source=row(key, cls, frame), metrics={})


@pytest.fixture
def task(tmp_path):
    publication, directory = tmp_path/'publication13', tmp_path/'tasks'
    for p in (publication, directory):
        (p/'images').mkdir(parents=True)
    r = row()
    native = np.zeros((16, 24), np.uint8)
    Image.fromarray(native).save(directory/'images/saved.png')
    image_sha = round4.digest(directory/'images/saved.png')
    canonical_proposal = dict(proposal('canonical'), polygon=POLYGON, vertex_count=8,
        formal_manifest_sha256='formal')
    Image.fromarray(native).save(publication/'images/canonical.png')
    round4.write_jsonl(publication/'proposals.jsonl', [canonical_proposal])
    pub_sha = round4.digest(publication/'proposals.jsonl')
    round4.write_json(publication/'manifest.json', dict(publication_version=13,
        formal_manifest_sha256='formal', proposals_sha256=pub_sha))
    round4.write_json(publication/'verification.json', dict(state='passed', proposals_sha256=pub_sha))
    round4.write_json(directory/'input_manifest.json', dict(formal_manifest_sha256='formal'))
    input_sha = round4.digest(directory/'input_manifest.json')
    draft = dict(schema='assistant_visual_preannotation_v1', origin='assistant_visual_preannotation',
        source=r, target_key='saved', class_id=4, polygon=copy.deepcopy(QUAD), vertex_count=4,
        formal_manifest_sha256='formal', status='assistant_preannotated_draft_pending_human_review',
        target_expected_revision=0, target_snapshot_payload_sha256=None,
        mask_semantics='assistant_direct_visible_fork_face_contour_draft_not_GT',
        draft_source=dict(target_key='saved', origin='assistant_visual_preannotation',
            snapshot_revision=0, current_payload_sha256=None),
        preannotation=dict(author_role='AI_assistant', image_sha256=image_sha,
            input_manifest_sha256=input_sha, polygon_sha256=round4.sha(QUAD),
            method='assistant_direct_native_image_contour_not_template_transfer',
            crop_inspected=True, full_image_inspected=True, human_saved=False,
            counts_toward_coverage_before_real_human_save=False, note_zh='只作助手预标注'),
        **dict.fromkeys(('human_edited', 'human_mask_confirmed', 'human_pose_confirmed', 'ground_truth_eligible',
            'automatic_training_eligible', 'robot_command_eligible', 'production_saved', 'counts_as_completed_annotation',
            'accepted_candidate', 'propagation_seed_eligible'), False))
    request = dict(target_key='saved', class_id=4, source=r, assistant_polygon=QUAD,
        preannotation=draft['preannotation'], counts_as_completed_annotation=False,
        existing_pose_record=False, existing_pose_revision=0, existing_pose_payload_sha256=None)
    round4.write_jsonl(directory/'proposals.jsonl', [draft])
    round4.write_jsonl(directory/'requests.jsonl', [request])
    manifest = dict(request_count=1, formal_manifest_sha256='formal', parent_proposals_sha256=pub_sha,
        proposals_sha256=round4.digest(directory/'proposals.jsonl'), requests_sha256=round4.digest(directory/'requests.jsonl'),
        input_manifest_sha256=input_sha, class_counts={'4': 1})
    round4.write_json(directory/'manifest.json', manifest)
    publications = round4.original.publication_inventory({13: publication}, 'formal')
    registry = saved.prelabel_registry(directory, {'saved': r}, 'formal', publications[13], {}, set())
    ref = registry['saved']
    value = dict(target_key='saved', revision=2, source=ref['source'], source_binding=ref['source_binding'],
        binding=ref['binding'], base_proposal_id=ref['proposal_sha256'], proposal_publication=13,
        event_kind='human_mask_gallery_revision', human_edited=True,
        polygon=copy.deepcopy(EDIT), vertex_count=4, proposal_polygon=QUAD, original_vertex_count=4,
        preannotation_provenance=copy.deepcopy(ref['preannotation_provenance']), template_provenance=None,
        human_source_provenance=None, pose=None, pose_store_written=False, original_proposal_modified=False,
        status='human_edited_draft_pending_confirmation', mask_semantics=draft['mask_semantics'], reviewer='标注员',
        **dict.fromkeys(saved.FALSE_FLAGS, False))
    return dict(directory=directory, publication=publication, publications=publications, rows={'saved': r},
        registry=registry, value=value, draft=draft, request=request)


def database(value):
    db = sqlite3.connect(':memory:')
    db.executescript('CREATE TABLE reviews(target_key TEXT,revision INTEGER,payload TEXT);'
        'CREATE TABLE events(id INTEGER PRIMARY KEY,target_key TEXT,revision INTEGER,payload TEXT);')
    old = copy.deepcopy(value)
    old['revision'] = 1
    for v in (old, value):
        db.execute('INSERT INTO events(target_key,revision,payload) VALUES (?,?,?)',
            (v['target_key'], v['revision'], json.dumps(v, ensure_ascii=False, indent=2)))
    db.execute('INSERT INTO reviews VALUES (?,?,?)',
        (value['target_key'], value['revision'], json.dumps(value, ensure_ascii=False, indent=2)))
    return db


def audit(task, db):
    return saved.gallery_source_records(db, task['rows'], [], task['publication'], 'formal',
        'snapshot', {13: task['publication']}, task['registry'])


def manual(task, reviews, records, previous=(), current=None, prohibited=()):
    return saved.completed_gallery_proposals(task['registry'], reviews, round4.indexed(records), task['rows'],
        list(previous), current or {}, 'pose', 'gallery', 'formal', 'classes', round4.GENERATION_NAMESPACE, prohibited)


def test_constants_pinned_inputs_no_old_engine_monkeypatch():
    assert round4.PUBLICATION_VERSION == 14
    assert round4.PARENT == round4.previous_generation.OUTPUT
    assert round4.OUTPUT.name == 'pallet_mask_remaining_round4_v1'
    assert round4.REQUESTS.name == 'pallet_mask_preannotated_requests_v1'
    assert round4.GENERATION_NAMESPACE == 'remaining_round4_generation'
    assert round4.MANUAL_SCHEMA == 'saved_gallery_mask_entry_v1'
    assert round4.attempt_target is round4.original.attempt_target
    assert round4.original.CLASSES == (1, 2, 9, 10, 15)
    assert round4.HISTORICAL_NAMESPACES[-1] == round4.previous_generation.GENERATION_NAMESPACE
    assert round4.PARENT_PINS['manifest.json'] == 'f2f985337f5efb17543e1f2df5588196fb6c597fc9f6167be52a14e68381e8d1'
    assert round4.REQUEST_PINS['verification.json'] == '8403c2f92a2bd73da4f874278d83af7dc4a2380b0e29a0af83e9481ed8e8e054'


def test_instruction_cannot_reauthorize_old_pending_boxes():
    instruction = round4.user_instruction([proposal('task')], [proposal('old')])
    assert instruction['date'] == '2026-10-25'
    assert instruction['statement_zh'] == '完成复核和修正，继续'
    assert instruction['actual_parent_new_candidate_count'] == instruction['actual_current_request_count'] == 1
    assert not instruction['current_original_rectangle_no_change_authorized']
    assert instruction['historical_original_rectangle_statement_bindings_unchanged']
    assert not instruction['creates_human_event'] and not instruction['authorizes_propagation']
    assert 'reviewed_original_rectangle_keys' not in instruction


def test_independent_draft_hash_not_in_canonical_publication_is_valid(task):
    assert 'saved' not in task['publications'][13]['proposals']
    with database(task['value']) as db:
        before = db.total_changes
        reviews, events, records, templates, audits = audit(task, db)
        assert db.total_changes == before
    assert len(reviews) == len(records) == 1 and len(events) == len(audits) == 2
    assert templates == {}
    assert all(a['proposal_registry'] == 'independent_preannotation' for a in audits)
    assert all(a['preannotation_provenance_validated'] for a in audits)
    rec = records[0]
    assert rec['current_payload_raw'] == rec['human_event_payload_raw']
    assert rec['current_payload_raw_sha256'] == hashlib.sha256(rec['current_payload_raw'].encode()).hexdigest()


def test_canonical_and_independent_task_events_share_binding_not_proposal_registry(task):
    canonical_proposal = task['publications'][13]['proposals']['canonical']
    r = canonical_proposal['source']
    task['rows']['canonical'] = r
    identity = {f: r[f] for f in saved.IDENTITY_FIELDS}
    identity.update(formal_manifest_sha256='formal',
        image_sha256=round4.digest(task['publication']/'images/canonical.png'))
    value = dict(target_key='canonical', revision=1, source=identity, source_binding=round4.sha(identity),
        binding=task['value']['binding'], base_proposal_id=round4.sha(canonical_proposal), proposal_publication=13,
        event_kind='human_mask_gallery_revision', human_edited=True, polygon=POLYGON, vertex_count=8,
        **dict.fromkeys(saved.FALSE_FLAGS, False))
    with database(task['value']) as db:
        raw = json.dumps(value, ensure_ascii=False, indent=2)
        db.execute('INSERT INTO reviews VALUES (?,?,?)', ('canonical', 1, raw))
        db.execute('INSERT INTO events(target_key,revision,payload) VALUES (?,?,?)', ('canonical', 1, raw))
        reviews, events, records, templates, audits = audit(task, db)
    assert len(reviews) == len(records) == 2 and len(events) == len(audits) == 3
    assert set(templates) == {'canonical'}
    assert templates['canonical']['polygon'] == POLYGON
    assert Counter(a['proposal_registry'] for a in audits) == {
        'independent_preannotation': 2, 'canonical_publication': 1}


@pytest.mark.parametrize('attack', ['binding', 'base_hash', 'publication', 'source', 'source_binding', 'revision',
    'target', 'vertices', 'auto_kind', 'not_human', 'gt', 'training', 'robot', 'human_confirmed', 'metric_pose',
    'nested_gt', 'machine', 'deleted', 'draft_hash', 'draft_author', 'draft_image', 'task_manifest',
    'fake_human_draft', 'draft_polygon', 'template', 'human_pose_provenance', 'pose', 'pose_written',
    'original_modified', 'status', 'reviewer', 'semantics', 'duplicate', 'current_raw', 'missing_latest'])
def test_every_older_task_event_fails_closed(task, attack):
    value = copy.deepcopy(task['value'])
    value['revision'] = 1
    changes = dict(binding=('binding', 'wrong'), base_hash=('base_proposal_id', 'canonical-not-draft'),
        publication=('proposal_publication', 12), source_binding=('source_binding', 'wrong'),
        revision=('revision', 99), target=('target_key', 'wrong'), vertices=('vertex_count', 8),
        auto_kind=('event_kind', 'mask_template_proposal'), not_human=('human_edited', False),
        gt=('ground_truth_eligible', True), training=('automatic_training_eligible', True),
        robot=('robot_command_eligible', True), human_confirmed=('human_confirmed', True),
        metric_pose=('metric_pose_confirmed', True), nested_gt=('pose', {'ground_truth_eligible': True}),
        machine=('machine_transfer_performed', True), deleted=('state', 'deleted'),
        draft_polygon=('proposal_polygon', EDIT), template=('template_provenance', {'fake': True}),
        human_pose_provenance=('human_source_provenance', {'origin': 'original_pose_human_revision'}),
        pose=('pose', {}), pose_written=('pose_store_written', True), original_modified=('original_proposal_modified', True),
        status=('status', 'confirmed'), reviewer=('reviewer', ''), semantics=('mask_semantics', 'GT'))
    if attack in changes:
        f, v = changes[attack]
        value[f] = v
    elif attack == 'source':
        value['source'] = dict(value['source'], split='test')
    elif attack == 'draft_hash':
        value['preannotation_provenance']['proposal_sha256'] = 'wrong'
    elif attack in ('draft_author', 'draft_image'):
        value['preannotation_provenance']['assistant_draft']['author_role' if attack == 'draft_author' else 'image_sha256'] = 'wrong'
    elif attack == 'task_manifest':
        value['preannotation_provenance']['worklist_manifest_sha256'] = 'other task'
    elif attack == 'fake_human_draft':
        value['preannotation_provenance']['assistant_draft_not_human_edit'] = False
    with database(task['value']) as db:
        db.execute('UPDATE events SET payload=? WHERE revision=1', (json.dumps(value),))
        if attack == 'duplicate':
            db.execute('INSERT INTO events(target_key,revision,payload) SELECT target_key,revision,payload FROM events LIMIT 1')
        elif attack == 'current_raw':
            db.execute('UPDATE reviews SET payload=?', (json.dumps(task['value']),))
        elif attack == 'missing_latest':
            db.execute('DELETE FROM events WHERE revision=2')
        with pytest.raises(ValueError):
            audit(task, db)


@pytest.mark.parametrize('attack', ['pose_created', 'pose_history_only', 'pose_changed', 'draft_class', 'request_source',
    'image', 'request_polygon', 'human_draft', 'original_rectangle', 'image_proof', 'input_proof'])
def test_registry_rejects_stale_identity_pose_dependency_and_forged_drafts(task, attack):
    draft, request = copy.deepcopy(task['draft']), copy.deepcopy(task['request'])
    current, history = {}, set()
    if attack in ('pose_created', 'pose_changed'):
        current['saved'] = dict(revision=1, polygon=EDIT)
    elif attack == 'pose_history_only':
        history.add('saved')
    elif attack == 'draft_class':
        draft['class_id'] = 5
    elif attack == 'request_source':
        request['source']['split'] = 'test'
    elif attack == 'image':
        (task['directory']/'images/saved.png').write_bytes(b'changed-native-image')
    elif attack == 'request_polygon':
        request['assistant_polygon'] = EDIT
    elif attack == 'human_draft':
        draft['human_edited'] = True
    elif attack == 'original_rectangle':
        draft['polygon'] = rectangle(task['rows']['saved'])
        draft['preannotation']['polygon_sha256'] = round4.sha(draft['polygon'])
    elif attack == 'image_proof':
        draft['preannotation']['image_sha256'] = 'wrong'
    elif attack == 'input_proof':
        draft['preannotation']['input_manifest_sha256'] = 'wrong'
    directory = task['directory']
    round4.write_jsonl(directory/'proposals.jsonl', [draft])
    round4.write_jsonl(directory/'requests.jsonl', [request])
    m = round4.read_json(directory/'manifest.json')
    m.update(proposals_sha256=round4.digest(directory/'proposals.jsonl'), requests_sha256=round4.digest(directory/'requests.jsonl'))
    round4.write_json(directory/'manifest.json', m)
    with pytest.raises(ValueError):
        saved.prelabel_registry(directory, task['rows'], 'formal', task['publications'][13], current, history)


def test_real_saved_gallery_canonical_uses_self_reference_not_template_or_pose(task, tmp_path):
    with database(task['value']) as db:
        reviews, _, records, _, _ = audit(task, db)
    proposals = manual(task, reviews, records)
    p = proposals[0]
    assert p['schema'] == 'saved_gallery_mask_entry_v1' and p['origin'] == 'mask_gallery_human_revision'
    assert p['human_edited'] and p['saved_gallery_manual_source'] and p['manual_four_point_source']
    assert p['human_source']['target_key'] == p['target_key']
    assert p['human_source']['gallery_review']['human_event_id'] == records[0]['human_event_id']
    assert p['human_source']['gallery_review']['current_payload_raw_sha256'] == records[0]['current_payload_raw_sha256']
    assert p['polygon'] == EDIT and p['polygon'] != task['draft']['polygon']
    assert p['rendering_id'] == 'remaining_round4_generation:manual_source:saved'
    assert p['target_expected_revision'] == 0 and p['target_snapshot_payload_sha256'] is None
    for f in ('template', 'pose_review', 'human_polygon_revision', 'original_pose_url', 'pose_snapshot_saved'):
        assert f not in p
    assert not p['propagation_seed_eligible'] and not p['machine_draft'] and not p['pose_store_written']
    assert all(p[f] is False for f in saved.FALSE_FLAGS)
    inventory = round4.rendering_inventory(dict(templates=[], rendering_by_target={}), {}, proposals, proposals, set())
    assert not inventory['templates'] and len(inventory['manual_source_renderings']) == 1
    assert inventory['publication_version'] == 14
    class Evidence:
        def image(self, frame):
            return np.zeros((16, 24), np.uint8)
    for directory in ('cases', 'images', 'masks', 'labelme'):
        (tmp_path/directory).mkdir()
    saved.package_manual_preview(tmp_path, proposals, Evidence())
    label = round4.read_json(tmp_path/'labelme/saved.json')
    assert label['shapes'][0]['points'] == EDIT
    assert label['flags']['saved_gallery_manual_source'] and not label['flags']['ground_truth_eligible']
    assert np.array_equal(np.asarray(Image.open(tmp_path/'masks/saved.png')) > 0, raster_mask(EDIT, 24, 16))


def test_unchanged_assistant_polygon_requires_real_saved_human_event_still_counts(task):
    value = copy.deepcopy(task['value'])
    value['polygon'] = copy.deepcopy(QUAD)
    with database(value) as db:
        reviews, _, records, _, _ = audit(task, db)
    p = manual(task, reviews, records)[0]
    assert p['human_edited'] and p['polygon_changed_from_assistant_draft'] is False
    status, _ = round4.saved_status([task['draft']], reviews, round4.indexed(records), 'snapshot')
    assert status['actually_saved'] == status['saved_unchanged'] == 1
    assert status['polygon_changed_from_proposal'] == 0
    with pytest.raises(ValueError):
        manual(task, {}, [])


@pytest.mark.parametrize('attack', ['locked_key', 'locked_frame', 'reserved_frame', 'original_rectangle', 'vertices', 'raw_pair'])
def test_saved_manual_additions_fail_closed(task, attack):
    with database(task['value']) as db:
        reviews, _, records, _, _ = audit(task, db)
    previous, protected = [], []
    if attack == 'locked_key':
        previous.append(proposal('saved'))
    elif attack == 'locked_frame':
        previous.append(proposal('other', 19, 'frame-saved'))
    elif attack == 'reserved_frame':
        protected.append('frame-saved')
    elif attack == 'original_rectangle':
        reviews['saved']['polygon'] = rectangle(task['rows']['saved'])
    elif attack == 'vertices':
        reviews['saved']['polygon'] = POLYGON
    else:
        records[0]['human_event_payload_raw'] += ' '
    with pytest.raises(ValueError):
        manual(task, reviews, records, previous=previous, prohibited=protected)


def test_whole_frame_protection_for_other_objects_all_risk_histories_and_tasks():
    protected = ['returned', 'deleted', 'deferred', 'confirmed']
    rows = {r['target_key']: r for r in [row(k) for k in protected] +
        [row('cross-'+k, 19, 'frame-'+k) for k in protected] +
        [row('gallery'), row('cross-gallery', 19, 'frame-gallery'),
            row('quarantine'), row('cross-quarantine', 19, 'frame-quarantine'),
            row('task'), row('cross-task', 19, 'frame-task'), row('active', 19)]}
    work, outcomes = round4.target_inventory(rows, [], dict.fromkeys(rows, 'eligible'),
        set(protected), {'gallery'}, {'quarantine'}, {'frame-task'})
    assert [k for k, _ in work] == ['active']
    reasons = {o['target_key']: o['reason'] for o in outcomes}
    assert all(reasons['cross-'+k] == 'whole_frame_history_or_task_reserved'
        for k in protected+['gallery', 'quarantine', 'task'])


def test_historical_task_inventory_includes_every_queue_and_rejected_draft(tmp_path, monkeypatch):
    monkeypatch.setattr(round4, 'PROJECT', tmp_path)
    task_dir = tmp_path/'outputs/pallet_mask_preannotated_requests_v1'
    (task_dir/'internal').mkdir(parents=True)
    earlier = tmp_path/'outputs/pallet_mask_old_requests_v1'
    earlier.mkdir()
    rs = {k: row(k) for k in ('issued', 'old', 'inspected', 'rejected', 'decision-rejected', 'author-rejected')}
    round4.write_jsonl(task_dir/'requests.jsonl', [dict(target_key='issued')])
    round4.write_jsonl(earlier/'requests.jsonl', [dict(source=rs['old'])])
    round4.write_jsonl(task_dir/'internal/shortlist.jsonl', [dict(target_key='inspected')])
    round4.write_json(task_dir/'internal/deferred_sources.json', [dict(target_key='rejected')])
    round4.write_json(task_dir/'internal/build_decisions.json', dict(decisions={'decision-rejected': dict(approved=False)}))
    round4.write_json(task_dir/'internal/assistant_decisions.json', dict(decisions=[dict(target_key='author-rejected', approved=False)]))
    keys, hashes = round4.historical_task_inventory(rs, task_dir)
    assert keys == set(rs)
    assert len(hashes) == 6
    assert all(round4.digest(tmp_path/name) == h for name, h in hashes.items())


def test_all_full_classes_including_class8_skip_and_capacity_is_dynamic():
    filled = (1, 2, 3, 6, 8, 9, 10, 13, 15)
    locked = [proposal(f'full{c}-{i}', c) for c in filled for i in range(100)] + [proposal('nineteen', 19)]
    rs = [row('target'+str(c), c) for c in filled] + [row('next', 19), row('reserved', 19)]
    rows = {r['target_key']: r for r in rs}
    work, outcomes = round4.target_inventory(rows, locked, dict.fromkeys(rows, 'eligible'), set(), set(), set(), {'frame-reserved'})
    assert [k for k, _ in work] == ['next']
    assert all(o['reason'] == 'locked_class_quota_full' for o in outcomes if o['class_id'] in set(filled) & set(round4.CLASSES))
    assert all(o['reason'] == 'class_not_requested' for o in outcomes if o['class_id'] in set(filled) - set(round4.CLASSES))
    potential, _, _, _ = round4.expand.select_locked_diverse(locked,
        [dict(target_key=k, class_id=r['final_class_id'], source=r, metrics={}) for k, r in work])
    assert Counter(p['class_id'] for p in locked+potential)[19] == 2


def test_seed_namespace_preserves_unchanged_reviews_but_no_quad_seed():
    gallery = {'saved': dict(row=row(), polygon=POLYGON, origin=round4.original.GALLERY_ORIGIN,
        saved_review_unchanged=True, new_human_edit_created=False)}
    templates = round4.generation_templates({}, set(), gallery, 'formal', 'classes')
    assert templates['saved']['rendering_id'] == 'remaining_round4_generation:saved'
    assert templates['saved']['saved_review_unchanged']
    gallery['saved']['polygon'] = QUAD
    with pytest.raises(ValueError):
        round4.generation_templates({}, set(), gallery, 'formal', 'classes')


def test_gallery_manual_counts_separately_from_pose_and_assistant_drafts(task):
    with database(task['value']) as db:
        reviews, _, records, _, _ = audit(task, db)
    proposals = manual(task, reviews, records)
    counts = round4.class_counts([], proposals, [], reviews, [], [], [], {}, task['rows'], [], [],
        dict.fromkeys(round4.ALL_CLASSES, 100))
    c = counts[4]
    assert c['saved_gallery_human'] == c['saved_human'] == c['manual_modified_added'] == c['manual_four_point_sources'] == 1
    assert c['saved_pose_human'] == c['modified_pose_source_records'] == c['manual_pose_added'] == 0
    assert c['assistant_drafts_counted_before_human_save'] == 0


def test_old_original_review_statement_binding_paths_and_bytes_never_rebound(tmp_path):
    (tmp_path/'parent_evidence').mkdir()
    statement = dict(statement_zh='old exact statement', target_keys=['old'])
    round4.write_json(tmp_path/'parent_evidence/old.json', statement)
    group = dict(path='parent_evidence/old.json', target_keys=['old'],
        statement_sha256=round4.sha(statement), file_sha256=round4.digest(tmp_path/'parent_evidence/old.json'))
    round4.write_json(tmp_path/'review_statement_bindings.json', dict(historical_groups=[group]))
    records = [dict(target_key='old', user_statement_sha256=round4.sha(statement))]
    binding = round4.historical_review_bindings(tmp_path, records)[0]
    assert binding['path'] == 'parent_evidence/parent_evidence/old.json'
    assert binding['statement_sha256'] == records[0]['user_statement_sha256']
    records[0]['user_statement_sha256'] = round4.sha(round4.user_instruction([], []))
    with pytest.raises(ValueError):
        round4.historical_review_bindings(tmp_path, records)


def test_report_dynamic_counts_and_default_new_only(tmp_path):
    fields = ('old_total', 'manual_modified_added', 'reviewed_original_rectangle', 'saved_human', 'new_candidates',
        'total', 'missing', 'saved_pose_human', 'saved_gallery_human', 'db_stored_human_review', 'capacity_matching_distinct_frames')
    counts = {c: dict.fromkeys(fields, 0) for c in round4.ALL_CLASSES}
    counts[19]['capacity_matching_distinct_frames'] = 57
    status = dict(actually_saved=29, polygon_changed_from_proposal=20, saved_unchanged=9)
    tasks = dict(actually_saved=37, polygon_changed_from_proposal=36, saved_unchanged=1)
    round4.build_report(tmp_path, [], counts, set(), set(), status, tasks, {}, 1515, 12)
    text = (tmp_path/'report_zh.html').read_text()
    assert 'id="only-new" checked' in text
    assert '20份轮廓变化、9份保存保持原候选' in text and '36份相对助手草稿改变、1份保存保持草稿' in text
    assert '原图容量 57' in text and '新增不同原图 43' in text
    assert '37份新人工来源为图册保存，不是位姿保存' in text
    assert all(f'<option value="{c}">{c}</option>' in text for c in round4.ALL_CLASSES)
    assert round4.read_json(tmp_path/'font_coverage.json')['all_report_Chinese_present']


def test_preserve_parent_public_bytes_and_complete_private_task_chain(tmp_path):
    parent, out, tasks = tmp_path/'parent', tmp_path/'out', tmp_path/'tasks'
    for directory, extension in (('cases', 'png'), ('images', 'png'), ('masks', 'png'), ('labelme', 'json')):
        (parent/directory).mkdir(parents=True)
        (out/directory).mkdir(parents=True)
        (parent/directory/f'old.{extension}').write_bytes(('literal-'+directory).encode())
    for namespace in round4.HISTORICAL_NAMESPACES:
        (parent/namespace/'templates').mkdir(parents=True)
        (parent/namespace/'templates/source.json').write_bytes(namespace.encode())
    names = ('vertex2_before_after.png', 'FONT_LICENSE.txt', 'review_dispositions.jsonl', 'review_disposition_statement.json',
        'reviewed_original_rectangle_source_records.jsonl', 'review_completion_statement.json',
        'new_review_completion_statement.json', 'pending_original_rectangle_saves.jsonl', 'all_manual_sources.jsonl')
    for name in names:
        (parent/name).write_bytes((name+' 中文\n').encode())
    (tasks/'internal/deeper').mkdir(parents=True)
    (tasks/'internal/deeper/private.json').write_bytes(b'raw task and draft rejection evidence')
    before = round4.file_inventory(parent)
    hashes = round4.preserve_assets(parent, out, [dict(target_key='old')], tasks)
    assert before == round4.file_inventory(parent)
    assert all(round4.digest(out/name) == h for name, h in hashes.items())
    assert (out/'preannotation_source_evidence/internal/deeper/private.json').read_bytes() == b'raw task and draft rejection evidence'
    assert (out/'all_manual_sources.jsonl').read_bytes() == (parent/'all_manual_sources.jsonl').read_bytes()
    assert (out/'pending_original_rectangle_saves.jsonl').read_bytes() == (parent/'pending_original_rectangle_saves.jsonl').read_bytes()


@pytest.mark.parametrize('attack', ['class', 'split', 'policy', 'viewpoint', 'vertices', 'boundary'])
def test_transfer_keeps_original_compatibility_topology_and_boundary_gate(attack):
    source, target = row('seed', 19), row('target', 19)
    template = dict(row=source, polygon=POLYGON, revision=1, human_polygon_revision=1,
        human_event_sha256='event', current_payload_sha256='current', human_mask_confirmed=False,
        origin=round4.prior.POSE_ORIGIN, pose_review=dict(target_key='seed'))
    accepted = dict(template_key='seed', polygon=copy.deepcopy(POLYGON), template_rank=1,
        metrics=dict(boundary_guard=dict(state='passed')))
    if attack == 'vertices':
        accepted['polygon'].pop()
    elif attack == 'boundary':
        accepted['metrics']['boundary_guard']['state'] = 'failed'
    else:
        target[{'class': 'final_class_id', 'split': 'split', 'policy': 'policy_id', 'viewpoint': 'viewpoint_candidate'}[attack]] = 'other'
    with pytest.raises(ValueError):
        round4.proposal_from_attempt('target', target, accepted, {'seed': template}, {}, 'pose', 'formal', 'classes')


def test_generation_does_not_overwrite_existing_or_outside_outputs(tmp_path):
    existing = tmp_path/'existing'
    existing.mkdir()
    (existing/'user.txt').write_text('preserve user work')
    with pytest.raises(ValueError, match='new outputs directory'):
        round4.generate(existing)
    assert (existing/'user.txt').read_text() == 'preserve user work'
    with pytest.raises(ValueError, match='new outputs directory'):
        round4.generate(tmp_path/'outside')
    with pytest.raises(ValueError, match='Workers'):
        round4.generate(round4.PROJECT/'outputs/invalid-workers-round4-nonexistent', workers=0)
