"""Synthetic publication-6 contracts; never invoke production generation."""
import copy
import json
import sqlite3

import numpy as np
import pytest
from PIL import Image

from pallet import mask_quota_completion as quota
from pallet.mask_template_transfer import annotation_inventory, rectangle


POLYGON = [[1, 1], [20, 1], [20, 10], [15, 10], [15, 5], [5, 5], [5, 10], [1, 10]]


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


@pytest.fixture
def gallery_fixture(tmp_path):
    paths = {v: tmp_path/str(v) for v in (3, 4, 5)}
    rows, previous, reviews = {}, [], {}
    classes = [c for c, count in ((1, 48), (2, 5), (9, 38), (10, 10), (15, 39)) for _ in range(count)]
    for i, cls in enumerate(classes):
        key = f'{i:024x}'
        rows[key] = r = row(key, cls)
        p = dict(target_key=key, source=r, class_id=cls, formal_manifest_sha256='formal')
        previous.append(p)
        if i < 97:
            identity = {k: r[k] for k in ('target_key', 'frame_id', 'split', 'box_index', 'bbox', 'size', 'source_pcd_sha256')}
            reviews[key] = dict(target_key=key, source=identity, revision=7,
                polygon=copy.deepcopy(POLYGON), vertex_count=8, human_edited=True,
                event_kind='human_mask_gallery_revision', base_proposal_id=quota.sha(p),
                proposal_publication=3 if i < 56 else 4)
    for version, path in paths.items():
        (path/'images').mkdir(parents=True)
        proposals = previous[:{3: 56, 4: 97, 5: 140}[version]]
        for p in proposals:
            (path/'images'/f'{p["target_key"]}.png').write_bytes(b'synthetic-image')
        quota.write_jsonl(path/'proposals.jsonl', proposals)
        proposals_sha = quota.digest(path/'proposals.jsonl')
        quota.write_json(path/'manifest.json', dict(publication_version=version,
            formal_manifest_sha256='formal', proposals_sha256=proposals_sha))
        quota.write_json(path/'verification.json', dict(state='passed', proposals_sha256=proposals_sha))
        for key, review in reviews.items():
            if review['proposal_publication'] == version:
                review['source'].update(formal_manifest_sha256='formal',
                    image_sha256=quota.digest(path/'images'/f'{key}.png'))
                review['source_binding'] = quota.sha(review['source'])
                review['binding'] = quota.sha(dict(formal='formal', proposals=proposals_sha,
                    editor_version=quota.EDITOR_VERSION))
    return paths, rows, previous, reviews


def gallery_templates(fixture, events=None, current=None):
    paths, rows, previous, reviews = fixture
    return quota.gallery_templates(previous, reviews,
        list(reviews.values()) if events is None else events,
        current or {}, rows, paths[5], 'formal', 'gallery-snapshot', paths)


def pose_seed(key='original'):
    return dict(row=row(key), polygon=copy.deepcopy(POLYGON), revision=9,
        human_polygon_revision=3, current_payload_sha256='current',
        human_event_sha256='human-event', human_mask_confirmed=False)


def test_140_parent_accepts_97_saved_humans_without_seeding_pending(gallery_fixture):
    _, rows, previous, reviews = gallery_fixture
    first = next(iter(reviews))
    current = {first: dict(revision=19, polygon=POLYGON)}
    gallery = gallery_templates(gallery_fixture, current=current)
    assert len(gallery) == 97
    assert gallery[first]['revision'] == 19
    assert gallery[first]['human_polygon_revision'] == 7
    assert gallery[first]['current_payload_sha256'] == quota.sha(current[first])
    union = quota.seed_union({'original': pose_seed(), first: pose_seed(first)}, gallery, 'pose-snapshot')
    assert len(union) == 98 and union[first] is gallery[first]
    assert union['original']['origin'] == quota.POSE_ORIGIN
    assert union['original']['pose_review']['snapshot_sha256'] == 'pose-snapshot'
    assert not (set(rows)-set(reviews)) & set(union)
    counts = quota.quota_counts(previous, [], reviews)
    assert sum(c['old_total'] for c in counts.values()) == 140
    assert sum(c['saved_human'] for c in counts.values()) == 97
    assert sum(c['prior_machine_pending'] for c in counts.values()) == 43
    assert [counts[c]['missing'] for c in quota.CLASSES] == [2, 45, 12, 40, 11]


def test_latest_v5_review_can_join_old_v3_v4_reviews(gallery_fixture):
    paths, _, previous, reviews = gallery_fixture
    p = previous[-1]; key = p['target_key']
    review = copy.deepcopy(next(iter(reviews.values())))
    review.update(target_key=key, proposal_publication=5, base_proposal_id=quota.sha(p))
    review['source'] = {k: p['source'][k] for k in ('target_key', 'frame_id', 'split', 'box_index', 'bbox', 'size', 'source_pcd_sha256')}
    review['source'].update(formal_manifest_sha256='formal', image_sha256=quota.digest(paths[5]/'images'/f'{key}.png'))
    review['source_binding'] = quota.sha(review['source'])
    review['binding'] = quota.sha(dict(formal='formal', proposals=quota.digest(paths[5]/'proposals.jsonl'), editor_version=quota.EDITOR_VERSION))
    reviews[key] = review
    assert len(gallery_templates(gallery_fixture)) == 98


@pytest.mark.parametrize('attack', ['binding', 'source_binding', 'base_proposal_id',
    'publication', 'source', 'not_human', 'gt', 'vertices', 'newer_event', 'duplicate_event',
    'parent_proposal', 'historical_image', 'historical_manifest'])
def test_gallery_rejects_invalid_provenance(gallery_fixture, attack):
    paths, _, previous, reviews = gallery_fixture
    key = next(iter(reviews)); review = reviews[key]
    events = copy.deepcopy(list(reviews.values()))
    if attack in ('binding', 'source_binding', 'base_proposal_id'):
        review[attack] = 'wrong'
    elif attack == 'publication':
        review['proposal_publication'] = 999
    elif attack == 'source':
        review['source']['frame_id'] = 'wrong'
    elif attack == 'not_human':
        review['human_edited'] = False
    elif attack == 'gt':
        review['ground_truth_eligible'] = True
    elif attack == 'vertices':
        review['vertex_count'] = 9
    elif attack == 'newer_event':
        events.append(dict(review, revision=8))
    elif attack == 'duplicate_event':
        events.append(copy.deepcopy(review))
    elif attack == 'parent_proposal':
        previous[0]['extra'] = 'changed'
    elif attack == 'historical_image':
        (paths[3]/'images'/f'{key}.png').write_bytes(b'changed')
    else:
        manifest = json.loads((paths[3]/'manifest.json').read_text())
        quota.write_json(paths[3]/'manifest.json', dict(manifest, proposals_sha256='wrong'))
    if attack not in ('newer_event', 'duplicate_event'):
        events = copy.deepcopy(list(reviews.values()))
    with pytest.raises(ValueError):
        gallery_templates(gallery_fixture, events)


def test_saved_rectangle_is_not_seed_and_missing_current_never_resurrected(gallery_fixture):
    _, rows, _, reviews = gallery_fixture
    first, second = list(reviews)[:2]
    reviews[first].update(polygon=rectangle(rows[first]), vertex_count=4)
    events = copy.deepcopy(list(reviews.values()))
    del reviews[second]
    templates = gallery_templates(gallery_fixture, events)
    assert len(templates) == 95 and first not in templates and second not in templates
    gallery_keys = set(reviews) | {v['target_key'] for v in events}
    work, _ = quota.target_inventory(rows, [], dict.fromkeys(rows, 'eligible'), gallery_keys, set())
    assert not {first, second} & {key for key, _ in work}


@pytest.mark.parametrize('state', ['deleted', 'deferred'])
def test_pose_deleted_or_deferred_excludes_saved_gallery_seed(gallery_fixture, state):
    _, rows, _, reviews = gallery_fixture
    key = next(iter(reviews))
    current = {key: dict(target_key=key, revision=19, polygon=POLYGON, state=state)}
    before = copy.deepcopy((current, reviews))
    gallery = gallery_templates(gallery_fixture, current=current)
    assert key not in gallery and len(gallery) == 96
    assert key not in quota.seed_union({}, gallery, 'pose-snapshot')
    assert (current, reviews) == before
    work, _ = quota.target_inventory(rows, [], dict.fromkeys(rows, 'eligible'), set(reviews), set())
    assert key not in {k for k, _ in work}


def test_inventory_union_protects_restored_masks_and_excludes_machine_seeds():
    keys = ('restored', 'human', 'deleted', 'deferred', 'confirmed', 'machine', 'pose_only', 'fresh', 'quarantine', 'gallery_history', 'published')
    rows = {key: row(key) for key in keys}
    rect = rectangle(rows['human']); changed = copy.deepcopy(rect); changed[0][0] += 1
    seq = dict(restored=[dict(polygon=changed), dict(polygon=rect)],
        human=[dict(polygon=POLYGON), dict(polygon=POLYGON, event_kind='unit_normalization')],
        deleted=[dict(polygon=POLYGON, state='deleted')],
        deferred=[dict(polygon=POLYGON, state='deferred')],
        confirmed=[dict(polygon=rect, human_pose_confirmed=True)],
        machine=[dict(polygon=POLYGON, event_kind='mask_template_proposal')],
        pose_only=[dict(polygon=rect)])
    with sqlite3.connect(':memory:') as db:
        db.executescript('CREATE TABLE events(id INTEGER PRIMARY KEY,target_key TEXT,revision INTEGER,payload TEXT);'
            'CREATE TABLE annotations(target_key TEXT,revision INTEGER,payload TEXT);')
        for key, values in seq.items():
            for rev, value in enumerate(values, 1):
                raw = json.dumps(dict(dict(state='draft', target_key=key, revision=rev), **value))
                db.execute('INSERT INTO events(target_key,revision,payload) VALUES (?,?,?)', (key, rev, raw))
            db.execute('INSERT INTO annotations VALUES (?,?,?)', (key, rev, raw))
        _, pose_templates, status = annotation_inventory(db, rows)
    union = quota.seed_union(pose_templates, {}, 'snapshot')
    assert set(union) == {'human'}
    assert union['human']['human_polygon_revision'] == 1 and union['human']['revision'] == 2
    work, outcomes = quota.target_inventory(rows, [dict(target_key='published')], status,
        {'gallery_history'}, {'quarantine'})
    assert {k for k, _ in work} == {'fresh', 'pose_only'}
    assert len(work)+len(outcomes) == len(rows)
    assert not quota.seed_union(pose_templates, {}, 'snapshot', {'human'})


def test_machine_origin_cannot_be_renamed_as_human_seed():
    with pytest.raises(ValueError, match='direct original'):
        quota.seed_union({'bad': dict(pose_seed('bad'), origin='machine')}, {}, 'snapshot')


@pytest.mark.parametrize('change', ['final_class_id', 'split', 'policy_id', 'viewpoint_candidate',
    'frame_id', 'vertex_count', 'boundary_guard'])
def test_proposal_contract_rejects_invalid_transfer(change):
    templates = quota.seed_union({'original': pose_seed()}, {}, 'snapshot')
    target = row('target')
    accepted = dict(template_key='original', polygon=copy.deepcopy(POLYGON),
        template_rank=1, metrics=dict(boundary_guard=dict(state='passed')))
    if change == 'vertex_count':
        accepted['polygon'].pop()
    elif change == 'boundary_guard':
        accepted['metrics']['boundary_guard']['state'] = 'failed'
    else:
        target[change] = {'final_class_id': 2, 'split': 'test', 'policy_id': 'other',
            'viewpoint_candidate': 'side', 'frame_id': 'frame-original'}[change]
    with pytest.raises(ValueError):
        quota.proposal_from_attempt('target', target, accepted, templates, {}, 'snapshot', 'formal', 'classes')


def test_original_pose_provenance_does_not_confirm_new_draft():
    templates = quota.seed_union({'original': dict(pose_seed(), human_mask_confirmed=True)}, {}, 'snapshot')
    accepted = dict(template_key='original', polygon=POLYGON, template_rank=2,
        metrics=dict(boundary_guard=dict(state='passed')))
    p = quota.proposal_from_attempt('target', row('target'), accepted, templates,
        {}, 'snapshot', 'formal', 'classes')
    assert not any(p[flag] for flag in quota.FALSE_FLAGS)
    assert p['template']['template_human_confirmed'] is True
    assert p['template']['origin'] == quota.POSE_ORIGIN
    assert p['generation_method']['name'] == 'original'
    assert p['template']['pose_review']['human_event_sha256'] == 'human-event'
    assert p['status'] == 'machine_draft_pending_visual_review'


def test_quota_selection_preserves_parent_and_caps_distinct_frames(gallery_fixture):
    _, _, previous, reviews = gallery_fixture
    before = copy.deepcopy(previous)
    candidates = [dict(target_key=f'new-{i}', class_id=1, source=row(f'new-{i}'),
        metrics=dict(boundary_ncc=.9)) for i in range(4)]
    candidates[0]['source']['frame_id'] = previous[0]['source']['frame_id']
    new, dispositions = quota.select_diverse(previous, candidates)
    counts = quota.quota_counts(previous, new, reviews)
    assert previous == before and len(new) == 2
    assert counts[1]['old_total'] == 48 and counts[1]['total'] == 50 and counts[1]['missing'] == 0
    assert dispositions['new-0'] == 'accepted_duplicate_frame_not_selected'
    assert 'accepted_quota_full_not_selected' in dispositions.values()


def test_preserve_all_three_namespaces_and_latest_rendering(tmp_path):
    parent, out = tmp_path/'parent', tmp_path/'out'
    for root in (parent, out):
        for folder in ('cases', 'images', 'masks', 'labelme', 'templates'):
            (root/folder).mkdir(parents=True)
    for folder, ext in (('cases', 'png'), ('images', 'png'), ('masks', 'png'), ('labelme', 'json')):
        (parent/folder/f'old.{ext}').write_bytes(b'old-canonical-asset')
    for namespace in ('refined', 'generation'):
        (parent/namespace/'templates').mkdir(parents=True)
        (parent/namespace/'templates/shared.json').write_bytes(namespace.encode())
    (parent/'templates/shared.json').write_bytes(b'original')
    (out/'templates/shared.json').write_bytes(b'latest')
    hashes = quota.preserve_parent_assets(parent, out, [dict(target_key='old')])
    assert all(quota.digest(out/name) == value for name, value in hashes.items())
    assert (out/'quota_generation/templates/shared.json').read_bytes() == b'latest'
    for namespace in ('refined', 'generation'):
        assert (out/namespace/'templates/shared.json').read_bytes() == namespace.encode()
    historical = [dict(row=dict(target_key='shared'), rendering_id=ns+':shared')
        for ns in ('historical', 'refined', 'generation')]
    parent_inventory = dict(templates=historical, rendering_by_target={'old': 'generation:shared'})
    templates = {'shared': dict(pose_seed('shared'), origin=quota.POSE_ORIGIN)}
    combined = [dict(target_key=k, template=dict(target_key='shared')) for k in ('old', 'new')]
    inventory = quota.rendering_inventory(parent_inventory, templates, combined, {'new'})
    assert inventory['templates'][:3] == historical
    assert inventory['rendering_by_target'] == {'old': 'generation:shared', 'new': 'quota_generation:shared'}


def test_report_distinguishes_pending_from_saved_and_new(gallery_fixture, tmp_path):
    from fontTools.ttLib import TTFont

    _, _, previous, reviews = gallery_fixture
    new = dict(target_key='new', class_id=2, source=row('new', 2))
    counts = quota.quota_counts(previous, [new], reviews)
    quota.build_report(tmp_path, previous+[new], {'new'}, counts, reviews)
    page = (tmp_path/'report_zh.html').read_text()
    assert '【历史机器候选】待人工复核' in page
    assert '【已保存人工修订 r7】' in page
    assert '【本轮新增】机器草稿 · 待人工复核' in page
    assert '历史候选共 140 份' in page
    assert '已保存人工修订 97 份' in page and '机器候选待复核 43 份' in page
    assert '本轮新增机器候选 1 份' in page
    assert '<th>历史总数</th>' in page and '<th>缺额</th>' in page
    assert '<html lang="zh-CN">' in page
    assert 'id="only-new" checked>只看本轮新增' in page
    assert 'id="filter"' in page and 'filter();' in page
    assert "url('report-font.otf?revision=6')" in page
    required = {ord(c) for c in page if '\u3400' <= c <= '\u9fff'}
    with TTFont(tmp_path/'report-font.otf') as font:
        assert required <= set(font.getBestCmap())
    coverage = json.loads((tmp_path/'font_coverage.json').read_text())
    assert coverage['all_report_Chinese_present'] is True
    assert coverage['chinese_glyphs'] == len(required)
    assert coverage['font_sha256'] == quota.digest(tmp_path/'report-font.otf')


def test_snapshot_is_readonly_backed_up_and_leaves_live_bytes(tmp_path):
    live, frozen = tmp_path/'live.sqlite3', tmp_path/'frozen.sqlite3'
    with sqlite3.connect(live) as db:
        db.executescript('CREATE TABLE events(id INTEGER PRIMARY KEY,target_key TEXT,revision INTEGER,payload TEXT);'
            'INSERT INTO events VALUES (1,"human",1,"saved-human-payload");')
    before = live.read_bytes()
    digest = quota.snapshot_database(live, frozen)
    assert live.read_bytes() == before
    assert frozen.stat().st_mode & 0o777 == 0o400
    assert quota.digest(tmp_path/'backups/frozen.sqlite3') == digest
    with quota.readonly(frozen, True) as db:
        with pytest.raises(sqlite3.OperationalError, match='readonly'):
            db.execute('DELETE FROM events')
    quota.verify_history_preserved(live, frozen)


def test_unimplemented_method_fails_before_any_file_access(tmp_path):
    with pytest.raises(ValueError, match='Multiscale integration deferred'):
        quota.generate(tmp_path/'not-created', method='multiscale')
    assert not (tmp_path/'not-created').exists()


def manual_fixture(classes=(1,)):
    requests, current, seeds, rows = [], {}, {}, {}
    for i, cls in enumerate(classes):
        key = f'manual-{i}'
        rows[key] = r = row(key, cls)
        current[key] = dict(target_key=key, revision=9, state='draft', polygon=copy.deepcopy(POLYGON),
            **dict.fromkeys(quota.FALSE_FLAGS, False))
        seeds[key] = dict(pose_seed(key), row=r, current_payload_sha256=quota.sha(current[key]))
        requests.append(dict(target_key=key, class_id=cls,
            source=dict(r, formal_manifest_sha256='formal'),
            pose_annotation_url='https://pose.example/?target='+key))
    return requests, current, seeds, rows


def build_manual(fixture, previous=(), quarantine=()):
    requests, current, seeds, rows = fixture
    return quota.manual_source_proposals(requests, seeds, current, rows, previous,
        'pose-snapshot', 'formal', 'classes', quarantine)


def test_24_saved_manual_frames_count_toward_quota_but_other_seeds_do_not(gallery_fixture):
    _, _, previous, reviews = gallery_fixture
    fixture = manual_fixture([c for c, n in ((1, 2), (2, 8), (9, 3), (10, 8), (15, 3)) for _ in range(n)])
    _, _, seeds, _ = fixture
    seeds['extra-human-seed-not-requested'] = pose_seed('extra-human-seed-not-requested')
    before = copy.deepcopy(fixture)
    manual = build_manual(fixture, previous)
    counts = quota.quota_counts(previous, [], reviews, manual=manual)
    assert fixture == before
    assert len(manual) == 24
    assert sum(c['total'] for c in counts.values()) == 164
    assert sum(c['saved_human'] for c in counts.values()) == 121
    assert sum(c['saved_gallery_human'] for c in counts.values()) == 97
    assert sum(c['saved_pose_human'] for c in counts.values()) == 24
    assert sum(c['prior_machine_pending'] for c in counts.values()) == 43
    assert {cls: c['missing'] for cls, c in counts.items()} == {1: 0, 2: 37, 9: 9, 10: 32, 15: 8}
    for p in manual:
        key = p['target_key']; value = fixture[1][key]
        assert p['schema'] == 'saved_pose_mask_gallery_entry_v1'
        assert p['origin'] == quota.POSE_ORIGIN
        assert p['source_label_kind'] == 'human_mask_source_manual_template_draft'
        assert p['status'] == 'human_edited_draft_pending_confirmation'
        assert p['human_edited'] and p['pose_snapshot_saved']
        assert not p['pose_store_written'] and not p['gallery_store_written']
        assert 'production_saved' not in p
        assert p['metrics'] == {} and 'generation_method' not in p
        assert p['flags'][0] == 'manual_source_not_machine_transfer'
        assert not any(p[flag] for flag in quota.FALSE_FLAGS)
        assert not p['template']['template_human_confirmed']
        assert p['template']['target_key'] == key
        assert p['rendering_id'] == 'quota_generation:'+key
        assert p['polygon'] == value['polygon']
        assert p['target_snapshot_payload_sha256'] == quota.sha(value)
        assert p['target_expected_revision'] == value['revision']


@pytest.mark.parametrize('attack', ['duplicate_request', 'duplicate_frame', 'prior_frame', 'prior_key',
    'quarantine', 'class', 'source', 'formal', 'missing_current', 'missing_seed', 'rectangle',
    'deleted', 'deferred', 'confirmed', 'payload', 'revision', 'polygon', 'machine_origin'])
def test_saved_manual_rejects_invalid_or_unfinished_sources(attack):
    fixture = manual_fixture((1, 1)); requests, current, seeds, rows = fixture
    key = requests[0]['target_key']; previous, quarantine = [], set()
    if attack == 'duplicate_request':
        requests.append(copy.deepcopy(requests[0]))
    elif attack == 'duplicate_frame':
        other = requests[1]['target_key']
        rows[other]['frame_id'] = rows[key]['frame_id']
        requests[1]['source']['frame_id'] = rows[key]['frame_id']
    elif attack in ('prior_frame', 'prior_key'):
        previous = [dict(target_key=key if attack == 'prior_key' else 'old',
            class_id=1, source=rows[key] if attack == 'prior_frame' else row('old'))]
    elif attack == 'quarantine':
        quarantine.add(key)
    elif attack == 'class':
        requests[0]['class_id'] = 2
    elif attack in ('source', 'formal'):
        requests[0]['source']['frame_id' if attack == 'source' else 'formal_manifest_sha256'] = 'wrong'
    elif attack == 'missing_current':
        del current[key]
    elif attack == 'missing_seed':
        del seeds[key]
    elif attack == 'rectangle':
        current[key]['polygon'] = rectangle(rows[key])
    elif attack in ('deleted', 'deferred'):
        current[key]['state'] = attack
    elif attack == 'confirmed':
        current[key]['human_mask_confirmed'] = True
        seeds[key]['current_payload_sha256'] = quota.sha(current[key])
    elif attack == 'payload':
        seeds[key]['current_payload_sha256'] = 'wrong'
    elif attack == 'revision':
        seeds[key]['revision'] += 1
    elif attack == 'polygon':
        seeds[key]['polygon'][0][0] += .1
    else:
        seeds[key]['origin'] = 'machine'
    with pytest.raises(ValueError):
        build_manual(fixture, previous, quarantine)


def test_saved_manual_precedes_machine_quota_selection_and_protects_targets(gallery_fixture):
    _, _, previous, reviews = gallery_fixture
    fixture = manual_fixture((1, 1))
    manual = build_manual(fixture, previous)
    candidate = dict(target_key='machine', class_id=1, source=row('machine'), metrics=dict(boundary_ncc=.99))
    new, dispositions = quota.select_diverse(previous+manual, [candidate])
    assert not new and dispositions == {'machine': 'accepted_quota_full_not_selected'}
    counts = quota.quota_counts(previous, new, reviews, manual=manual)
    assert counts[1]['manual_added'] == 2 and counts[1]['new_candidates'] == 0
    keys = {p['target_key'] for p in manual}
    work, outcomes = quota.target_inventory(fixture[3], previous,
        dict.fromkeys(keys, 'human_mask_history_protected'), set(), set(), keys)
    assert not work and {v['reason'] for v in outcomes} == {'saved_manual_source_counted'}


def test_quotas_reject_cross_class_duplicate_frames():
    old = dict(target_key='old', class_id=1, source=row('old'))
    duplicate = dict(target_key='new', class_id=2, source=dict(row('new', 2), frame_id=old['source']['frame_id']))
    with pytest.raises(ValueError, match='repeats a target or frame'):
        quota.quota_counts([old], [], {}, manual=[duplicate])


def test_freeze_manual_sources_preserves_exact_event_bytes_without_writes():
    fixture = manual_fixture()
    requests, current, seeds, _ = fixture
    key = requests[0]['target_key']
    event = dict(current[key], revision=3)
    event_raw = json.dumps(event, indent=2)  # raw event hash is intentionally non-canonical
    seeds[key]['human_event_sha256'] = quota.hashlib.sha256(event_raw.encode()).hexdigest()
    raw = json.dumps(current[key], indent=1)
    manual = build_manual(fixture)
    with sqlite3.connect(':memory:') as db:
        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);')
        db.execute('INSERT INTO annotations VALUES (?,?,?)', (key, 9, raw))
        db.execute('INSERT INTO events VALUES (1,?,?,?)', (key, 3, event_raw))
        changes = db.total_changes
        frozen = quota.freeze_manual_sources(db, manual)
        assert db.total_changes == changes
        assert frozen[0]['current_payload_raw'] == raw
        assert frozen[0]['human_event_payload_raw'] == event_raw
        assert frozen[0]['human_event_sha256'] != quota.sha(event)
        assert frozen[0]['human_event_payload']['polygon'] == manual[0]['polygon']
        db.execute('UPDATE events SET payload=?', (json.dumps(event),))
        with pytest.raises(ValueError, match='frozen payload/event mismatch'):
            quota.freeze_manual_sources(db, manual)


def test_manual_rendering_and_report_are_not_machine_comparisons(gallery_fixture, tmp_path):
    _, _, previous, reviews = gallery_fixture
    manual = build_manual(manual_fixture((2,)), previous)
    keys = {p['target_key'] for p in manual}
    evidence = type('Evidence', (), {'image': lambda self, frame: np.full((16, 24), 100, np.uint8)})()
    for folder in ('cases', 'images', 'masks', 'labelme'):
        (tmp_path/folder).mkdir()
    quota.package_manual_preview(tmp_path, manual, evidence)
    p = manual[0]; key = p['target_key']
    exported = json.loads((tmp_path/'labelme'/f'{key}.json').read_text())
    assert exported['flags']['human_edited'] and not exported['flags']['machine_draft']
    assert exported['flags']['pose_snapshot_saved']
    assert not exported['flags']['independent_gallery_saved']
    assert exported['mask_template_provenance']['metrics'] == {}
    assert exported['shapes'][0]['points'] == POLYGON
    with Image.open(tmp_path/'images'/f'{key}.png') as image:
        assert image.size == (24, 16)
    counts = quota.quota_counts(previous, [], reviews, manual=manual)
    quota.build_report(tmp_path, previous+manual, set(), counts, reviews, keys)
    page = (tmp_path/'report_zh.html').read_text()
    assert '【本轮计入人工描绘 r9】原位姿已保存 · 未确认真值' in page
    assert '并未导入独立图册人工保存历史；不是机器迁移' in page
    assert 'data-kind="manual"' in page
    assert '本轮计入已保存人工描绘 1 份' in page
    assert '<th>新增已保存人工</th><th>新增机器候选</th>' in page
    assert p['original_pose_url'] in page


def test_manual_rendering_inventory_maps_to_own_latest_template():
    fixture = manual_fixture((2,))
    manual = build_manual(fixture)
    templates = quota.seed_union(fixture[2], {}, 'pose-snapshot')
    inventory = quota.rendering_inventory(dict(templates=[], rendering_by_target={}),
        templates, manual, set(), {p['target_key'] for p in manual})
    key = manual[0]['target_key']
    assert inventory['rendering_by_target'] == {key: 'quota_generation:'+key}
    assert inventory['templates'][0]['polygon'] == manual[0]['polygon']
