"""Publication-7 contracts; synthetic fixtures never change production stores."""
import copy
import hashlib
import json
import sqlite3

import pytest

from pallet import mask_quota_100 as quota
from pallet import mask_quota_completion as original
from pallet.mask_template_transfer import annotation_inventory


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


def row(key, cls=10):
    return dict(target_key=key, target_id='target-'+key, frame_id='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=10):
    return dict(target_key=key, class_id=cls, source=row(key, cls),
        polygon=copy.deepcopy(POLYGON), vertex_count=8,
        metrics=dict(boundary_ncc=.9, ecc=.95), template=dict(target_key='shared'))


def human_fixture(classes=(10,)):
    requests, current, templates, rows = [], {}, {}, {}
    for n, cls in enumerate(classes):
        key = f'manual-{n}'; rows[key] = r = row(key, cls)
        current[key] = dict(target_key=key, revision=9, state='draft', source=r,
            polygon=copy.deepcopy(POLYGON), **dict.fromkeys(quota.FALSE_FLAGS, False))
        templates[key] = dict(row=r, polygon=copy.deepcopy(POLYGON), revision=9,
            human_polygon_revision=3, current_payload_sha256=quota.sha(current[key]),
            human_event_sha256='human-event', human_mask_confirmed=False)
        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, templates, rows


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


def gallery_review(key, polygon=POLYGON, **kwargs):
    return dict(target_key=key, polygon=copy.deepcopy(polygon), revision=7,
        human_edited=True, event_kind='human_mask_gallery_revision', **kwargs)


def test_constants_do_not_mutate_frozen_engine_or_publications():
    before = dict(original.SOURCE_PUBLICATIONS)
    assert quota.PUBLICATION_VERSION == 7 and quota.TARGET_PER_CLASS == 100
    assert quota.GENERATION_NAMESPACE == 'quota100_generation'
    assert quota.VERSION == 'direct_human_union_quota100_v1'
    assert set(quota.SOURCE_PUBLICATIONS) == {3, 4, 5, 6}
    assert quota.SOURCE_PUBLICATIONS[6] == quota.PARENT
    assert original.SOURCE_PUBLICATIONS == before
    assert original.PUBLICATION_VERSION == 6 and original.GENERATION_NAMESPACE == 'quota_generation'


def test_manual_helper_counts_above_old_50_without_implicit_seed_quota():
    previous = [proposal(f'old-{i}') for i in range(50)]
    fixture = human_fixture((10,)*13)
    fixture[2]['seed-only'] = dict(copy.deepcopy(fixture[2]['manual-0']), row=row('seed-only'))
    before = copy.deepcopy(fixture)
    additions = manual(fixture, previous)
    assert fixture == before and len(additions) == 13
    counts = quota.quota_counts(previous, [], {}, fixture[1], fixture[2], manual=additions)
    assert counts[10]['old_total'] == 50 and counts[10]['total'] == 63
    assert counts[10]['manual_added'] == counts[10]['saved_pose_human'] == 13
    assert counts[10]['missing'] == 37 and counts[10]['goal'] == 100
    for p in additions:
        key = p['target_key']
        assert p['schema'] == original.MANUAL_SCHEMA and p['generation_schema'] == quota.VERSION
        assert p['manual_source_kind'] == 'completed_manual_request'
        assert p['rendering_id'] == 'quota100_generation:'+key
        assert p['origin'] == quota.POSE_ORIGIN and p['human_edited']
        assert p['metrics'] == {} and 'generation_method' not in p
        assert not p['machine_transfer_performed'] and not p['new_human_edit_created']
        assert not p['pose_store_written'] and not p['gallery_store_written']
        assert not any(p[flag] for flag in quota.FALSE_FLAGS)
        assert p['polygon'] == fixture[1][key]['polygon']
        assert p['target_snapshot_payload_sha256'] == quota.sha(fixture[1][key])


@pytest.mark.parametrize('attack', ['duplicate_request', 'duplicate_frame', 'prior_key', 'prior_frame',
    'quarantine', 'class', 'formal', 'source', 'missing_current', 'missing_seed', 'rectangle',
    'deleted', 'deferred', 'confirmed', 'training', 'robot', 'payload', 'revision', 'polygon', 'machine_origin'])
def test_manual_sources_reject_invalid_or_unfinished_work(attack):
    f = human_fixture((10, 10)); requests, current, templates, rows = f
    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_key', 'prior_frame'):
        previous = [dict(proposal(key if attack == 'prior_key' else 'old'),
            source=row('old') if attack == 'prior_key' else rows[key])]
    elif attack == 'quarantine':
        quarantine.add(key)
    elif attack == 'class':
        requests[0]['class_id'] = 2
    elif attack in ('formal', 'source'):
        requests[0]['source']['formal_manifest_sha256' if attack == 'formal' else 'frame_id'] = 'wrong'
    elif attack == 'missing_current':
        del current[key]
    elif attack == 'missing_seed':
        del templates[key]
    elif attack == 'rectangle':
        current[key]['polygon'] = POLYGON[:4]
    elif attack in ('deleted', 'deferred'):
        current[key]['state'] = attack
    elif attack in ('confirmed', 'training', 'robot'):
        current[key][{'confirmed': 'human_mask_confirmed', 'training': 'automatic_training_eligible',
            'robot': 'robot_command_eligible'}[attack]] = True
        templates[key]['current_payload_sha256'] = quota.sha(current[key])
    elif attack == 'payload':
        templates[key]['current_payload_sha256'] = 'wrong'
    elif attack == 'revision':
        templates[key]['revision'] += 1
    elif attack == 'polygon':
        templates[key]['polygon'][0][0] += .1
    else:
        templates[key]['origin'] = 'machine'
    with pytest.raises(ValueError):
        manual(f, previous, quarantine)


def test_latest_164_gallery_plus_30_existing_pose_plus_13_manual_is_207_human():
    previous = [proposal(f'old-{cls}-{n}', cls) for cls in quota.CLASSES
        for n in range(37 if cls == 10 else 50)]
    inherited = previous[:30]
    requests, current, templates, _ = f = human_fixture((10,)*13)
    for p in inherited:
        key = p['target_key']
        current[key] = dict(target_key=key, revision=9, state='draft', polygon=POLYGON)
        templates[key] = dict(copy.deepcopy(templates['manual-0']), row=p['source'],
            current_payload_sha256=quota.sha(current[key]))
    reviews = {p['target_key']: gallery_review(p['target_key']) for p in previous[30:194]}
    additions = manual(f, previous)
    counts = quota.quota_counts(previous, [], reviews, current, templates, inherited, additions)
    total = lambda k: sum(c[k] for c in counts.values())
    assert total('old_total') == 237 and total('manual_added') == 13
    assert total('saved_gallery_human') == 164 and total('existing_saved_pose_human') == 30
    assert total('saved_pose_human') == 43 and total('saved_human') == 207
    assert total('old_pending_machine') == 43 and total('new_candidates') == 0
    assert all(c['total'] == c['missing'] == 50 for c in counts.values())


@pytest.mark.parametrize('invalid', ['rectangle', 'deleted', 'deferred', 'not_human', 'missing_seed'])
def test_latest_saved_counts_never_use_stale_legacy_polygon(invalid):
    p = proposal('old'); old_manual = [p]
    current = {'old': dict(state='draft', polygon=copy.deepcopy(POLYGON), revision=10)}
    templates = {'old': dict(polygon=POLYGON)}
    reviews = {'old': gallery_review('old')}
    if invalid == 'rectangle':
        current['old']['polygon'] = POLYGON[:4]; reviews['old']['polygon'] = POLYGON[:4]
    elif invalid in ('deleted', 'deferred'):
        current['old']['state'] = invalid
    elif invalid == 'not_human':
        reviews['old']['human_edited'] = False; templates = {}
    else:
        templates = {}; reviews = {}
    c = quota.quota_counts([p], [], reviews, current, templates, old_manual)[10]
    assert c['saved_human'] == 0 and c['existing_saved_pose_human'] == 0
    assert c['old_pending_machine'] == 1 and c['old_total'] == 1


def test_human_counts_are_key_union_not_gallery_plus_pose_double_count():
    p = proposal('same')
    current = {'same': dict(state='draft', polygon=POLYGON)}
    c = quota.quota_counts([p], [], {'same': gallery_review('same')}, current,
        {'same': dict(polygon=POLYGON)}, [p])[10]
    assert c['saved_gallery_human'] == c['saved_pose_human'] == c['saved_human'] == 1
    assert c['old_pending_machine'] == 0


def test_distinct_frames_and_100_cap_apply_globally():
    previous = [proposal(f'old-{n}') for n in range(50)]
    candidates = [proposal(f'new-{n}') for n in range(70)]
    selected, dispositions = quota.select_diverse(previous, candidates, goal=quota.TARGET_PER_CLASS)
    c = quota.quota_counts(previous, selected, {}, {}, {})[10]
    assert len(selected) == 50 and c['total'] == 100 and c['missing'] == 0
    assert list(dispositions.values()).count('accepted_quota_full_not_selected') == 20
    with pytest.raises(ValueError, match='exceeds goal'):
        quota.quota_counts(previous, candidates, {}, {}, {})
    duplicate = dict(proposal('cross-class', 1), source=dict(row('cross-class', 1), frame_id='frame-old-0'))
    with pytest.raises(ValueError, match='repeats a target or frame'):
        quota.quota_counts(previous, [duplicate], {}, {}, {})


def test_machine_generation_wraps_frozen_original_contract_without_global_changes():
    f = human_fixture((10,)); templates = original.seed_union(f[2], {}, 'snapshot')
    accepted = dict(template_key='manual-0', polygon=POLYGON, template_rank=4,
        metrics=dict(boundary_guard=dict(state='passed')))
    before = copy.deepcopy((accepted, templates))
    p = quota.proposal_from_attempt('new', row('new'), accepted, templates, {}, 'snapshot', 'formal', 'classes')
    assert (accepted, templates) == before
    assert p['schema'] == quota.VERSION and p['continuation']['batch'] == 7
    assert p['continuation']['all_compatible_templates_considered']
    assert p['target_per_class'] == 100 and p['generation_method']['name'] == 'original'
    assert p['generation_method']['code_sha256'] == quota.digest(quota.PROJECT/'pallet/mask_template_continue.py')
    assert not any(p[flag] for flag in quota.FALSE_FLAGS)
    assert original.PUBLICATION_VERSION == 6
    accepted['metrics']['boundary_guard']['state'] = 'failed'
    with pytest.raises(ValueError):
        quota.proposal_from_attempt('new', row('new'), accepted, templates, {}, 'snapshot', 'formal', 'classes')


def test_all_four_historical_namespaces_and_old_assets_preserved(tmp_path):
    parent, out = tmp_path/'parent', tmp_path/'out'
    for root in (parent, out):
        for name in ('cases', 'images', 'masks', 'labelme', 'templates'):
            (root/name).mkdir(parents=True)
    for folder, extension in (('cases', 'png'), ('images', 'png'), ('masks', 'png'), ('labelme', 'json')):
        (parent/folder/f'old.{extension}').write_bytes(b'old-canonical-asset')
    (parent/'templates/shared.json').write_bytes(b'old-template')
    for namespace in ('refined', 'generation', 'quota_generation'):
        (parent/namespace/'templates').mkdir(parents=True)
        (parent/namespace/'templates/shared.json').write_bytes(namespace.encode())
    (out/'templates/shared.json').write_bytes(b'new-direct-human')
    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/'quota100_generation/templates/shared.json').read_bytes() == b'new-direct-human'
    assert (out/'templates/shared.json').read_bytes() == b'old-template'
    for namespace in ('refined', 'generation', 'quota_generation'):
        assert (out/namespace/'templates/shared.json').read_bytes() == namespace.encode()
    historical = [dict(rendering_id=ns+':shared') for ns in ('historical', 'refined', 'generation', 'quota_generation')]
    parent_inventory = dict(templates=historical, rendering_by_target={'old': 'quota_generation:shared'})
    templates = {'shared': dict(row=row('shared'), origin=quota.POSE_ORIGIN)}
    combined = [proposal(k) for k in ('old', 'new', 'manual')]
    inventory = quota.rendering_inventory(parent_inventory, templates, combined, {'new'}, {'manual'})
    assert inventory['templates'][:4] == historical
    assert inventory['rendering_by_target'] == dict(old='quota_generation:shared',
        new='quota100_generation:shared', manual='quota100_generation:shared')


def test_legacy_audit_tracks_latest_raw_sources_without_changing_old_proposal():
    f = human_fixture(); requests, current, templates, rows = f
    key = requests[0]['target_key']
    event = dict(current[key], revision=3)
    event_raw = json.dumps(event, indent=2)
    templates[key]['human_event_sha256'] = hashlib.sha256(event_raw.encode()).hexdigest()
    historical = manual(f)
    original_proposal = copy.deepcopy(historical)
    current[key]['revision'] = 11
    current[key]['event_kind'] = 'unit_normalization'
    templates[key]['revision'] = 11
    templates[key]['current_payload_sha256'] = quota.sha(current[key])
    raw = json.dumps(current[key], indent=1)
    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, 11, raw))
        db.execute('INSERT INTO events VALUES (1,?,?,?)', (key, 3, event_raw))
        changes = db.total_changes
        records, audit = quota.audit_inherited_manual(db, historical, templates, current, 'new-snapshot')
        assert db.total_changes == changes
        assert historical == original_proposal
        assert audit[0]['source_changed'] and not audit[0]['polygon_changed']
        assert audit[0]['historical_revision'] == 9 and audit[0]['current_revision'] == 11
        assert audit[0]['latest_active_direct_human']
        assert records[0]['current_payload_raw'] == raw
        assert records[0]['human_event_payload_raw'] == event_raw
        assert records[0]['human_event_sha256'] != quota.sha(event)
        assert records[0]['snapshot_sha256'] == 'new-snapshot'
        current[key]['state'] = 'deleted'
        db.execute('UPDATE annotations SET payload=?', (json.dumps(current[key]),))
        records, audit = quota.audit_inherited_manual(db, historical, {}, current, 'new-snapshot')
        assert not audit[0]['latest_active_direct_human']
        assert records[0]['schema'] == 'inactive_legacy_pose_mask_source_audit_v1'


def test_report_only_new_is_machine_sidecar_and_never_calls_old_67_new(tmp_path):
    from fontTools.ttLib import TTFont

    f = human_fixture(); added_manual = manual(f)
    previous = [proposal('old-reviewed', 2), proposal('old-pending', 1)]
    new = [proposal('machine', 10)]
    reviews = {'old-reviewed': gallery_review('old-reviewed')}
    counts = quota.quota_counts(previous, new, reviews, f[1], f[2], manual=added_manual)
    quota.build_report(tmp_path, previous+added_manual+new, {'machine'}, counts, reviews,
        f[1], manual=added_manual)
    page = (tmp_path/'report_zh.html').read_text()
    assert '<html lang="zh-CN">' in page
    assert 'id="only-new" checked>只看本轮新增机器候选' in page
    assert '本轮新增机器候选 1 份' in page and '本轮计入已保存人工描绘 1 份' in page
    assert page.count('data-batch="new"') == 1
    assert '【已保存图册人工修订 r7】历史候选对照，不是新候选' in page
    assert '【历史候选】待人工复核，未计为已保存人工轮廓' in page
    assert '【本轮计入人工描绘 r9】不是机器迁移，未确认真值' in page
    assert 'data-kind="manual" hidden' in page
    assert '未确认真值，不自动进入训练或机器人控制' in page
    assert '累计 4 个不同帧，距500帧仍缺 496 帧' 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())


def test_missing_parent_seal_or_non_original_method_never_creates_output(tmp_path):
    out = tmp_path/'out'
    with pytest.raises(ValueError, match='Only the frozen original'):
        quota.generate(out, method='multiscale')
    assert not out.exists()
    with pytest.raises(ValueError, match='Workers'):
        quota.generate(out, workers=0)
    assert not out.exists()


def test_new_pose_seed_only_is_protected_not_implicitly_counted():
    f = human_fixture(); additions = manual(f)
    extra = 'unrequested-new-human'
    rows = dict(f[3], **{extra: row(extra)})
    status = dict.fromkeys(rows, 'human_mask_history_protected')
    templates = dict(f[2], **{extra: dict(polygon=POLYGON)})
    counts = quota.quota_counts([], [], {}, f[1], templates, manual=additions)
    assert counts[10]['saved_human'] == 1 and counts[10]['total'] == 1
    work, outcomes = original.target_inventory(rows, [], status, set(), set(), {'manual-0'})
    assert not work
    assert {v['target_key']: v['reason'] for v in outcomes}[extra] == 'human_mask_history_protected'


def test_44_existing_humans_are_explicit_reuse_not_requests_or_new_edits():
    classes = (10,)*13+(1,)*5+(2,)*2+(9,)*8+(15,)*29
    requests, current, templates, rows = f = human_fixture(classes)
    f = (requests[:13], current, templates, rows)
    previous = [proposal(f'old-{cls}-{n}', cls) for cls in quota.CLASSES
        for n in range(37 if cls == 10 else 50)]
    requested = manual(f, previous)
    before = copy.deepcopy((requests, current, templates, rows, previous, requested))
    reused, inventory = quota.existing_human_reuse(templates, current, rows, previous,
        requested, 'pose-snapshot', 'formal', 'classes')
    assert (requests, current, templates, rows, previous, requested) == before
    assert len(reused) == 44 and len(requested) == 13
    assert all(v['reason'] == 'counted' for v in inventory)
    assert {c: sum(p['class_id'] == c for p in reused) for c in (1, 2, 9, 15)} == {1: 5, 2: 2, 9: 8, 15: 29}
    assert not {p['target_key'] for p in requested} & {p['target_key'] for p in reused}
    counts = quota.quota_counts(previous, [], {}, current, templates, manual=requested+reused)
    assert {c: v['total'] for c, v in counts.items()} == {1: 55, 2: 52, 9: 58, 10: 50, 15: 79}
    assert sum(c['total'] for c in counts.values()) == 294
    assert sum(c['manual_added'] for c in counts.values()) == 57
    assert sum(c['manual_requested'] for c in counts.values()) == 13
    assert sum(c['manual_existing_reused'] for c in counts.values()) == 44
    assert sum(c['newmanual'] for c in counts.values()) == 13
    for p in reused:
        assert p['manual_source_kind'] == 'existing_saved_human_reuse_for_100_goal'
        assert not p['new_human_edit_created'] and not p['machine_transfer_performed']
        assert p['metrics'] == {} and 'generation_method' not in p
        assert 'manual_request_sha256' not in p
        assert not any(p[flag] for flag in quota.FALSE_FLAGS)
        assert p['rendering_id'] == 'quota100_generation:'+p['target_key']
        assert p['original_pose_url'].endswith('target='+p['target_key'])


@pytest.mark.parametrize('invalid', ['quarantine', 'prior_frame', 'requested_frame', 'duplicate_reuse_frame',
    'source_identity', 'rectangle', 'deleted', 'deferred', 'payload', 'confirmed', 'training', 'robot'])
def test_reuse_reports_invalid_sources_without_forcing_expected_count(invalid):
    requests, current, templates, rows = human_fixture((10, 1, 1))
    requested = manual((requests[:1], current, templates, rows))
    key, other = 'manual-1', 'manual-2'
    previous, quarantine = [], set()
    if invalid == 'quarantine':
        quarantine.add(key)
    elif invalid == 'prior_frame':
        previous = [dict(proposal('old'), source=dict(row('old'), frame_id=rows[key]['frame_id']))]
    elif invalid == 'requested_frame':
        rows[key]['frame_id'] = requested[0]['source']['frame_id']
    elif invalid == 'duplicate_reuse_frame':
        rows[other]['frame_id'] = rows[key]['frame_id']
        current[other]['source']['frame_id'] = rows[key]['frame_id']
        templates[other]['current_payload_sha256'] = quota.sha(current[other])
    elif invalid == 'source_identity':
        current[key]['source'] = dict(current[key]['source'], split='test')
        templates[key]['current_payload_sha256'] = quota.sha(current[key])
    elif invalid == 'rectangle':
        current[key]['polygon'] = POLYGON[:4]
    elif invalid in ('deleted', 'deferred'):
        current[key]['state'] = invalid
    elif invalid == 'payload':
        templates[key]['current_payload_sha256'] = 'wrong'
    else:
        current[key][{'confirmed': 'human_mask_confirmed', 'training': 'automatic_training_eligible',
            'robot': 'robot_command_eligible'}[invalid]] = True
        templates[key]['current_payload_sha256'] = quota.sha(current[key])
    reused, inventory = quota.existing_human_reuse(templates, current, rows, previous,
        requested, 'snapshot', 'formal', 'classes', quarantine)
    assert len(reused) == 1 and len(inventory) == 2
    assert sum(v['reason'] != 'counted' for v in inventory) == 1


def test_all_57_added_manual_sources_freeze_exact_raw_current_and_events():
    f = human_fixture((10,)*13+(1,)*5+(2,)*2+(9,)*8+(15,)*29)
    requests, current, templates, rows = f
    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);')
        raw_sources = {}
        for n, key in enumerate(current, 1):
            raw = json.dumps(current[key], indent=1)
            event_raw = json.dumps(dict(current[key], revision=3), indent=2)
            templates[key]['human_event_sha256'] = hashlib.sha256(event_raw.encode()).hexdigest()
            db.execute('INSERT INTO annotations VALUES (?,?,?)', (key, 9, raw))
            db.execute('INSERT INTO events VALUES (?,?,?,?)', (n, key, 3, event_raw))
            raw_sources[key] = raw, event_raw
        requested = manual((requests[:13], current, templates, rows))
        reused, _ = quota.existing_human_reuse(templates, current, rows, [], requested,
            'pose-snapshot', 'formal', 'classes')
        changes = db.total_changes
        records = original.freeze_manual_sources(db, requested+reused)
        assert db.total_changes == changes and len(records) == 57
        for record in records:
            raw, event_raw = raw_sources[record['target_key']]
            assert record['current_payload_raw'] == raw and record['human_event_payload_raw'] == event_raw
            assert record['human_event_sha256'] == hashlib.sha256(event_raw.encode()).hexdigest()


def test_report_distinguishes_existing_reuse_from_completed_requests(tmp_path):
    requests, current, templates, rows = human_fixture((10, 15))
    requested = manual((requests[:1], current, templates, rows))
    reused, _ = quota.existing_human_reuse(templates, current, rows, [], requested,
        'pose-snapshot', 'formal', 'classes')
    additions = requested+reused
    counts = quota.quota_counts([], [], {}, current, templates, manual=additions)
    quota.build_report(tmp_path, additions, set(), counts, {}, current, manual=additions)
    page = (tmp_path/'report_zh.html').read_text()
    assert '完成人工请求 1 份，既有已保存人工轮廓复用 1 份（不是新人工编辑）' in page
    assert '【既有人工轮廓复用 r9】不是新人工编辑，不是机器迁移，未确认真值' in page
    assert '【本轮计入人工描绘 r9】不是机器迁移，未确认真值' in page
    assert 'data-batch="new"' not in page
