"""Publication15 contracts; every mutation below is in a temporary store."""
import copy
import json
import sqlite3
from collections import Counter

import numpy as np
from PIL import Image
import pytest

from pallet import mask_remaining_round5 as round5
from pallet import mask_saved_preannotations_v2 as saved
from pallet.mask_template_transfer import rectangle
from pallet.pose_review_geometry import 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={})


def native(path):
    path.parent.mkdir(parents=True, exist_ok=True)
    Image.fromarray(np.zeros((16, 24), np.uint8)).save(path)


def make_publication(directory, version, proposals):
    directory.mkdir()
    for p in proposals:
        native(directory/'images'/f'{p["target_key"]}.png')
    round5.write_jsonl(directory/'proposals.jsonl', proposals)
    round5.write_json(directory/'manifest.json', dict(publication_version=version,
        formal_manifest_sha256='formal', proposals_sha256=round5.digest(directory/'proposals.jsonl')))
    round5.write_json(directory/'verification.json', dict(state='passed',
        manifest_sha256=round5.digest(directory/'manifest.json'), proposals_sha256=round5.digest(directory/'proposals.jsonl')))


def make_task(directory, key, version, publication, rows):
    native(directory/'images'/f'{key}.png')
    r = rows[key]
    round5.write_json(directory/'input_manifest.json', dict(formal_manifest_sha256='formal'))
    input_sha = round5.digest(directory/'input_manifest.json')
    draft = dict(schema='assistant_visual_preannotation_v1', origin='assistant_visual_preannotation',
        source=r, target_key=key, class_id=r['final_class_id'], 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=key, origin='assistant_visual_preannotation', snapshot_revision=0, current_payload_sha256=None),
        preannotation=dict(author_role='AI_assistant', image_sha256=round5.digest(directory/'images'/f'{key}.png'),
            input_manifest_sha256=input_sha, polygon_sha256=round5.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=key, class_id=r['final_class_id'], 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)
    round5.write_jsonl(directory/'proposals.jsonl', [draft])
    round5.write_jsonl(directory/'requests.jsonl', [request])
    manifest = dict(request_count=1, formal_manifest_sha256='formal',
        parent_proposals_sha256=publication['proposals_sha256'], parent_manifest_sha256=publication['manifest_sha256'],
        parent_verification_sha256=publication['verification_sha256'],
        proposals_sha256=round5.digest(directory/'proposals.jsonl'), requests_sha256=round5.digest(directory/'requests.jsonl'),
        input_manifest_sha256=input_sha, class_counts={str(r['final_class_id']): 1},
        public_assets={f'images/{key}.png': round5.digest(directory/'images'/f'{key}.png')})
    round5.write_json(directory/'manifest.json', manifest)
    seal = dict(state='passed', request_count=1, manifest_sha256=round5.digest(directory/'manifest.json'),
        proposals_sha256=manifest['proposals_sha256'], parent_verification_sha256=publication['verification_sha256'],
        public_assets=manifest['public_assets'])
    for name in ('verification.json', 'independent_verification.json'):
        round5.write_json(directory/name, seal)
    return saved.prelabel_registry(directory, rows, 'formal', publication, {}, set(), version, f'v{version-12}')


def task_event(ref, revision=1):
    return dict(target_key=ref['proposal']['target_key'], revision=revision, source=ref['source'], source_binding=ref['source_binding'],
        binding=ref['binding'], base_proposal_id=ref['proposal_sha256'], proposal_publication=ref['proposal_publication'],
        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=ref['proposal']['mask_semantics'], reviewer='标注员',
        **dict.fromkeys(saved.FALSE_FLAGS, False))


def canonical_event(publication, key, revision=1, polygon=None):
    p = publication['proposals'][key]
    identity = {f: p['source'][f] for f in saved.IDENTITY_FIELDS}
    identity.update(formal_manifest_sha256='formal', image_sha256=round5.digest(publication['path']/'images'/f'{key}.png'))
    return dict(target_key=key, revision=revision, source=identity, source_binding=round5.sha(identity),
        binding=publication['binding'], base_proposal_id=round5.sha(p), proposal_publication=14,
        event_kind='human_mask_gallery_revision', human_edited=True,
        polygon=copy.deepcopy(polygon or p['polygon']), vertex_count=len(polygon or p['polygon']),
        **dict.fromkeys(saved.FALSE_FLAGS, False))


@pytest.fixture
def task(tmp_path):
    p13, p14 = tmp_path/'pub13', tmp_path/'pub14'
    normal = dict(proposal('normal'), polygon=POLYGON, vertex_count=8, formal_manifest_sha256='formal')
    old = dict(proposal('old'), polygon=QUAD, vertex_count=4, formal_manifest_sha256='formal', schema=saved.SCHEMA)
    make_publication(p13, 13, [normal])
    make_publication(p14, 14, [normal, old])
    publications = round5.original.publication_inventory({13: p13, 14: p14}, 'formal')
    rows = {k: row(k) for k in ('normal', 'old', 'saved')}
    v1 = make_task(tmp_path/'v1', 'old', 13, publications[13], rows)
    v2 = make_task(tmp_path/'v2', 'saved', 14, publications[14], rows)
    registry = saved.combine_registries(v1, v2)
    refs = {r['proposal']['target_key']: r for r in registry.values()}
    events = [canonical_event(publications[14], 'normal'), task_event(refs['old']),
        canonical_event(publications[14], 'old', 2), task_event(refs['saved'])]
    return dict(publications=publications, rows=rows, registry=registry, refs=refs,
        events=events, previous=list(publications[14]['proposals'].values()), directory=tmp_path/'v2')


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


def audit(task, db):
    return saved.gallery_source_records(db, task['rows'], task['previous'], task['publications'][14]['path'],
        'formal', 'snapshot', {v: p['path'] for v, p in task['publications'].items()}, task['registry'])


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


def test_constants_strict_engine_and_input_pins():
    assert round5.PUBLICATION_VERSION == 15 and round5.PARENT == round5.previous_generation.OUTPUT
    assert round5.OUTPUT.name == 'pallet_mask_remaining_round5_v1'
    assert round5.REQUESTS.name == 'pallet_mask_preannotated_requests_v2'
    assert round5.GENERATION_NAMESPACE == 'remaining_round5_generation'
    assert round5.attempt_target is round5.original.attempt_target
    assert round5.original.CLASSES == (1, 2, 9, 10, 15)
    assert round5.HISTORICAL_NAMESPACES[-1] == round5.previous_generation.GENERATION_NAMESPACE
    assert round5.PARENT_PINS['manifest.json'] == '1cf30d3628f69adbc573260ec66c335fd174ffdb89550b6772f8bb2d274b005a'
    assert round5.REQUEST_PINS['verification.json'] == '4730c01bc4fd16dbe0f4095336ab8edd0606aed8e021ce7c6a1bedb41f37ee65'


def test_empty_parent_candidate_set_is_genuinely_empty_and_not_reauthorized():
    instruction = round5.user_instruction([proposal('task')], [])
    assert instruction['statement_zh'] == '完成复核和修正，继续'
    assert instruction['actual_parent_new_candidate_count'] == 0
    assert instruction['observed_parent_candidate_keys'] == []
    assert instruction['actual_current_request_count'] == 1
    assert not instruction['current_original_rectangle_no_change_authorized']
    assert not instruction['creates_human_event'] and not instruction['authorizes_propagation']
    status, audit = round5.saved_status([], {}, {}, 'snapshot')
    assert status['parent_new_machine_candidates'] == status['actually_saved'] == 0 and audit == []


def test_two_independent_task_packs_and_later_canonical_save_resolve_per_event(task):
    assert len(task['registry']) == 2
    assert set(task['registry']) == {(13, task['refs']['old']['proposal_sha256'], 'old'),
        (14, task['refs']['saved']['proposal_sha256'], 'saved')}
    assert 'saved' not in task['publications'][14]['proposals']
    with database(task['events']) as db:
        changes = db.total_changes
        reviews, events, records, templates, audits = audit(task, db)
        assert db.total_changes == changes
    assert len(reviews) == len(records) == 3 and len(events) == len(audits) == 4
    assert set(templates) == {'normal'}
    assert Counter(a['proposal_registry'] for a in audits) == {'canonical_publication': 2, 'independent_preannotation': 2}
    old = [a for a in audits if a['target_key'] == 'old']
    assert [a['proposal_registry'] for a in old] == ['independent_preannotation', 'canonical_publication']
    assert [a['preannotation_namespace'] for a in old] == ['v1', None]
    assert round5.indexed(records)['old']['proposal_registry'] == 'canonical_publication'
    assert all(r['current_payload_raw'] == r['human_event_payload_raw'] for r in records)


@pytest.mark.parametrize('attack', ['publication', 'base_hash', 'binding', 'target', 'raw_current', 'missing_latest',
    'duplicate', 'historical_draft_hash', 'historical_task_manifest', 'historical_task_namespace', 'historical_gt',
    'historical_pose', 'historical_author', 'historical_polygon', 'new_task_fake_canonical', 'wrong_source', 'source_binding'])
def test_all_raw_historical_events_and_current_pairs_fail_closed(task, attack):
    events = copy.deepcopy(task['events'])
    value = events[1]  # old v1 event followed by a valid canonical pub14 current
    if attack == 'publication': value['proposal_publication'] = 14
    elif attack == 'base_hash': value['base_proposal_id'] = round5.sha(task['publications'][14]['proposals']['old'])
    elif attack == 'binding': value['binding'] = 'wrong'
    elif attack == 'target': value['target_key'] = 'saved'
    elif attack == 'duplicate': events.insert(2, copy.deepcopy(value))
    elif attack == 'historical_draft_hash': value['preannotation_provenance']['proposal_sha256'] = 'wrong'
    elif attack == 'historical_task_manifest': value['preannotation_provenance']['worklist_manifest_sha256'] = 'wrong'
    elif attack == 'historical_task_namespace': value['preannotation_provenance'] = events[3]['preannotation_provenance']
    elif attack == 'historical_gt': value['ground_truth_eligible'] = True
    elif attack == 'historical_pose': value['pose'] = {}
    elif attack == 'historical_author': value['preannotation_provenance']['assistant_draft']['author_role'] = 'human'
    elif attack == 'historical_polygon': value['proposal_polygon'] = EDIT
    elif attack == 'new_task_fake_canonical': events[3]['base_proposal_id'] = 'claimed-canonical-pub14'
    elif attack == 'wrong_source': value['source']['split'] = 'test'
    elif attack == 'source_binding': value['source_binding'] = 'wrong'
    with database(events) as db:
        if attack == 'raw_current':
            db.execute('UPDATE reviews SET payload=payload||? WHERE target_key=?', (' ', 'saved'))
        elif attack == 'missing_latest':
            db.execute('DELETE FROM events WHERE target_key=? AND revision=2', ('old',))
        with pytest.raises(ValueError):
            audit(task, db)


@pytest.mark.parametrize('attack', ['parent_manifest', 'parent_proposals', 'parent_seal', 'manifest_hash', 'seal_not_passed',
    'seal_request_count', 'independent_seal', 'image', 'draft_human', 'pose_dependency', 'pose_history_only', 'version'])
def test_complete_sealed_task_and_original_pose_dependency_required(task, attack):
    directory, publication = task['directory'], task['publications'][14]
    manifest = round5.read_json(directory/'manifest.json')
    seal = round5.read_json(directory/'verification.json')
    current, history_keys, version = {}, set(), 14
    if attack.startswith('parent_'):
        field = {'parent_manifest': 'parent_manifest_sha256', 'parent_proposals': 'parent_proposals_sha256',
            'parent_seal': 'parent_verification_sha256'}[attack]
        manifest[field] = 'wrong'
        round5.write_json(directory/'manifest.json', manifest)
    elif attack == 'manifest_hash': seal['manifest_sha256'] = 'wrong'
    elif attack == 'seal_not_passed': seal['state'] = 'pending'
    elif attack == 'seal_request_count': seal['request_count'] = 2
    elif attack == 'independent_seal': (directory/'independent_verification.json').write_text('{}')
    elif attack == 'image': (directory/'images/saved.png').write_bytes(b'changed')
    elif attack == 'draft_human':
        draft = read_one(directory/'proposals.jsonl'); draft['human_edited'] = True
        round5.write_jsonl(directory/'proposals.jsonl', [draft])
    elif attack == 'pose_dependency': current['saved'] = dict(revision=1, polygon=EDIT)
    elif attack == 'pose_history_only': history_keys.add('saved')
    elif attack == 'version': version = 13
    round5.write_json(directory/'verification.json', seal)
    if attack != 'independent_seal': round5.write_json(directory/'independent_verification.json', seal)
    with pytest.raises(ValueError):
        saved.prelabel_registry(directory, task['rows'], 'formal', publication, current, history_keys, version, 'v2')


def read_one(path):
    return round5.read_jsonl(path)[0]


def test_registry_duplicates_and_task_scope_cannot_count_old_tasks(task):
    with pytest.raises(ValueError): saved.combine_registries(task['registry'], task['registry'])
    assert set(saved.task_references(task['registry'], 'v2')) == {'saved'}
    with database(task['events']) as db:
        reviews, _, records, _, _ = audit(task, db)
    proposals = manual(task, reviews, records)
    assert [p['target_key'] for p in proposals] == ['saved']
    p = proposals[0]
    proof = p['human_source']['gallery_review']
    assert p['schema'] == saved.SCHEMA and p['origin'] == 'mask_gallery_human_revision'
    assert p['polygon'] == EDIT and p['polygon_changed_from_assistant_draft']
    assert p['human_source']['target_key'] == p['target_key']
    assert proof['proposal_publication'] == 14 and proof['task_manifest_sha256'] == task['refs']['saved']['task_manifest_sha256']
    assert proof['base_proposal_id'] == task['refs']['saved']['proposal_sha256']
    assert p['rendering_id'] == 'remaining_round5_generation:manual_source:saved'
    assert p['manual_four_point_source'] and not p['propagation_seed_eligible']
    assert p['target_expected_revision'] == 0 and p['target_snapshot_payload_sha256'] is None
    assert all(p[f] is False for f in saved.FALSE_FLAGS)
    assert all(f not in p for f in ('template', 'pose_review', 'human_polygon_revision', 'original_pose_url'))


@pytest.mark.parametrize('attack', ['locked_key', 'locked_frame', 'reserved_frame', 'original_rectangle', 'vertices', 'raw_pair'])
def test_manual_sources_reject_protected_or_non_actual_contours(task, attack):
    with database(task['events']) as db:
        reviews, _, records, _, _ = audit(task, db)
    previous, protected = list(task['previous']), []
    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: round5.indexed(records)['saved']['human_event_payload_raw'] += ' '
    with pytest.raises(ValueError):
        manual(task, reviews, records, previous=previous, prohibited=protected)


def test_latest_actual_contour_renders_native_image_mask_and_explicit_gallery_schema(task, tmp_path):
    with database(task['events']) as db:
        reviews, _, records, _, _ = audit(task, db)
    proposals = manual(task, reviews, records)
    class Evidence:
        def image(self, frame): return np.zeros((16, 24), np.uint8)
    for name in ('cases', 'images', 'labelme', 'masks'): (tmp_path/name).mkdir()
    saved.package_manual_preview(tmp_path, proposals, Evidence())
    label = round5.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 round5.digest(tmp_path/'images/saved.png') == proposals[0]['human_source']['image_sha256']
    assert np.array_equal(np.asarray(Image.open(tmp_path/'masks/saved.png')) > 0, raster_mask(EDIT, 24, 16))


def test_historical_task_scope_preserves_old_rejections_but_not_new_unissued_v3(tmp_path, monkeypatch):
    monkeypatch.setattr(round5, 'PROJECT', tmp_path)
    parent = tmp_path/'outputs/parent'; parent.mkdir(parents=True)
    old = tmp_path/'outputs/old'; old.mkdir()
    round5.write_jsonl(old/'requests.jsonl', [dict(target_key='old')])
    round5.write_json(parent/'historical_task_input_hashes.json', {'outputs/old/requests.jsonl': round5.digest(old/'requests.jsonl')})
    tasks = {}
    rows = {k: row(k) for k in ('old', 'v1', 'v2', 'rejected-v1', 'rejected-v2', 'unissued-v3')}
    for ns in ('v1', 'v2'):
        directory = tmp_path/'outputs'/ns; (directory/'internal').mkdir(parents=True); tasks[ns] = directory
        round5.write_jsonl(directory/'requests.jsonl', [dict(target_key=ns)])
        round5.write_jsonl(directory/'internal/shortlist.jsonl', [dict(target_key='rejected-'+ns)])
        for name in ('deferred_sources', 'build_decisions', 'assistant_decisions'):
            round5.write_json(directory/'internal'/f'{name}.json', {})
    staged = tmp_path/'outputs/pallet_mask_preannotated_requests_v3'; staged.mkdir()
    round5.write_jsonl(staged/'requests.jsonl', [dict(target_key='unissued-v3')])
    keys, hashes = round5.historical_task_inventory(rows, parent, tasks)
    assert keys == set(rows)-{'unissued-v3'} and len(hashes) == 11
    assert not any('v3' in n for n in hashes)
    (old/'requests.jsonl').write_text('changed')
    with pytest.raises(ValueError): round5.historical_task_inventory(rows, parent, tasks)


def test_all_whole_frame_histories_pending_boxes_and_tasks_protected_and_full_classes_skip():
    reasons = ('returned', 'deleted', 'deferred', 'confirmed', 'gallery', 'quarantine', 'task', 'pending')
    rows = {r['target_key']: r for r in [row(k, 19) for k in reasons] +
        [row('cross-'+k, 19, 'frame-'+k) for k in reasons] + [row('active', 19)]}
    work, outcomes = round5.target_inventory(rows, [], dict.fromkeys(rows, 'eligible'),
        {'returned', 'deleted', 'deferred', 'confirmed', 'pending'}, {'gallery'}, {'quarantine'}, {'frame-task', 'frame-pending'})
    assert [k for k, _ in work] == ['active']
    assert {o['target_key'] for o in outcomes} == set(rows)-{'active'}
    full = (1, 2, 3, 6, 8, 9, 10, 13, 15)
    locked = [proposal(f'full{c}-{i}', c) for c in full for i in range(100)]
    rows = {f'target{c}': row(f'target{c}', c) for c in full}
    work, outcomes = round5.target_inventory(rows, locked, dict.fromkeys(rows, 'eligible'), set(), set(), set())
    assert not work and len(outcomes) == len(full)
    assert next(o for o in outcomes if o['class_id'] == 8)['reason'] == 'locked_class_quota_full'


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


def test_no_quad_seeds_and_new_namespace_only():
    gallery = {'seed': dict(row=row('seed'), polygon=POLYGON, origin=round5.original.GALLERY_ORIGIN)}
    templates = round5.generation_templates({}, set(), gallery, 'formal', 'classes')
    assert templates['seed']['rendering_id'] == 'remaining_round5_generation:seed'
    gallery['seed']['polygon'] = QUAD
    with pytest.raises(ValueError): round5.generation_templates({}, set(), gallery, 'formal', 'classes')


def test_preserves_complete_parent_and_two_separate_task_namespaces(tmp_path):
    parent, out = tmp_path/'parent', tmp_path/'out'
    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 round5.HISTORICAL_NAMESPACES:
        (parent/namespace/'templates').mkdir(parents=True)
        (parent/namespace/'templates/source.json').write_bytes(namespace.encode())
    for name in ('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'):
        (parent/name).write_bytes((name+' 中文\n').encode())
    tasks = {ns: tmp_path/ns for ns in ('v1', 'v2')}
    for ns, directory in tasks.items():
        (directory/'internal').mkdir(parents=True); (directory/'internal/private.json').write_bytes(ns.encode())
    before = round5.file_inventory(parent)
    hashes = round5.preserve_assets(parent, out, [dict(target_key='old')], tasks)
    assert before == round5.file_inventory(parent)
    assert all(round5.digest(out/name) == h for name, h in hashes.items())
    assert (out/'preannotation_source_evidence/v1/internal/private.json').read_bytes() == b'v1'
    assert (out/'preannotation_source_evidence/v2/internal/private.json').read_bytes() == b'v2'
    assert (out/'all_manual_sources.jsonl').read_bytes() == (parent/'all_manual_sources.jsonl').read_bytes()


def test_report_uses_real_zero_parent_tasks_dynamic_capacity_and_saved_count(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 round5.ALL_CLASSES}
    counts[19]['capacity_matching_distinct_frames'] = 57
    status = dict(parent_new_machine_candidates=0)
    tasks = dict(actually_saved=35, polygon_changed_from_proposal=35, saved_unchanged=0)
    round5.build_report(tmp_path, [], counts, set(), set(), status, tasks, {}, 1550, 12)
    text = (tmp_path/'report_zh.html').read_text()
    assert '第14版真实新增机器候选 0 份' in text and '35份相对助手草稿改变、0份保存保持草稿' in text
    assert '35份新人工来源为图册保存，不是位姿保存' in text
    assert '原图容量 57' in text and '新增不同原图 43' in text
    assert 'id="only-new" checked' in text
    assert all(f'<option value="{c}">{c}</option>' in text for c in round5.ALL_CLASSES)
    assert round5.read_json(tmp_path/'font_coverage.json')['all_report_Chinese_present']


@pytest.mark.parametrize('attack', ['class', 'split', 'policy', 'viewpoint', 'vertices', 'boundary'])
def test_frozen_transfer_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=round5.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):
        round5.proposal_from_attempt('target', target, accepted, {'seed': template}, {}, 'pose', 'formal', 'classes')


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


@pytest.mark.parametrize('attack', [None, 'old_raw_prefix', 'outside_scope', 'current_changed_outside_scope'])
def test_delta_records_every_actual_extra_event_and_checks_whole_raw_prefix(tmp_path, attack):
    before, after = tmp_path/'before.sqlite3', tmp_path/'after.sqlite3'
    def create(path, events):
        db = sqlite3.connect(path)
        db.executescript('CREATE TABLE reviews(target_key TEXT PRIMARY KEY,revision INTEGER,payload TEXT);'
            'CREATE TABLE events(id INTEGER PRIMARY KEY,target_key TEXT,revision INTEGER,payload TEXT);')
        for key, revision, raw in events:
            db.execute('INSERT INTO events(target_key,revision,payload) VALUES (?,?,?)', (key, revision, raw))
            db.execute('INSERT OR REPLACE INTO reviews VALUES (?,?,?)', (key, revision, raw))
        db.commit(); db.close()
    old = [('old', 1, '{"old":1}')]
    create(before, old)
    create(after, old+[('task', 1, '{"task":1}'), ('task', 2, '{"task":2}')])
    if attack:
        with sqlite3.connect(after) as db:
            if attack == 'old_raw_prefix': db.execute('UPDATE events SET payload=payload||? WHERE id=1', (' ',))
            elif attack == 'outside_scope': db.execute('INSERT INTO events(target_key,revision,payload) VALUES (?,?,?)', ('other', 1, '{}'))
            else: db.execute('UPDATE reviews SET payload=? WHERE target_key=?', ('changed', 'old'))
        with pytest.raises(ValueError): round5.validate_source_delta(before, after, 'reviews', {'task'})
    else:
        delta = round5.validate_source_delta(before, after, 'reviews', {'task'})
        assert delta['new_events'] == 2 and delta['current_changed_keys'] == ['task']
        assert delta['new_event_counts_by_target'] == {'task': 2}
        assert [r['revision'] for r in delta['new_event_raw_records']] == [1, 2]
        assert delta['new_event_target_keys'] == ['task'] and delta['raw_historical_prefix_bytewise_preserved']
