"""Publication13 contracts. Fixtures never write production stores."""
import copy
import hashlib
import json
import sqlite3
from collections import Counter

import numpy as np
import pytest
from PIL import Image

from pallet import mask_remaining_round3 as round3
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]]
POLYGON = [[1, 1], [20, 1], [20, 10], [15, 10], [15, 5], [5, 5], [5, 10], [1, 10]]


def row(key, 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 database(path=':memory:'):
    db = sqlite3.connect(path)
    db.executescript('CREATE TABLE annotations(target_key TEXT,revision INTEGER,payload TEXT);'
        'CREATE TABLE events(id INTEGER PRIMARY KEY,target_key TEXT,revision INTEGER,payload TEXT);')
    return db


def payload(r, polygon=None, revision=2):
    return dict(target_key=r['target_key'], revision=revision, state='draft', source=copy.deepcopy(r),
        binding='binding', polygon=copy.deepcopy(rectangle(r) if polygon is None else polygon),
        reviewer='real reviewer 检验', pose=dict(robot_command_eligible=False), **dict.fromkeys(round3.FALSE_FLAGS, False))


def insert(db, value, raw=None):
    raw = json.dumps(value, indent=2, ensure_ascii=False) if raw is None else raw
    db.execute('INSERT INTO annotations VALUES (?,?,?)', (value['target_key'], value['revision'], raw))
    db.execute('INSERT INTO events(target_key,revision,payload) VALUES (?,?,?)',
        (value['target_key'], value['revision'], raw))
    return raw


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


def request(r):
    return dict(target_key=r['target_key'], class_id=r['final_class_id'], existing_pose_revision=0,
        source=dict(r, formal_manifest_sha256='formal'), pose_annotation_url='https://example.invalid/'+r['target_key'])


def test_constants_parent_pins_original_engine_and_no_monkeypatch():
    old = round3.previous_generation
    assert round3.PUBLICATION_VERSION == 13 and old.PUBLICATION_VERSION == 12
    assert round3.OUTPUT.name == 'pallet_mask_remaining_round3_v1'
    assert round3.PARENT == old.OUTPUT
    assert round3.REQUESTS.name == 'pallet_mask_remaining_round2_requests_v1'
    assert round3.GENERATION_NAMESPACE == 'remaining_round3_generation'
    assert round3.attempt_target is round3.original.attempt_target
    assert round3.original.CLASSES == (1, 2, 9, 10, 15)
    assert len(round3.HISTORICAL_NAMESPACES) == 11
    assert round3.HISTORICAL_NAMESPACES[-1] == old.GENERATION_NAMESPACE
    assert old.USER_STATEMENT != round3.USER_STATEMENT
    assert old.ORIGINAL_REVIEWS.keys().isdisjoint(round3.PENDING_ORIGINAL_RECTANGLES)
    assert round3.PARENT_PINS['manifest.json'] == 'c76c845420a35b69ed860e8efed3d15b9dc3083629013c3a5dd5ab6b3b2d747e'
    assert round3.PARENT_PINS['verification.json'] == '724cd94da93f9c3ff5a103ca8becf014a9b90857b4f8efda0b3cce318c820a65'


def test_instruction_does_not_invent_explicit_no_change_review_scope():
    instruction = round3.user_instruction([request(row('new'))], [proposal('candidate')])
    assert instruction['statement_zh'] == round3.USER_STATEMENT
    assert instruction['actual_parent_new_candidate_count'] == instruction['actual_current_request_count'] == 1
    assert instruction['mentioned_candidate_count'] == 185 and instruction['mentioned_manual_count'] == 54
    assert instruction['mentioned_batches_already_accounted_in_parent_publication'] == 12
    assert not instruction['current_original_rectangle_no_change_authorized']
    assert instruction['future_new_manual_tasks_require_assistant_preannotation']
    assert instruction['historical_original_rectangle_statement_bindings_unchanged']
    assert 'scoped_request_keys' not in instruction and 'reviewed_original_rectangle_keys' not in instruction
    assert not instruction['creates_human_event'] and not instruction['authorizes_propagation']


def test_pending_original_box_preserves_raw_utf8_and_is_not_a_review_or_source():
    r = row('box'); value = payload(r)
    with database() as db:
        raw = insert(db, value); before = db.total_changes
        record = round3.pending_original_rectangle_save(db, 'box', r, 'snapshot', 'binding', request(r))
        assert db.total_changes == before
        with pytest.raises(ValueError):
            round3.remaining.validated_manual_source(db, 'box', r, 'snapshot', 'binding')
    assert record['current_payload_raw'] == record['saved_event_payload_raw'] == raw
    assert record['current_payload_raw_sha256'] == hashlib.sha256(raw.encode('utf-8')).hexdigest()
    assert record['saved_event_raw_sha256'] == hashlib.sha256(raw.encode('utf-8')).hexdigest()
    assert not record['human_edited'] and not record['propagation_seed_eligible']
    assert record['pending_excluded_from_coverage'] and record['source_frame_reserved']
    assert record['pending_specific_original_rectangle_review'] and not record['counts_toward_published_coverage']
    assert not any(record[f] for f in round3.FALSE_FLAGS)
    for forbidden in ('user_statement_sha256', 'user_reviewed_no_change', 'human_polygon_revision',
            'human_event_id', 'original_rectangle_review_only'):
        assert forbidden not in record


@pytest.mark.parametrize('attack', ['target', 'revision', 'binding', 'split', 'bbox', 'frame', 'policy',
    'class', 'viewpoint', 'changed_quad', 'deleted', 'deferred', 'confirmed', 'gt', 'train', 'robot',
    'nested_robot', 'auto', 'machine', 'origin', 'absent_event', 'different_raw', 'newer_event',
    'older_modified', 'older_confirmed', 'older_machine', 'duplicate_current', 'duplicate_event', 'stale_request'])
def test_pending_box_rejects_modified_unsafe_ambiguous_or_stale_evidence(attack):
    r = row('box'); value = payload(r); req = request(r)
    if attack in ('target', 'revision', 'binding'):
        value[{'target': 'target_key', 'revision': 'revision', 'binding': 'binding'}[attack]] = 'wrong'
    elif attack in ('split', 'bbox', 'frame', 'policy', 'class', 'viewpoint'):
        f = {'frame': 'frame_id', 'policy': 'policy_id', 'class': 'final_class_id', 'viewpoint': 'viewpoint_candidate'}.get(attack, attack)
        value['source'][f] = 'wrong'
    elif attack == 'changed_quad':
        value['polygon'] = QUAD
    elif attack in ('deleted', 'deferred', 'confirmed'):
        value['state'] = attack
    elif attack in ('gt', 'train', 'robot'):
        value[{'gt': 'ground_truth_eligible', 'train': 'automatic_training_eligible', 'robot': 'robot_command_eligible'}[attack]] = True
    elif attack == 'nested_robot':
        value['pose']['robot_command_eligible'] = True
    elif attack == 'auto':
        value['event_kind'] = next(iter(round3.AUTO_EVENTS))
    elif attack == 'machine':
        value['machine_draft'] = True
    elif attack == 'origin':
        value['origin'] = 'unknown_machine'
    elif attack == 'stale_request':
        req['existing_pose_revision'] = 2
    with database() as db:
        if attack.startswith('older_'):
            old = payload(r, revision=1)
            if attack == 'older_modified':
                old['polygon'] = QUAD
            elif attack == 'older_confirmed':
                old['ground_truth_eligible'] = True
            else:
                old['machine_transfer_performed'] = True
            db.execute('INSERT INTO events(target_key,revision,payload) VALUES (?,?,?)', ('box', 1, json.dumps(old)))
        raw = json.dumps(value, indent=2)
        db.execute('INSERT INTO annotations VALUES (?,?,?)', ('box', 2, raw))
        if attack != 'absent_event':
            db.execute('INSERT INTO events(target_key,revision,payload) VALUES (?,?,?)',
                ('box', 2, json.dumps(value) if attack == 'different_raw' else raw))
        if attack in ('duplicate_event', 'newer_event'):
            db.execute('INSERT INTO events(target_key,revision,payload) VALUES (?,?,?)',
                ('box', 2 if attack == 'duplicate_event' else 3, raw))
        if attack == 'duplicate_current':
            db.execute('INSERT INTO annotations VALUES (?,?,?)', ('box', 2, raw))
        with pytest.raises(ValueError):
            round3.pending_original_rectangle_save(db, 'box', r, 'snapshot', 'binding', req)


def test_completed_quad_counts_but_pending_original_box_never_joins_canonical(tmp_path):
    rs = {r['target_key']: r for r in (row('quad', 5), row('original', 4))}
    with database() as db:
        for key, polygon in (('quad', QUAD), ('original', None)):
            insert(db, payload(rs[key], polygon))
        candidates = {'quad': round3.remaining.validated_manual_source(db, 'quad', rs['quad'], 'snapshot', 'binding')}
        pending = {'original': round3.pending_original_rectangle_save(db, 'original', rs['original'], 'snapshot', 'binding', request(rs['original']))}
        before = db.total_changes
        manual = round3.completed_manual_proposals([request(r) for r in rs.values()], candidates, pending, rs,
            [], 'snapshot', 'formal', 'classification')
        assert db.total_changes == before
    assert len(manual) == 1 and manual[0]['target_key'] == 'quad'
    assert manual[0]['manual_four_point_source'] and not manual[0]['propagation_seed_eligible']
    assert manual[0]['rendering_id'] == 'remaining_round3_generation:manual_source:quad'
    assert manual[0]['human_edited'] and not manual[0]['machine_draft']
    assert round3.generation_templates(candidates, {'quad'}, {}, 'formal', 'classification') == {}
    inventory = round3.rendering_inventory(dict(templates=[], rendering_by_target={}), {}, manual, manual, set())
    assert len(inventory['manual_source_renderings']) == 1 and not inventory['templates']
    assert inventory['publication_version'] == 13
    class Evidence:
        def image(self, frame):
            return np.zeros((16, 24), np.uint8)
    for d in ('cases', 'images', 'masks', 'labelme'):
        (tmp_path/d).mkdir()
    round3.package_manual_preview(tmp_path, manual, Evidence())
    label = round3.read_json(tmp_path/'labelme/quad.json')
    assert label['flags']['human_edited'] and not label['flags']['ground_truth_eligible']
    assert label['shapes'][0]['points'] == QUAD
    assert not (tmp_path/'labelme/original.json').exists()
    assert np.array_equal(np.asarray(Image.open(tmp_path/'masks/quad.png')) > 0,
        raster_mask(QUAD, *rs['quad']['size']))


@pytest.mark.parametrize('attack', ['locked_frame', 'locked_key', 'quarantine', 'gallery', 'class', 'split', 'formal', 'missing', 'stale_revision', 'pending_overlap'])
def test_completed_sources_fail_closed(attack):
    r = row('manual')
    with database() as db:
        insert(db, payload(r, QUAD))
        candidates = {'manual': round3.remaining.validated_manual_source(db, 'manual', r, 'snapshot', 'binding')}
    req = request(r); previous = []; quarantine = []; gallery = []; pending = {}
    if attack == 'locked_frame':
        previous = [proposal('locked', 22, r['frame_id'])]
    elif attack == 'locked_key':
        previous = [proposal('manual')]
    elif attack == 'quarantine':
        quarantine = ['manual']
    elif attack == 'gallery':
        gallery = ['manual']
    elif attack in ('class', 'split', 'formal'):
        if attack == 'class':
            req['class_id'] = 1
        else:
            req['source']['split' if attack == 'split' else 'formal_manifest_sha256'] = 'wrong'
    elif attack == 'stale_revision':
        req['existing_pose_revision'] = 2
    elif attack == 'pending_overlap':
        pending['manual'] = {}
    else:
        candidates = {}
    with pytest.raises(ValueError):
        round3.completed_manual_proposals([req], candidates, pending, {'manual': r}, previous,
            'snapshot', 'formal', 'classification', quarantine, gallery)


def test_generation_templates_exclude_old_five_gallery_and_quads_but_allow_saved_unchanged():
    gallery = {k: dict(row=row(k, c), polygon=POLYGON, origin=round3.original.GALLERY_ORIGIN,
        saved_review_unchanged=True, new_human_edit_created=False) for k, c in (('old5', 1), ('saved', 3))}
    templates = round3.generation_templates({}, set(), gallery, 'formal', 'classification')
    assert set(templates) == {'saved'} and templates['saved']['saved_review_unchanged']
    assert not templates['saved']['new_human_edit_created']
    assert templates['saved']['rendering_id'] == 'remaining_round3_generation:saved'
    gallery['saved']['polygon'] = QUAD
    with pytest.raises(ValueError):
        round3.generation_templates({}, set(), gallery, 'formal', 'classification')


def test_eight_full_classes_skip_and_pending_frames_reserved_across_other_targets():
    filled = (1, 2, 3, 6, 9, 10, 13, 15)
    locked = [proposal(f'full{c}-{i}', c) for c in filled for i in range(100)]
    rs = [row(f'c{c}', c) for c in filled]+[row('active', 8), row('reserved', 4),
        row('cross_pending', 19, 'frame-reserved'), row('cross_locked', 19, locked[0]['source']['frame_id'])]
    rows = {r['target_key']: r for r in rs}
    work, outcomes = round3.target_inventory(rows, locked, dict.fromkeys(rows, 'eligible'), set(), set(), set(), {'frame-reserved'})
    assert [k for k, _ in work] == ['active']
    reasons = {v['target_key']: v['reason'] for v in outcomes}
    assert reasons['c3'] == reasons['c6'] == reasons['c13'] == 'locked_class_quota_full'
    assert reasons['cross_locked'] == 'locked_counted_frame'
    assert reasons['cross_pending'] == reasons['reserved'] == 'pending_original_rectangle_frame_reserved'


def test_capacity_is_recomputed_not_hardcoded_and_pending_not_a_counted_slot():
    locked = [proposal('already', 19)]
    rows = {r['target_key']: r for r in (row('next', 19), row('reserved', 19), row('another', 20))}
    work, _ = round3.target_inventory(rows, locked, dict.fromkeys(rows, 'eligible'), set(), set(), set(), {'frame-reserved'})
    candidates = [dict(target_key=k, class_id=r['final_class_id'], source=r, metrics={}) for k, r in work]
    selected, _, _, _ = round3.expand.select_locked_diverse(locked, candidates)
    assert Counter(p['class_id'] for p in locked+selected)[19] == 2
    assert not any(p['target_key'] == 'reserved' for p in selected)


def test_pose_complete_history_audit_preserves_returned_rectangles_and_deleted(tmp_path):
    r = row('restored')
    with database() as db:
        old = payload(r, QUAD, revision=1)
        db.execute('INSERT INTO events(target_key,revision,payload) VALUES (?,?,?)', ('restored', 1, json.dumps(old)))
        insert(db, payload(r))
        current, audit = round3.audit_pose_snapshot(db, {'restored': r}, 'binding')
        protected = round3.expand.protected_history(db, {'restored': r}, current)
    assert audit[0]['returned_to_original_rectangle'] and audit[0]['historical_modified_polygon']
    assert protected == {'restored'}


@pytest.mark.parametrize('attack', ['source', 'binding', 'relational', 'duplicate'])
def test_pose_history_audit_rejects_all_event_identity_corruption(attack):
    r = row('key')
    with database() as db:
        insert(db, payload(r, QUAD))
        if attack == 'duplicate':
            db.execute('INSERT INTO events(target_key,revision,payload) SELECT target_key,revision,payload FROM events')
        else:
            bad = payload(r, QUAD)
            if attack == 'source':
                bad['source']['split'] = 'test'
            elif attack == 'binding':
                bad['binding'] = 'wrong'
            else:
                bad['target_key'] = 'wrong'
            db.execute('UPDATE events SET payload=?', (json.dumps(bad),))
        with pytest.raises(ValueError):
            round3.audit_pose_snapshot(db, {'key': r}, 'binding')


def test_historical_statement_groups_keep_distinct_old_scopes_and_raw_source_bytes(tmp_path):
    (tmp_path/'parent_evidence').mkdir()
    old = dict(statement_zh='old review exact', scoped_request_keys=['old'], reviewed_original_rectangle_keys=['old'])
    newer = dict(statement_zh='newer review exact', scoped_request_keys=['newer'], reviewed_original_rectangle_keys=['newer'])
    round3.write_json(tmp_path/'parent_evidence/review_completion_statement.json', old)
    round3.write_json(tmp_path/'review_completion_statement.json', newer)
    round3.write_json(tmp_path/'review_statement_bindings.json', dict(
        historical=dict(path='parent_evidence/review_completion_statement.json', statement_sha256=round3.sha(old), target_keys=['old']),
        current=dict(path='review_completion_statement.json', statement_sha256=round3.sha(newer), target_keys=['newer'])))
    records = [dict(target_key=k, user_statement_sha256=round3.sha(s)) for k, s in [('old', old), ('newer', newer)]]
    result = round3.historical_review_bindings(tmp_path, records)
    assert result[0]['path'] == 'parent_evidence/review_completion_statement.json'
    assert result[1]['path'] == 'parent_evidence/parent_evidence/review_completion_statement.json'
    assert {g['statement_sha256'] for g in result} == {round3.sha(old), round3.sha(newer)}
    records[0]['user_statement_sha256'] = round3.sha(round3.user_instruction([], []))
    with pytest.raises(ValueError):
        round3.historical_review_bindings(tmp_path, records)


@pytest.fixture
def saved_gallery(tmp_path):
    directory = tmp_path/'publication12'; (directory/'images').mkdir(parents=True)
    r = row('saved', 3)
    p = dict(target_key='saved', class_id=3, source=r, formal_manifest_sha256='formal', polygon=POLYGON)
    round3.write_jsonl(directory/'proposals.jsonl', [p])
    proposals_sha = round3.digest(directory/'proposals.jsonl')
    round3.write_json(directory/'manifest.json', dict(publication_version=12,
        formal_manifest_sha256='formal', proposals_sha256=proposals_sha))
    round3.write_json(directory/'verification.json', dict(state='passed', proposals_sha256=proposals_sha))
    (directory/'images/saved.png').write_bytes(b'original-native-image')
    source = {f: r[f] for f in ('target_key', 'frame_id', 'split', 'box_index', 'bbox', 'size', 'source_pcd_sha256')}
    source.update(formal_manifest_sha256='formal', image_sha256=round3.digest(directory/'images/saved.png'))
    value = dict(target_key='saved', revision=2, source=source, source_binding=round3.sha(source),
        polygon=POLYGON, vertex_count=8, human_edited=True, event_kind='human_mask_gallery_revision',
        proposal_publication=12, base_proposal_id=round3.sha(p),
        binding=round3.sha(dict(formal='formal', proposals=proposals_sha, editor_version=round3.original.EDITOR_VERSION)))
    return directory, r, p, value


def gallery_database(value):
    db = database()
    db.execute('CREATE TABLE reviews(target_key TEXT,revision INTEGER,payload TEXT)')
    old = copy.deepcopy(value); old['revision'] = 1
    db.execute('INSERT INTO events(target_key,revision,payload) VALUES (?,?,?)', ('saved', 1, json.dumps(old)))
    raw = json.dumps(value, indent=2, ensure_ascii=False)
    db.execute('INSERT INTO events(target_key,revision,payload) VALUES (?,?,?)', ('saved', 2, raw))
    db.execute('INSERT INTO reviews VALUES (?,?,?)', ('saved', 2, raw))
    return db


def test_gallery_freezes_exact_current_latest_and_checks_all_older_event_bindings(saved_gallery):
    directory, r, p, value = saved_gallery
    with gallery_database(value) as db:
        before = db.total_changes
        reviews, events, sources, templates, audit = round3.gallery_source_records(db, {'saved': r}, [p],
            directory, 'formal', 'snapshot', {12: directory})
        assert db.total_changes == before
    assert len(reviews) == len(sources) == len(templates) == 1
    assert len(events) == len(audit) == 2
    assert sources[0]['current_payload_raw'] == sources[0]['human_event_payload_raw']
    assert audit[0]['historical_binding_validated'] and audit[1]['historical_binding_validated']
    assert templates['saved']['human_polygon_revision'] == 2


@pytest.mark.parametrize('attack', ['binding', 'source_binding', 'source', 'proposal', 'publication',
    'flags', 'kind', 'not_human', 'vertices', 'relational', 'current_raw', 'duplicate_event', 'historical_image'])
def test_all_gallery_historical_events_fail_closed_not_just_current(saved_gallery, attack):
    directory, r, p, value = saved_gallery
    with gallery_database(value) as db:
        old = copy.deepcopy(value); old['revision'] = 1
        if attack == 'binding':
            old['binding'] = 'wrong'
        elif attack == 'source_binding':
            old['source_binding'] = 'wrong'
        elif attack == 'source':
            old['source']['split'] = 'test'
        elif attack == 'proposal':
            old['base_proposal_id'] = 'wrong'
        elif attack == 'publication':
            old['proposal_publication'] = 11
        elif attack == 'flags':
            old['ground_truth_eligible'] = True
        elif attack == 'kind':
            old['event_kind'] = 'mask_template_proposal'
        elif attack == 'not_human':
            old['human_edited'] = False
        elif attack == 'vertices':
            old['vertex_count'] = 10
        elif attack == 'relational':
            old['target_key'] = 'wrong'
        elif attack == 'current_raw':
            db.execute('UPDATE reviews SET payload=?', (json.dumps(value),))
        elif attack == 'duplicate_event':
            db.execute('INSERT INTO events(target_key,revision,payload) SELECT target_key,revision,payload FROM events LIMIT 1')
        else:
            (directory/'images/saved.png').write_bytes(b'changed')
        db.execute('UPDATE events SET payload=? WHERE revision=1', (json.dumps(old),))
        with pytest.raises(ValueError):
            round3.gallery_source_records(db, {'saved': r}, [p], directory, 'formal', 'snapshot', {12: directory})


def test_preserve_all_parent_bytes_namespaces_and_private_chain_without_root_aliases(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(('old-'+directory).encode())
    for namespace in round3.HISTORICAL_NAMESPACES:
        (parent/namespace/'templates').mkdir(parents=True)
        (parent/namespace/'templates/shared.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'):
        (parent/name).write_bytes(('literal-'+name+' 中文\n').encode('utf-8'))
    (parent/'parent_evidence/deeper').mkdir(parents=True)
    (parent/'parent_evidence/deeper/private-only.jsonl').write_bytes(b'private exact source\n')
    before = round3.file_inventory(parent)
    copied = round3.preserve_assets(parent, out, [dict(target_key='old')])
    assert round3.file_inventory(parent) == before
    assert all(round3.digest(out/name) == value for name, value in copied.items())
    assert not (parent/'private-only.jsonl').exists()
    assert (out/'parent_evidence/parent_evidence/deeper/private-only.jsonl').read_bytes() == b'private exact source\n'
    assert (out/'reviewed_original_rectangle_source_records.jsonl').read_bytes() == (parent/'reviewed_original_rectangle_source_records.jsonl').read_bytes()
    assert (out/'review_completion_statement.json').read_bytes() == (parent/'review_completion_statement.json').read_bytes()


@pytest.mark.parametrize('attack', ['class', 'split', 'policy', 'viewpoint', 'vertices', 'boundary'])
def test_transfer_proposal_preserves_frozen_compatibility_topology_and_beam_gate(attack):
    source = row('seed', 3); target = row('target', 3)
    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=round3.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):
        round3.proposal_from_attempt('target', target, accepted, {'seed': template}, {}, 'snapshot', 'formal', 'classes')


def test_rendering_inventory_does_not_mutate_historical_namespaces():
    old = proposal('old'); old['rendering_id'] = 'old_generation:seed'
    parent = dict(templates=[dict(rendering_id=old['rendering_id'], polygon=POLYGON)],
        manual_source_renderings=[], rendering_by_target={'old': old['rendering_id']})
    before = canonical(parent)
    inv = round3.rendering_inventory(parent, {}, [], [old], set())
    assert canonical(parent) == before and inv['templates'] == parent['templates']
    assert inv['publication_version'] == 13 and inv['generation_template_namespace'] == round3.GENERATION_NAMESPACE


def test_chinese_report_all22_actual_counts_default_new_only_and_pending_exclusion(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 round3.ALL_CLASSES}
    counts[19]['capacity_matching_distinct_frames'] = 57
    round3.build_report(tmp_path, [], counts, set(), set(), set(), {}, set(),
        dict(unchanged_keys=[], polygon_changed_from_proposal=36, saved_unchanged=15), {})
    text = (tmp_path/'report_zh.html').read_text()
    assert 'id="only-new" checked' in text
    assert all(f'<option value="{c}">{c}</option>' in text for c in round3.ALL_CLASSES)
    assert round3.USER_STATEMENT in text
    assert '36份轮廓变化、15份保存后保持原候选' in text
    assert '本轮新增机器候选 0 份' in text and '至少还需新增不同原图 43' in text
    assert '旧五份原框复核继续绑定原来的两份声明' in text and '单列等待专项复核说明，不计覆盖' in text
    assert '1449个已计入帧全部锁定' in text and '2个待专项复核原图另行保留' in text
    assert 'max-width:1090px' in text and 'overflow-x:auto' in text
    assert round3.read_json(tmp_path/'font_coverage.json')['all_report_Chinese_present']


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