"""Backup-only Class 10 manual requests; no generated masks or live writes.

Review creates an internal contact sheet in a fresh temporary directory. Build
requires explicit per-image visual decisions, writes a new frozen request pack,
and never activates it. The six pre-existing human masks remain conditional
priority-0 reuse evidence, NOT additions to the pending 231-frame batch.
"""
from __future__ import annotations

import argparse
from collections import Counter, defaultdict
from contextlib import closing
from datetime import datetime, timezone
import hashlib
import html
import json
import math
from pathlib import Path
import re
import shutil
import sys

import cv2
import numpy as np
from PIL import Image, ImageDraw, ImageFont

PROJECT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(PROJECT))
from pallet.cluster_targets import digest, load_dataset, protected_snapshot, target_key
from pallet.mask_quota_completion import (GALLERY_ORIGIN, POSE_ORIGIN,
    gallery_templates, seed_union)
from pallet.mask_template_refined import QUARANTINE, read_jsonl, readonly, write_jsonl
from pallet.mask_template_transfer import (ImageEvidence, annotation_inventory,
    compatible, rectangle, write_json)
from pallet.pose_review_geometry import canonical
from scripts.build_mask_template_requests import (database_fingerprint,
    native_quality, patch_vector, render_case, signature)

OUT = PROJECT/'outputs/pallet_mask_class10_manual_supplement_v1'
QUOTA = PROJECT/'outputs/pallet_mask_quota_completion_v1'
DIAGNOSTIC = PROJECT/'outputs/pallet_mask_class10_completion_diagnostic_v1'
POSE_LIVE = PROJECT/'outputs/pallet_pose_human_review_v1/annotations.sqlite3'
GALLERY_LIVE = PROJECT/'outputs/pallet_mask_gallery_reviews_v1/mask_reviews.sqlite3'
POSE_ACCESS = PROJECT/'outputs/pallet_pose_review_managed_v1/public_access.json'
FONT = Path('/tmp/opencode/pallet_pose_design/NotoSansCJKsc-Regular.otf')
COUNT = 13
HUMAN_REUSE_KEYS = {'5a50c8a3f3b203f4a73302c5', '769e10f2f395d177eee6ee8f',
    '77c50239649469197cae6b04', '82570f9f6b30bb2c1d696306',
    '8515501d58bc1f637a826f4b', 'b62526c40d7f972094b41bdb'}

# Filled only after viewing each native-intensity crop and full source image.
# These are assistant source-quality decisions, not human class/GT confirmation.
VISUAL_REVIEW = {
    'c3f61efbb64accbbd71ca166': '整图底部目标完整；横梁、左右脚及中部窄开口可辨。右段有少量强度缺点，仍能沿连续边缘人工描绘；与现存同源 Class 10 人工参考外观一致。',
    'd9c2c8a3d7a9abfda3a3bca1': '整图底部单开口横梁与两端支脚完整，黑色内缘连续；不是把上方框架或地面车叉当作目标。',
    '3986404faf57fbe77449a0a7': '箱体下方横梁、中央脚及两端脚清楚，目标未截断；只描绘底部叉取结构，不包含箱体侧板或背景。',
    'b1e615d7fedaab6533759265': '640×480 原图右侧托盘底部的横梁与两端脚可辨，原框不是左侧载管托盘；背景颗粒明显且目标较小，须放大原生图核对边界，不沿噪声描点。',
    'b36308b768afba163c86276c': '整图底部横梁和中部窄开口清晰，左右脚均完整；边缘比同组部分帧平顺，可直接人工区分托盘与地面。',
    '201e2c973a4edac7c4f093a6': '底部单开口横梁和两脚完整；横梁内缘少量黑色缺点不遮断主轮廓，地面与车叉在目标之外。',
    '53ba0983f0d15d0a2a68c031': '箱体下方横梁、中央脚和两端脚完整；开口内侧边缘对比明显，与现存同源人工参考一致，不把箱体侧板计入。',
    '9b7aa309dbf99f376b205eb3': '底部横梁与中央窄开口清楚，两端脚完整；左侧横梁有局部强度缺点，但开口和脚的连续边缘仍可辨认。',
    '6890d57090773e451d8c0060': '整图底部横梁和两脚完整、黑色内缘连续；底面亮度稍低但原生轮廓清楚，不需要假定缺失结构。',
    '8ee3e8919513e00ae7a3bb56': '底部横梁、两大开口和中部窄开口可辨，脚端均在图内；右侧少量强度噪点不遮断结构边界。',
    '8da5ffa1748366aed21b599a': '底部叉取结构完整，横梁、两端脚及中部窄开口边缘清楚；上层框架和反光箱体与原框目标分离。',
    '905122c848e4b20bf15c379b': '整图底部横梁与脚完整，中部窄开口边缘连续；目标不与下方车叉相连，不把地面反光当作轮廓。',
    '67838228711c32a1b7be1f28': '底部横梁和中部窄开口清晰，左右脚端完整；开口内地面可与托盘本体区分，没有明显遮挡或截断。',
}
VISUAL_REJECTIONS = {}


def require(condition, message):
    if not condition:
        raise ValueError(message)


def read_json(path):
    return json.loads(Path(path).read_text())


def sha(value):
    return hashlib.sha256(canonical(value)).hexdigest()


def input_hashes(paths):
    return {str(p.relative_to(PROJECT)): digest(p) for p in paths}


def prepare():
    """Read source identities, complete histories, and direct-human seeds only."""
    cv2.setNumThreads(1)
    formal = Path(read_json(PROJECT/'configs/active_formal_dataset.json')['dataset'])
    classification = PROJECT/'outputs/pallet_appearance_center_reclassification_v1/targets.jsonl'
    manifest = read_json(QUOTA/'manifest.json')
    previous = read_jsonl(QUOTA/'proposals.jsonl')
    require(len(previous) == len({p['target_key'] for p in previous}) ==
        len({p['source']['frame_id'] for p in previous}) == 231 and
        Counter(p['class_id'] for p in previous) == {1: 50, 2: 50, 9: 50, 10: 31, 15: 50},
        'Expected pending 231-frame batch with Class 10 = 31')
    require(digest(QUOTA/'proposals.jsonl') == manifest['proposals_sha256'] and
        digest(QUOTA/'template_inventory.json') == manifest['template_inventory_sha256'] and
        digest(formal/'manifest.json') == manifest['formal_manifest_sha256'] and
        digest(classification) == manifest['classification_sha256'], 'Quota/source identity changed')
    annotations, sources = load_dataset(formal)
    values = read_jsonl(classification)
    rows = {r['target_key']: r for r in values}
    identities = {target_key(a['frame_id'], i): (a, b)
        for a in annotations for i, b in enumerate(a['boxes'])}
    require(len(rows) == len(values) and set(rows) == set(identities), 'Target coverage mismatch')
    for key, row in rows.items():
        annotation, bbox = identities[key]
        source = sources[row['frame_id']]
        require(row['bbox'] == bbox and
            all(row[k] == annotation[k] for k in ('frame_id', 'group_id', 'split')) and
            row['policy_id'] == source['sensor_policy']['policy_id'] and
            row['source_pcd_sha256'] == source['source_anchor_hash'] and
            row['image'] == source['image'], 'Formal source identity mismatch')
        row['size'] = source['size']
    fingerprints = {}
    for kind, live, frozen, expected in (
            ('pose', POSE_LIVE, QUOTA/'reviews_snapshot.sqlite3', manifest['snapshot_sha256']),
            ('gallery', GALLERY_LIVE, QUOTA/'gallery_reviews_snapshot.sqlite3', manifest['gallery_snapshot_sha256'])):
        require(digest(frozen) == expected, 'Frozen database hash changed')
        fingerprints[kind] = database_fingerprint(frozen, True)
        require(database_fingerprint(live) == fingerprints[kind], 'Live review differs from frozen quota')
    with closing(readonly(QUOTA/'reviews_snapshot.sqlite3', True)) as db:
        current, pose, status = annotation_inventory(db, rows)
        pose_events = [json.loads(raw) for raw, in db.execute('SELECT payload FROM events ORDER BY id')]
        human_events = {v['target_key']: {} for v in pose_events}
        for key, revision, raw in db.execute('SELECT target_key,revision,payload FROM events ORDER BY id'):
            human_events[key][revision] = (json.loads(raw), hashlib.sha256(raw.encode()).hexdigest())
    with closing(readonly(QUOTA/'gallery_reviews_snapshot.sqlite3', True)) as db:
        reviews = {k: json.loads(raw) for k, raw in db.execute('SELECT target_key,payload FROM reviews')}
        gallery_events = [json.loads(raw) for raw, in db.execute('SELECT payload FROM events ORDER BY id')]
    parent = Path(manifest['parent'])
    gallery = gallery_templates(read_jsonl(parent/'proposals.jsonl'), reviews, gallery_events,
        current, rows, parent, manifest['formal_manifest_sha256'], manifest['gallery_snapshot_sha256'])
    old_protection = read_json(QUOTA/'protected_targets.json')
    quarantine = QUARANTINE | set(manifest.get('preserved_quarantined_targets', [])) | set(old_protection['quarantine'])
    templates = seed_union(pose, gallery, manifest['snapshot_sha256'], quarantine)
    inventory = read_json(QUOTA/'template_inventory.json')
    frozen_templates = {t['row']['target_key']: {k: v for k, v in t.items() if k != 'rendering_id'}
        for t in inventory['templates'] if t['rendering_id'].startswith('quota_generation:')}
    require(templates == frozen_templates and len(templates) == 175 and
        sum(t['row']['final_class_id'] == 10 for t in templates.values()) == 22,
        'Direct-human seed inventory changed')
    machine_keys = {p['target_key'] for p in read_jsonl(QUOTA/'new_proposals.jsonl')}
    require(len(machine_keys) == 67 and machine_keys <= {p['target_key'] for p in previous} and
        not machine_keys.intersection(templates), 'Machine candidates entered seed inventory')
    reuse = read_jsonl(DIAGNOSTIC/'existing_human_reuse.jsonl')
    require({r['target_key'] for r in reuse} == HUMAN_REUSE_KEYS and len(reuse) == 6,
        'Expected six existing saved-human reuse records')
    for r in reuse:
        key = r['target_key']; t = templates[key]; value = current[key]
        event, event_sha = human_events[key][t['human_polygon_revision']]
        require(t['origin'] == POSE_ORIGIN and rows[key]['final_class_id'] == 10 and
            r['source'] == rows[key] and r['polygon'] == t['polygon'] == value['polygon'] and
            len(t['polygon']) > 4 and value == r['current_payload'] and
            sha(value) == r['current_payload_sha256'] == t['current_payload_sha256'] and
            event_sha == r['human_event_sha256'] == t['human_event_sha256'] and
            event['polygon'] == value['polygon'] and
            event.get('event_kind') not in ('mask_template_proposal', 'axes_normalization', 'unit_normalization') and
            value.get('state') not in ('deleted', 'deferred') and
            not any(value.get(flag) for flag in ('human_mask_confirmed', 'human_pose_confirmed',
                'automatic_training_eligible', 'ground_truth_eligible', 'robot_command_eligible')),
            'Existing-human reuse provenance changed')
    quota_keys = {p['target_key'] for p in previous}
    quota_frames = {p['source']['frame_id'] for p in previous}
    require(not HUMAN_REUSE_KEYS.intersection(quota_keys) and
        len(quota_frames | {r['source']['frame_id'] for r in reuse}) == 237,
        'Six existing human masks are not distinct novel frames')
    research_keys = {p['target_key'] for p in read_jsonl(DIAGNOSTIC/'accepted_candidates.jsonl')}
    pose_history = {v['target_key'] for v in pose_events}
    gallery_history = set(reviews) | {v['target_key'] for v in gallery_events}
    special_history = {v['target_key'] for v in pose_events if v.get('state') in ('deleted', 'deferred') or
        v.get('human_mask_confirmed') or v.get('human_pose_confirmed')}
    excluded = (quota_keys | HUMAN_REUSE_KEYS | set(current) | pose_history | gallery_history |
        special_history | quarantine | set(templates) | research_keys |
        set(old_protection['pose_mask_history_or_noneligible']) |
        set(old_protection['gallery_saved_or_history']))
    # Stronger than the minimum: do not disturb a protected other box in the same frame.
    excluded_frames = {rows[k]['frame_id'] for k in excluded}
    eligible = {k: r for k, r in rows.items() if r['final_class_id'] == 10 and
        status[k] == 'eligible' and k not in excluded and r['frame_id'] not in excluded_frames}
    outcomes = {r['target_key']: r for r in read_jsonl(QUOTA/'outcomes.jsonl')}
    diagnostic_outcomes = {r['target_key']: r for r in read_jsonl(DIAGNOSTIC/'outcomes.jsonl')}
    tracking = defaultdict(Counter)
    # Read rejection metadata only; no candidate polygon is read as a template.
    with (DIAGNOSTIC/'registration_attempts.jsonl').open() as handle:
        for line in handle:
            trial = json.loads(line)
            for config in trial['metrics'].get('configurations', []):
                tracking[trial['target_key']][str(config['metrics'].get('rejection'))] += 1
    evidence = ImageEvidence(formal, rows, sources)
    usable, rejections = {}, Counter()
    human_groups = defaultdict(list)
    for key, t in templates.items():
        human_groups[signature(t['row'])].append(key)
    clear_groups = defaultdict(list)
    all_groups = defaultdict(list)
    for key, row in sorted(eligible.items()):
        all_groups[signature(row)].append(key)
        quality, rejection = native_quality(row, evidence)
        if rejection:
            rejections[rejection] += 1
            continue
        refs = sorted(k for k, t in templates.items() if compatible(t['row'], row))
        usable[key] = dict(quality=quality, compatible_human_template_keys=refs,
            exact_signature_human_template_keys=human_groups[signature(row)],
            oldseed_coverage_absent=not refs,
            exact_view_human_template_absent=not human_groups[signature(row)],
            original_attempt_outcome=outcomes.get(key), multiscale_diagnostic_outcome=diagnostic_outcomes.get(key),
            tracking_configuration_rejections=dict(tracking[key]))
        clear_groups[signature(row)].append(key)
    for sig, keys in clear_groups.items():
        vectors = np.array([patch_vector(evidence, k) for k in keys])
        distances = np.maximum(0, 2-2*(vectors @ vectors.mean(axis=0)))
        if len(keys) > 1:
            distances *= len(keys)/(len(keys)-1)
        else:
            distances[:] = 0
        for i, key in enumerate(keys):
            others = [j for j, k in enumerate(keys) if rows[k]['frame_id'] != rows[key]['frame_id']]
            distance = float(distances[i]) if len(others) == len(keys)-1 else (
                float(np.mean([np.sum((vectors[i]-vectors[j])**2) for j in others])) if others else 0.)
            usable[key].update(medoid_mean_squared_patch_distance=distance,
                compatible_neighbor_count=sum(rows[k]['frame_id'] != rows[key]['frame_id'] for k in all_groups[sig]),
                usable_compatible_neighbor_count=len(others))
        for rank, key in enumerate(sorted(keys, key=lambda k: (usable[k]['medoid_mean_squared_patch_distance'], k)), 1):
            usable[key]['medoid_rank'] = rank
    paths = [Path(__file__), PROJECT/'scripts/build_mask_template_requests.py', classification,
        PROJECT/'configs/active_formal_dataset.json', PROJECT/'configs/active_mask_template_requests.json',
        PROJECT/'configs/active_mask_template_proposals.json', PROJECT/'configs/active_mask_gallery.json',
        QUOTA/'manifest.json', QUOTA/'proposals.jsonl', QUOTA/'template_inventory.json',
        QUOTA/'protected_targets.json', QUOTA/'outcomes.jsonl', QUOTA/'new_proposals.jsonl',
        QUOTA/'reviews_snapshot.sqlite3', QUOTA/'gallery_reviews_snapshot.sqlite3',
        DIAGNOSTIC/'existing_human_reuse.jsonl', DIAGNOSTIC/'accepted_candidates.jsonl',
        DIAGNOSTIC/'registration_attempts.jsonl', DIAGNOSTIC/'outcomes.jsonl']
    paths += [PROJECT/name for name in ('pallet/mask_template_transfer.py', 'pallet/mask_quota_completion.py',
        'pallet/mask_template_refined.py', 'pallet/cluster_targets.py', 'pallet/pose_review_geometry.py')]
    return dict(formal=formal, rows=rows, evidence=evidence, eligible=eligible, usable=usable,
        templates=templates, reuse=reuse, fingerprints=fingerprints, excluded=excluded,
        excluded_frames=excluded_frames, quota_keys=quota_keys, machine_keys=machine_keys,
        research_keys=research_keys, rejections=dict(rejections), inputs=input_hashes(paths),
        formal_manifest_sha256=manifest['formal_manifest_sha256'])


def ranked(data, count, approved_only=False):
    rows, usable = data['rows'], data['usable']
    pool = set(usable) - set(VISUAL_REJECTIONS)
    if approved_only:
        pool &= set(VISUAL_REVIEW)
    chosen, frames = [], set()
    sigs, groups, splits = Counter(), Counter(), Counter()
    while pool and len(chosen) < count:
        options = [k for k in pool if rows[k]['frame_id'] not in frames]
        if not options:
            break
        def rank(key):
            v, row = usable[key], rows[key]
            score = (.55*(1-v['medoid_mean_squared_patch_distance']/4) + .35*v['quality']['clarity_score'] +
                .1*min(math.log1p(v['usable_compatible_neighbor_count'])/math.log(101), 1))
            # Missing exact sensor/split/view coverage first, then diversity and
            # observed tracking ambiguity, finally medoid/clarity (not accuracy).
            tracking_failed = v['tracking_configuration_rejections'].get('unreliable_vertex_tracking', 0) > 0
            return (not v['oldseed_coverage_absent'], not v['exact_view_human_template_absent'],
                sigs[signature(row)], groups[row['group_id']], splits[row['split']],
                not tracking_failed, -score, key)
        key = min(options, key=rank); row = rows[key]
        chosen.append(key); frames.add(row['frame_id']); pool.remove(key)
        sigs[signature(row)] += 1; groups[row['group_id']] += 1; splits[row['split']] += 1
    return chosen


def contact_sheet(root, requests, name='selection_contact.png'):
    columns, width, height = 2, 800, 280
    sheet = Image.new('RGB', (columns*width, math.ceil(len(requests)/columns)*height), '#111923')
    draw = ImageDraw.Draw(sheet)
    font = ImageFont.truetype(str(FONT), 17)
    for i, request in enumerate(requests):
        key, row = request['target_key'], request['source']
        x, y = i % columns*width, i//columns*height
        draw.text((x+8, y+5), f'{i+1:02d} Class 10 | {key}', font=font, fill='white')
        draw.text((x+8, y+31), f'{row["split"]} | {row["viewpoint_candidate"]} | {row["policy_id"]}', font=font, fill='#b8d6ee')
        with Image.open(root/request['contact_crop']) as image:
            # Nearest-neighbor enlargement keeps low-resolution source evidence visible.
            scale = min((width-20)/image.width, (height-65)/image.height)
            crop = image.resize((round(image.width*scale), round(image.height*scale)), Image.Resampling.NEAREST)
            sheet.paste(crop, (x+10, y+60))
    sheet.save(root/name)


def review(directory):
    require(directory.is_relative_to(Path('/tmp/opencode')) and not directory.exists(), 'Use a new /tmp/opencode review directory')
    data = prepare(); keys = ranked(data, 39)
    directory.mkdir(); (directory/'cases').mkdir(); (directory/'images').mkdir()
    requests = []
    for key in keys:
        row = data['rows'][key]
        render_case(row, data['evidence'], directory/'cases'/f'{key}.png')
        shutil.copyfile(data['formal']/row['image'], directory/'images'/f'{key}.png')
        requests.append(dict(target_key=key, source=row, contact_crop=f'cases/{key}.png', **data['usable'][key]))
    write_jsonl(directory/'shortlist.jsonl', requests)
    for start in range(0, len(requests), 12):
        contact_sheet(directory, requests[start:start+12], f'review_{start+1:02d}_{min(start+12,len(requests)):02d}.png')
    seeds = []
    for key, t in sorted(data['templates'].items()):
        if t['row']['final_class_id'] == 10:
            render_case(t['row'], data['evidence'], directory/'cases'/f'{key}.png')
            seeds.append(dict(target_key=key, source=t['row'], contact_crop=f'cases/{key}.png'))
    for start in range(0, len(seeds), 12):
        contact_sheet(directory, seeds[start:start+12], f'direct_human_seeds_{start+1:02d}.png')
    print(json.dumps(dict(review_directory=str(directory), shortlisted=len(requests), eligible=len(data['eligible']),
        usable=len(data['usable']), quality_rejections=data['rejections']), ensure_ascii=False))


def report(requests, pose_url, reuse):
    esc = html.escape
    priority0 = ''.join(f'<li><code>{r["target_key"]}</code> · {r["source"]["split"]} · '
        f'现存人工多边形 {r["vertex_count"]} 点，当前修订 {r["current_payload"]["revision"]}；'
        f'<a href="{esc(pose_url+"/?target="+r["target_key"], quote=True)}">核对现存人工记录</a></li>' for r in reuse)
    cards = []
    for r in requests:
        key, s = r['target_key'], r['source']
        cards.append(f'''<article id="{key}"><h2>备选顺序 {r['request_order']:02d} · Class 10 · 待人工描绘</h2>
<p><code>{key}</code> <button data-copy="{key}">复制目标键</button> <span role="status"></span></p>
<p><a class="action" target="_blank" rel="noopener" href="{esc(r['pose_annotation_url'], quote=True)}">打开原位姿标注</a></p>
<p>{esc(r['reason_zh'])}</p><p>来源：{esc(s['frame_id'])}<br>划分：{esc(s['split'])} · 视角：{esc(str(s['viewpoint_candidate']))}<br>
传感器策略：{esc(s['policy_id'])}<br>来源组：{esc(s['group_id'])}</p>
<p>无当前位姿保存记录，也无任何位姿事件历史。现有兼容人工模板 {len(r['diagnostic_compatible_template_ids'])} 个；
严格同类别／划分／传感器／视角人工模板 {len(r['exact_signature_human_template_keys'])} 个。
清晰同组合其他帧 {r['usable_compatible_neighbor_count']} 个；邻居数和图像评分不是迁移成功率。</p>
<figure><img src="{r['contact_crop']}" alt="Class 10 原生强度局部与原始橙色矩形"><figcaption>只显示原始矩形，没有机器或人工新多边形。</figcaption></figure>
<p>图像复查：{esc(r['source_visual_review_zh'])} 此为助手图像可描绘性复查，不是人工类别确认。</p>
<p>原分类复核标记：<code>{esc(', '.join(r['classification_review_flags']) or '无附加标记')}</code>；沿用候选 Class 10，尚未人工确认类别。</p>
<details><summary>完整原生图像</summary><img loading="lazy" src="{r['native_image']}" alt="完整原生强度源图"></details>
<details><summary>既有算法排除依据（不是标签）</summary><pre>{esc(json.dumps(r['prior_algorithm_evidence'],ensure_ascii=False,indent=2))}</pre></details>
<p>状态：备用、未激活、needs_manual_tracing。需沿真实可见边界人工描绘超过四个顶点的有效多边形；不为凑数添加冗余点。
类别可疑、遮挡或边界不清时应暂缓复核，不得用原始矩形冒充完成掩膜。</p></article>''')
    return f'''<!doctype html><html lang="zh-CN"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
<title>Class 10 人工补充备用清单 · 13 帧 · 未激活</title><style>
@font-face{{font-family:RequestSans;src:url('report-font.otf')}}*{{box-sizing:border-box}}
body{{font:17px/1.65 RequestSans,sans-serif;background:#111923;color:#edf2f7;max-width:1280px;margin:auto;padding:24px}}
a{{color:#8ed7ff}}code{{font-family:monospace;user-select:all}}article,.notice{{border:1px solid #536479;padding:20px;border-radius:12px;margin:20px 0;background:#192432}}
img{{max-width:100%;height:auto;display:block;margin:12px auto}}figure img{{width:100%;image-rendering:pixelated}}figure{{margin:16px 0}}
td,th{{border:1px solid #536479;padding:8px 16px}}table{{border-collapse:collapse}}pre{{white-space:pre-wrap;overflow-wrap:anywhere}}
button,.action{{font:inherit;display:inline-block;padding:8px 14px;border-radius:8px;background:#17496b;color:#edf2f7;border:1px solid #7194ad}}p,li{{overflow-wrap:anywhere}}
</style></head><body><h1>Class 10 人工模板补充：13 帧备用清单</h1>
<div class="notice"><strong>备用、未激活；不是已完成标签、已接受掩膜、真值或训练集。</strong>
<p>当前待验证配额批次共 231 个不同帧：Class 1、2、9、15 各 50；Class 10 为 31，缺 19。此为待验证批次清单，不等于当前在线已发布数量或人工真值数量。</p>
<table><tr><th>类别</th><th>当前待验证批次帧数</th><th>距 50 缺额</th></tr>
<tr><td>1 / 2 / 9 / 15</td><td>各 50</td><td>各 0</td></tr><tr><td>10</td><td>31</td><td>19</td></tr></table>
<p><strong>优先级 0：先独立核验并决定是否复用批次之外六个现存人工掩膜。</strong>它们尚未在本次构建中计入配额，也未写入图册。
若主会话批准复用，则 31 + 6 = 37，最多再需 13 个新人工任务补到 50；若复用未获批准，本包不足以单独填满原始 19 帧缺口，仍需另建六帧或采用合格研究结果。</p>
<p>本包不预先计入研究中的三个机器候选；也已排除其目标及同帧，避免主会话后续采用时重复。
主会话应在研究和独立验证后决定只取前 N 个任务，并构建新的冻结子包；不得覆盖本包或据此自动激活服务。</p></div>
<h2>优先级 0：六个现存人工掩膜（本包请求数之外）</h2><ul>{priority0}</ul>
<h2>选择原则与边界</h2><p>仅选 Class 10 现有候选分类；排除全部 231 帧（含 67 个新机器候选）、六个现存人工目标、所有位姿当前记录和历史、
删除／暂缓／确认历史、图册当前记录及历史、隔离目标、直接人工模板来源，以及这些目标的同帧。没有用机器候选作模板。</p>
<p>优先补足缺失的传感器策略／划分／视角组合，再兼顾来源组、划分和已观察到的逐顶点跟踪歧义。
同组合清晰图块采用原有请求脚本的原生质量门槛与归一化图块 medoid 距离排序，并逐张检查原始图像。
严格同视角统计只让 unknown 匹配 unknown；算法兼容模板统计沿用原算法的未知视角兼容规则。两种数量分开呈现，均非正确率。</p>
<p><strong>覆盖限制：</strong>采用无当前位姿、无位姿历史且无同帧受保护对象的严格筛选后，只有 17 帧可用。
本次 13 帧覆盖四个传感器策略、四个来源组、train／val 两个划分，视角均为 unknown；没有可选的全新未覆盖兼容组，也没有符合本严格条件的 test 帧。
因此本包主要处理已有模板仍跟踪失败的结构和强度歧义；同一来源组的连续帧不是独立场景，不能把十三帧说成十三种新结构或缺失视角。</p>
<p>原位姿入口取自构建时受管 public_access.json 的 public_url：<a href="{esc(pose_url, quote=True)}">位姿标注</a>。
临时入口可能变化；本包没有包含密钥或访问码，不保证隧道始终在线。沿用已有登录方式。</p>
{''.join(cards)}<footer><p>未部署；所有完成、接受、确认、训练及生产保存标志均为否。
字体：<a href="FONT_LICENSE.txt">Noto 字体许可</a>。</p></footer>
<script>document.querySelectorAll('[data-copy]').forEach(b=>b.onclick=async()=>{{try{{await navigator.clipboard.writeText(b.dataset.copy);b.nextElementSibling.textContent='已复制';}}catch(e){{b.nextElementSibling.textContent='请选中目标键手动复制';}}}});</script></body></html>'''


def build_font(page):
    from fontTools import subset
    from fontTools.ttLib import TTFont
    required = {ord(c) for c in page if '\u3400' <= c <= '\u9fff'}
    with TTFont(FONT) as font:
        require(required <= set(font.getBestCmap()), 'Source font lacks Chinese report glyphs')
        sub = subset.Subsetter(); sub.populate(text=page); sub.subset(font)
        font.save(OUT/'report-font.otf')
    with TTFont(OUT/'report-font.otf') as font:
        require(required <= set(font.getBestCmap()), 'Subset font lacks Chinese report glyphs')
    shutil.copyfile(PROJECT/'pallet/assets/pose_review/FONT_LICENSE.txt', OUT/'FONT_LICENSE.txt')
    write_json(OUT/'font_coverage.json', dict(state='passed', chinese_glyphs=len(required),
        all_report_Chinese_present=True, source_font_sha256=digest(FONT), font_sha256=digest(OUT/'report-font.otf')))


def build():
    require(not OUT.exists(), 'Use a fresh output version; never overwrite a frozen request package')
    data = prepare()
    keys = ranked(data, COUNT, approved_only=True)
    require(len(keys) == COUNT and all(VISUAL_REVIEW[k] for k in keys), 'All 13 crops need explicit source-image review')
    pose_url = read_json(POSE_ACCESS)['public_url'].rstrip('/')
    require(pose_url.startswith('https://') and '?' not in pose_url, 'Unexpected managed public URL')
    before = protected_snapshot(data['formal'])
    OUT.mkdir(); (OUT/'images').mkdir(); (OUT/'cases').mkdir()
    requests = []
    for order, key in enumerate(keys, 1):
        row, v = data['rows'][key], data['usable'][key]
        source = {k: row[k] for k in ('target_key', 'target_id', 'frame_id', 'box_index', 'bbox', 'size',
            'split', 'group_id', 'policy_id', 'viewpoint_candidate', 'source_pcd_sha256', 'image')}
        source.update(image_sha256=digest(data['formal']/row['image']),
            formal_manifest_sha256=data['formal_manifest_sha256'])
        shutil.copyfile(data['formal']/row['image'], OUT/'images'/f'{key}.png')
        bounds = render_case(row, data['evidence'], OUT/'cases'/f'{key}.png')
        reason = ('补齐现有人工模板未覆盖的类别／传感器／划分／视角组合；' if v['oldseed_coverage_absent'] else
            '该兼容组合已有人工模板，但既有算法未给出可用迁移；')
        if v['tracking_configuration_rejections'].get('unreliable_vertex_tracking'):
            reason += '研究记录存在逐顶点跟踪不可靠，需直接人工判定边界；'
        reason += f"同组合清晰图块代表性排名 {v['medoid_rank']}/{v['usable_compatible_neighbor_count']+1}，兼顾来源组与划分多样性。"
        requests.append(dict(schema='manual_mask_template_request_v1', request_order=order, target_key=key,
            copy_key=key, class_id=10, source=source, reason=reason, reason_zh=reason,
            status='needs_manual_tracing', activation_state='backup_not_activated',
            source_label_kind='ORIGINAL_RECTANGLE', original_rectangle=rectangle(row),
            existing_pose_record=False, existing_pose_revision=0, existing_pose_payload_sha256=None,
            existing_pose_geometry_sha256=None, pose_history_present=False,
            preserve_existing_pose_until_intentional_human_edit=True,
            compatible_neighbor_count=v['compatible_neighbor_count'], usable_compatible_neighbor_count=v['usable_compatible_neighbor_count'],
            neighbor_count_semantics='Exact class/split/policy/view distinct-other-frame targets; not successful transfers or probabilities',
            oldseed_coverage_absent=v['oldseed_coverage_absent'], exact_view_human_template_absent=v['exact_view_human_template_absent'],
            diagnostic_compatible_template_ids=v['compatible_human_template_keys'],
            exact_signature_human_template_keys=v['exact_signature_human_template_keys'],
            medoid_mean_squared_patch_distance=v['medoid_mean_squared_patch_distance'], medoid_rank=v['medoid_rank'],
            image_quality=v['quality'], source_visual_review_zh=VISUAL_REVIEW[key],
            class_assignment_status='candidate_not_human_confirmed',
            classification_review_flags=row.get('classification_review_flags', []),
            source_visual_review_kind='assistant_source_image_review_NOT_human_class_confirmation',
            closest_human_reference_key=None, requested_required_vertex_count=None,
            required_vertex_count_is_reference_only=True, topology_must_be_manually_determined=True,
            minimum_manual_template_vertices=5, pose_annotation_url=pose_url+'/?target='+key,
            native_image=f'images/{key}.png', contact_crop=f'cases/{key}.png', crop_native_bounds=bounds,
            prior_algorithm_evidence={k: v[k] for k in ('original_attempt_outcome', 'multiscale_diagnostic_outcome',
                'tracking_configuration_rejections')},
            human_mask_confirmed=False, human_pose_confirmed=False, accepted_candidate=False,
            ground_truth_eligible=False, automatic_training_eligible=False, production_saved=False,
            counts_as_completed_annotation=False, generated_polygons=0))
    write_jsonl(OUT/'requests.jsonl', requests)
    priority0 = [dict(target_key=r['target_key'], class_id=10, source=r['source'],
        priority=0, status='existing_saved_human_pending_primary_reuse_decision',
        counted_in_pending_231=False, counted_by_this_build=False,
        current_revision=r['current_payload']['revision'], current_payload_sha256=r['current_payload_sha256'],
        human_polygon_revision=r['human_polygon_revision'], human_event_sha256=r['human_event_sha256'],
        vertex_count=r['vertex_count'], original_pose_url=pose_url+'/?target='+r['target_key'],
        independent_publication_verification_claimed=False, ground_truth_eligible=False) for r in data['reuse']]
    write_jsonl(OUT/'priority0_existing_human_reuse.jsonl', priority0)
    page = report(requests, pose_url, data['reuse'])
    (OUT/'report_zh.html').write_text(page)
    build_font(page)
    contact_sheet(OUT, requests)
    write_jsonl(OUT/'selection_ranking.jsonl', [dict(target_key=k, source=data['rows'][k], **v)
        for k, v in sorted(data['usable'].items())])
    write_json(OUT/'source_visual_review.json', dict(review_kind='assistant_source_image_review_NOT_human_class_confirmation',
        selected={k: VISUAL_REVIEW[k] for k in keys}, rejections=VISUAL_REJECTIONS))
    write_json(OUT/'used_image_hashes.json', data['evidence'].used)
    write_json(OUT/'protected_formal_before.json', before)
    after = protected_snapshot(data['formal'])
    write_json(OUT/'protected_formal_after.json', after)
    require(before == after, 'Formal data changed during selection')
    require(all(digest(PROJECT/name) == expected for name, expected in data['inputs'].items()), 'Selection inputs/configuration changed')
    require(all(digest(data['formal']/name) == expected for name, expected in data['evidence'].used.items()), 'Source image changed')
    for kind, live in (('pose', POSE_LIVE), ('gallery', GALLERY_LIVE)):
        require(database_fingerprint(live) == data['fingerprints'][kind], 'Live history changed; rebuild in a new version')
    require(read_json(POSE_ACCESS)['public_url'].rstrip('/') == pose_url, 'Managed public URL changed')
    require(len({r['target_key'] for r in requests}) == len({r['source']['frame_id'] for r in requests}) == COUNT,
        'Requests must have distinct targets and frames')
    for r in requests:
        key = r['target_key']
        require(key in data['eligible'] and key not in data['excluded'] and
            r['source']['frame_id'] not in data['excluded_frames'] and
            digest(OUT/r['native_image']) == r['source']['image_sha256'] and
            r['original_rectangle'] == rectangle(data['rows'][key]) and len(r['original_rectangle']) == 4,
            'Final target/source eligibility check failed')
    names = ['report_zh.html', 'report-font.otf', 'FONT_LICENSE.txt'] + [r[k] for r in requests for k in ('native_image', 'contact_crop')]
    public_assets = {name: digest(OUT/name) for name in sorted(names)}
    require(len(public_assets) == 3+2*COUNT == 29 and all(re.fullmatch(
        r'(report_zh\.html|report-font\.otf|FONT_LICENSE\.txt|(?:cases|images)/[0-9a-f]{24}\.png)', name) for name in names),
        'Public asset allowlist differs from existing manual-request loader')
    require(not list(OUT.rglob('*.sqlite*')) and not list(OUT.rglob('*.db')) and
        not (OUT/'masks').exists() and not (OUT/'labelme').exists(), 'Private database or generated mask in output')
    timestamp = datetime.now(timezone.utc).isoformat()
    manifest = dict(schema='manual_mask_template_requests_v1', state='verified_static_manual_tracing_requests',
        activation_state='backup_not_activated', created_at=timestamp, request_count=COUNT,
        class_counts={'10': COUNT}, requested_class_counts={'10': COUNT},
        pending_batch_count=231, pending_batch_class_counts={'1': 50, '2': 50, '9': 50, '10': 31, '15': 50},
        pending_batch_is_not_active_publication_or_ground_truth=True,
        remaining_published_gaps=None, pending_batch_class10_gap=19,
        priority0_existing_human_count=6, priority0_counted_by_this_build=0,
        conditional_after_primary_approves_six_human_reuse=dict(class10_base=37, additional_manual_needed=13),
        conditional_without_six_human_reuse=dict(class10_base=31, additional_manual_needed=19, this_package_is_insufficient=True),
        subset_policy='Primary decides first N after research; build a NEW frozen subset package, never overwrite or auto-activate',
        requests_sha256=digest(OUT/'requests.jsonl'), existing_pose_request_count=0,
        uncovered_compatibility_request_count=sum(r['oldseed_coverage_absent'] for r in requests),
        exact_view_uncovered_request_count=sum(r['exact_view_human_template_absent'] for r in requests),
        class_selection_pools={'10': dict(eligible=len(data['eligible']), usable=len(data['usable']))},
        selected_split_counts=dict(Counter(r['source']['split'] for r in requests)),
        selected_sensor_policy_counts=dict(Counter(r['source']['policy_id'] for r in requests)),
        selected_source_group_counts=dict(Counter(r['source']['group_id'] for r in requests)),
        selected_view_counts=dict(Counter(r['source']['viewpoint_candidate'] for r in requests)),
        coverage_limitation='No wholly uncovered compatible signature remains in strict no-pose/no-protected-frame pool; unknown views only, train/val only, consecutive frames are not independent scenes',
        image_quality_rejections=data['rejections'], new_machine_candidates_excluded=67,
        additional_multiscale_research_candidates_excluded=sorted(data['research_keys']),
        selection_priority=['no_pose_current_or_events_or_other_protected_frame', 'no_compatible_direct_human_seed',
            'no_exact_class_split_policy_view_seed', 'signature_diversity', 'source_group_diversity',
            'split_diversity', 'observed_unreliable_vertex_tracking', 'medoid_and_native_clarity', 'individual_source_image_review'],
        compatibility_policy='Ranking and medoid: exact class/split/policy/view; algorithm seed count: original compatible() semantics',
        medoid_objective='Mean squared Euclidean distance to other clear compatible 64x28 zero-mean unit-L2 patches; not transfer success',
        direct_human_seed_count=175, class10_direct_human_seed_count=22, generated_candidates_used_as_templates=0,
        pose_public_url=pose_url, pose_public_url_authority='managed public_access.json public_url field',
        pose_url_temporary=True, frozen_input_sha256=data['inputs'], database_logical_fingerprints=data['fingerprints'],
        reused_frozen_snapshots=True, live_stores_match_frozen_at_start_and_finish=True,
        protected_formal_files_verified=len(before), evidence_images_verified=len(data['evidence'].used),
        production_database_writes=0, configuration_writes=0, service_writes=0, publication_changes=0,
        generated_polygons=0, completed_manual_labels=0, human_confirmation_inferred=False,
        accepted_candidates=False, ground_truth_eligible=False, automatic_training_eligible=False,
        public_assets=public_assets)
    write_json(OUT/'manifest.json', manifest)
    verification = dict(state='passed', schema='manual_mask_template_request_verification_v1', verified_at=timestamp,
        request_count=COUNT, requests_sha256=digest(OUT/'requests.jsonl'), manifest_sha256=digest(OUT/'manifest.json'),
        public_assets=public_assets, public_asset_count=len(public_assets), all_request_targets_live_eligible=True,
        all_source_identities_and_hashes_verified=True, native_images_byte_identical_to_formal_sources=True,
        only_original_rectangle_annotations=True, all_selected_source_images_individually_reviewed=True,
        no_published_or_human_mask_history_targets=True, no_pose_current_or_event_targets=True,
        no_gallery_history_or_quarantine_or_protected_frames=True, all_67_new_machine_targets_excluded=True,
        no_generated_templates=True, six_existing_human_masks_not_counted_by_build=True,
        no_private_databases_in_output=True, all_report_Chinese_present=True, pose_url_current_at_verification=True,
        live_stores_match_frozen_at_start_and_finish=True, protected_formal_files_unchanged=True,
        active_config_files_unchanged=True, production_database_writes=0, configuration_writes=0, service_writes=0,
        publication_changes=0, generated_polygons=0, completed_manual_labels=0, activated=False,
        ground_truth_eligible=False, automatic_training_eligible=False)
    write_json(OUT/'verification.json', verification)
    require(all(digest(OUT/name) == expected for name, expected in public_assets.items()), 'Public asset changed')
    (OUT/'README.md').write_text('# Class 10 人工补充备用包（未激活）\n\n'
        '13 个待描绘请求；`report_zh.html`、`requests.jsonl`；内部可读联系表 `selection_contact.png`。\n\n'
        '基线为待验证 231 帧批次，四类各 50、Class 10 为 31（缺 19），不是在线发布或真值数量。\n'
        '优先级 0 的六个现存人工掩膜在本次构建中不计数；主会话独立批准复用后为 37，再需至多 13 个新人工任务。\n'
        '若研究候选被采用，可仅取前 N 个并另建冻结子包；本包不得覆盖。若六个复用未获批准，13 个任务不足填满原缺口。\n\n'
        '仅 verification.json 的 public_assets 可经现有 /template-requests/ 命名空间对外提供（29 个文件）；其余元数据及联系表保持内部。\n'
        '本脚本不写 active config、数据库或服务；不生成新多边形、accepted masks、真值或训练输入。\n')
    write_json(OUT/'artifact_hashes.json', {str(p.relative_to(OUT)): digest(p) for p in sorted(OUT.rglob('*')) if p.is_file()})
    print(json.dumps(dict(state='passed', output=str(OUT.relative_to(PROJECT)), request_count=COUNT,
        public_asset_count=len(public_assets), activated=False, manifest_sha256=digest(OUT/'manifest.json'),
        verification_sha256=digest(OUT/'verification.json')), ensure_ascii=False))


if __name__ == '__main__':
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('--review-directory', type=Path, help='Fresh /tmp/opencode directory for source-image inspection')
    parser.add_argument('--build', action='store_true', help='Build the frozen backup after explicit visual decisions')
    args = parser.parse_args()
    require(bool(args.review_directory) != args.build, 'Choose exactly one of --review-directory or --build')
    if args.review_directory:
        review(args.review_directory.resolve())
    else:
        build()
