"""Independent quota-100 manual worklist: read-only evidence, no activation.

--review stages ranked crops/full images inside this package's private internal
directory. After individually inspecting them, record decisions there and run
--build. A sealed package is never overwritten. No proposal/mask is generated.
"""
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, protected_snapshot
from pallet.mask_quota_saved_extension import file_inventory, load_formal_evidence
from pallet.mask_template_refined import QUARANTINE, read_jsonl, readonly, verify_history_preserved, write_jsonl
from pallet.mask_template_transfer import annotation_inventory, rectangle, unchanged_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_quota_100_requests_v1'
BASE = PROJECT/'outputs/pallet_mask_quota_100_v2'
POSE = PROJECT/'outputs/pallet_pose_human_review_v1/annotations.sqlite3'
GALLERY = PROJECT/'outputs/pallet_mask_gallery_reviews_v1/mask_reviews.sqlite3'
ACCESS = PROJECT/'outputs/pallet_pose_review_managed_v1/public_access.json'
FONT = Path('/tmp/opencode/pallet_pose_design/NotoSansCJKsc-Regular.otf')
QUOTAS = {1: 10, 10: 10, 9: 2, 15: 2}
BASE_COUNTS = {1: 58, 2: 100, 9: 83, 10: 54, 15: 83}
OLD_REQUESTS = [PROJECT/'outputs/pallet_mask_template_requests_v1/requests.jsonl',
    PROJECT/'outputs/pallet_mask_class10_manual_supplement_v2/requests.jsonl']


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 prepare():
    cv2.setNumThreads(1)
    manifest = read_json(BASE/'manifest.json')
    proposals = read_jsonl(BASE/'proposals.jsonl')
    require(len(proposals) == 378 and Counter(p['class_id'] for p in proposals) == BASE_COUNTS and
        len({p['source']['frame_id'] for p in proposals}) == 378, 'Expected 378 distinct quota-100 frames')
    require(manifest['publication_version'] == 7 and manifest['saved_human'] == 251 and
        manifest['old_pending_machine'] == 43 and manifest['new_proposals'] == 84,
        'Baseline human/pending decomposition differs')
    for name in ('proposals', 'new_proposals', 'template_inventory'):
        suffix = '.json' if name == 'template_inventory' else '.jsonl'
        require(digest(BASE/(name+suffix)) == manifest[name+'_sha256'], 'Baseline hash differs: '+name)
    formal, rows, evidence = load_formal_evidence(manifest)
    # The complete original classification row is retained in each request.
    original_rows = {r['target_key']: r for r in read_jsonl(
        PROJECT/'outputs/pallet_appearance_center_reclassification_v1/targets.jsonl')}
    for k, row in rows.items():
        require(row['image'] == evidence.sources[row['frame_id']]['image'], 'Formal image identity mismatch')
    fingerprints, history_checks = {}, {}
    for kind, live, name, field in [('pose', POSE, 'reviews_snapshot.sqlite3', 'snapshot_sha256'),
            ('gallery', GALLERY, 'gallery_reviews_snapshot.sqlite3', 'gallery_snapshot_sha256')]:
        frozen = BASE/name
        require(digest(frozen) == manifest[field], 'Latest frozen database hash differs')
        verify_history_preserved(live, frozen)
        fingerprints[kind] = database_fingerprint(frozen, True)
        require(database_fingerprint(live) == fingerprints[kind],
            'Live store differs from latest quota snapshot; rebuild against new immutable evidence')
        history_checks[kind] = dict(frozen_sha256=digest(frozen), all_frozen_event_bytes_preserved=True,
            live_logically_equal_to_frozen=True, table_counts=fingerprints[kind]['table_counts'])
    with closing(readonly(BASE/'reviews_snapshot.sqlite3', True)) as db:
        current, pose_templates, status = annotation_inventory(db, rows)
        events = [(i, k, rev, raw, json.loads(raw)) for i, k, rev, raw in db.execute(
            'SELECT id,target_key,revision,payload FROM events ORDER BY id')]
    with closing(readonly(BASE/'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 = [(k, raw, json.loads(raw)) for k, raw in db.execute('SELECT target_key,payload FROM events ORDER BY id')]
    inventory = read_json(BASE/'template_inventory.json')
    templates = {t['row']['target_key']: t for t in inventory['templates']
        if t['rendering_id'].startswith('quota100_generation:')}
    require(len(templates) == manifest['generation_templates'] == 256, 'Latest direct-human seed count differs')
    new_keys = {p['target_key'] for p in read_jsonl(BASE/'new_proposals.jsonl')}
    require(len(new_keys) == 84 and not new_keys.intersection(templates), 'New machine candidates entered seed inventory')
    for key, t in templates.items():
        require(t['row'] == rows[key] and len(t['polygon']) > 4, 'Seed source identity differs')
        if t['origin'] == 'mask_gallery_human_revision':
            v = reviews[key]
            require(v['polygon'] == t['polygon'] and v['revision'] == t['human_polygon_revision'] and
                v.get('human_edited') is True and v.get('event_kind') == 'human_mask_gallery_revision' and
                any(k == key and hashlib.sha256(raw.encode()).hexdigest() == t['human_event_sha256']
                    for k, raw, _ in gallery_events), 'Gallery seed lacks exact saved human event')
        else:
            require(key in pose_templates and all(t[f] == pose_templates[key][f]
                for f in ('polygon', 'revision', 'human_event_sha256', 'current_payload_sha256')),
                'Pose seed differs from original annotation_inventory human provenance')
    history = defaultdict(list)
    special = set()
    for i, key, revision, raw, v in events:
        modified = bool(v.get('polygon')) and not unchanged_rectangle(v['polygon'], rows[key])
        flags = dict(state=v.get('state'), human_mask_confirmed=bool(v.get('human_mask_confirmed')),
            human_pose_confirmed=bool(v.get('human_pose_confirmed')), mask_modified=modified)
        history[key].append(dict(event_id=i, revision=revision, event_kind=v.get('event_kind'),
            payload_raw_sha256=hashlib.sha256(raw.encode()).hexdigest(), **flags))
        if modified or flags['state'] in ('deleted', 'deferred') or flags['human_mask_confirmed'] or flags['human_pose_confirmed']:
            special.add(key)
    gallery_history = set(reviews) | {k for k, _, _ in gallery_events}
    quarantine = QUARANTINE | set(manifest.get('preserved_quarantined_targets', []))
    old_requests = [r for path in OLD_REQUESTS for r in read_jsonl(path)]
    require(len(old_requests) == 37 and len({r['target_key'] for r in old_requests}) == 37,
        'Expected unchanged completed original 24+13 request keys')
    old_keys = {r['target_key'] for r in old_requests}
    human_keys = set(pose_templates) | set(templates) | {t['row']['target_key'] for t in inventory['templates']}
    protected = ({p['target_key'] for p in proposals} | gallery_history | special | quarantine | human_keys | old_keys |
        {k for k, reason in status.items() if reason != 'eligible'})
    protected_frames = {rows[k]['frame_id'] for k in protected}
    eligible = {k: r for k, r in rows.items() if r['final_class_id'] in QUOTAS and status[k] == 'eligible'
        and k not in protected and r['frame_id'] not in protected_frames
        and (k not in history or k in current) and
        (k not in current or unchanged_rectangle(current[k].get('polygon'), r))}
    groups, all_groups, human_groups = defaultdict(list), defaultdict(list), defaultdict(list)
    for k, t in templates.items():
        human_groups[signature(t['row'])].append(k)
    usable, rejected = {}, Counter()
    for key, row in sorted(eligible.items()):
        all_groups[signature(row)].append(key)
        quality, reason = native_quality(row, evidence)
        if reason:
            rejected[f'{row["final_class_id"]}:{reason}'] += 1
            continue
        usable[key] = dict(quality=quality, exact_signature_human_template_keys=human_groups[signature(row)],
            exact_view_human_template_absent=not human_groups[signature(row)],
            no_pose_current_or_history=key not in current and key not in history)
        groups[signature(row)].append(key)
    for sig, keys in groups.items():
        vectors = np.array([patch_vector(evidence, k) for k in keys])
        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(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',
        PROJECT/'pallet/mask_template_transfer.py', PROJECT/'pallet/mask_template_refined.py',
        PROJECT/'pallet/mask_quota_saved_extension.py', PROJECT/'pallet/cluster_targets.py',
        PROJECT/'pallet/pose_review_geometry.py',
        PROJECT/'outputs/pallet_appearance_center_reclassification_v1/targets.jsonl'] + OLD_REQUESTS
    paths += [BASE/name for name in ('manifest.json', 'proposals.jsonl', 'new_proposals.jsonl',
        'template_inventory.json', 'reviews_snapshot.sqlite3', 'gallery_reviews_snapshot.sqlite3')]
    inputs = {str(p.relative_to(PROJECT)): digest(p) for p in paths}
    pools = {c: dict(eligible=sum(r['final_class_id'] == c for r in eligible.values()),
        usable=sum(rows[k]['final_class_id'] == c for k in usable),
        usable_no_pose_current_or_history=sum(rows[k]['final_class_id'] == c and v['no_pose_current_or_history']
            for k, v in usable.items())) for c in QUOTAS}
    return dict(formal=formal, rows=rows, original_rows=original_rows, evidence=evidence,
        manifest=manifest, templates=templates, current=current, history=history, eligible=eligible,
        usable=usable, rejected=dict(rejected), protected=protected, protected_frames=protected_frames,
        inputs=inputs, fingerprints=fingerprints, history_checks=history_checks, pools=pools,
        configs=file_inventory(PROJECT/'configs'), excluded_diagnostic_counts=dict(
            cumulative_frames=378, selected_new_machine_candidates=84, gallery_history_targets=len(gallery_history),
            protected_pose_history_targets=len(special), human_seed_targets=len(human_keys),
            completed_original_request_targets=37, quarantine_targets=len(quarantine),
            protected_frames=len(protected_frames)))


def ranked(data, decisions=None):
    chosen, frames = [], set()
    rows, usable = data['rows'], data['usable']
    for cls, quota in QUOTAS.items():
        sigs, groups, splits = Counter(), Counter(), Counter()
        pool = [k for k in usable if rows[k]['final_class_id'] == cls and
            (decisions is None or (decisions.get(k, {}).get('approved') is True and
                rows[k]['group_id'] not in decisions.get('__excluded_source_groups__', {})))]
        for _ in range(quota):
            options = [k for k in pool if k not in chosen and rows[k]['frame_id'] not in frames]
            if not options:
                break
            def rank(k):
                v, r = usable[k], rows[k]
                # Larger crops contribute to ranking after safety/coverage/diversity;
                # these measurements are not probabilities or quality guarantees.
                score = (.45*(1-v['medoid_mean_squared_patch_distance']/4) + .35*v['quality']['clarity_score'] +
                    .20*min(math.log1p(v['quality']['bbox_area_native_pixels'])/math.log(10001), 1))
                return (not v['no_pose_current_or_history'], not v['exact_view_human_template_absent'],
                    sigs[signature(r)], groups[r['group_id']], splits[r['split']], -score, k)
            key = min(options, key=rank); row = rows[key]
            chosen.append(key); frames.add(row['frame_id'])
            sigs[signature(row)] += 1; groups[row['group_id']] += 1; splits[row['split']] += 1
    return chosen


def montage(root, items, filename, full=False):
    width, height = (680, 580) if full else (680, 240)
    sheet = Image.new('RGB', (2*width, math.ceil(len(items)/2)*height), '#111923')
    draw = ImageDraw.Draw(sheet); font = ImageFont.truetype(str(FONT), 17)
    for i, item in enumerate(items):
        row, key = item['source'], item['target_key']
        x, y = i % 2*width, i//2*height
        draw.text((x+8, y+4), f'{item["request_order"]:02d} Class {row["final_class_id"]} | {key}', font=font, fill='white')
        draw.text((x+8, y+30), f'{row["split"]} | {row["policy_id"]} | pose={item["existing_pose_record"]}', font=font, fill='#b8d6ee')
        with Image.open(root/item['native_image' if full else 'contact_crop']) as image:
            image = image.convert('RGB')
            if full:
                r = row['bbox']; ImageDraw.Draw(image).rectangle((r['x'], r['y'], r['x']+r['width'], r['y']+r['height']), outline='#ffb428', width=1)
            scale = min((width-20)/image.width, (height-65)/image.height)
            image = image.resize((round(image.width*scale), round(image.height*scale)), Image.Resampling.NEAREST)
            sheet.paste(image, (x+10, y+60))
    sheet.save(root/filename)


def review():
    require(not (OUT/'manifest.json').exists(), 'Never overwrite a sealed package')
    require(not OUT.exists() or (OUT/'internal/review/shortlist.jsonl').exists(), 'Unknown staging directory')
    data = prepare()
    decisions_path = OUT/'internal/source_visual_decisions.json'
    if decisions_path.exists():
        decisions = read_json(decisions_path)
        data['usable'] = {k: v for k, v in data['usable'].items() if decisions.get(k, {}).get('approved') is not False
            and data['rows'][k]['group_id'] not in decisions.get('__excluded_source_groups__', {})}
    keys = ranked(data)
    root = OUT/'internal/review'; (root/'cases').mkdir(parents=True, exist_ok=True); (root/'images').mkdir(exist_ok=True)
    shortlist = []
    for order, key in enumerate(keys, 1):
        row = data['rows'][key]
        render_case(row, data['evidence'], root/'cases'/f'{key}.png')
        shutil.copyfile(data['formal']/row['image'], root/'images'/f'{key}.png')
        shortlist.append(dict(target_key=key, source=row, request_order=order,
            existing_pose_record=key in data['current'], native_image=f'images/{key}.png',
            contact_crop=f'cases/{key}.png', **data['usable'][key]))
    write_jsonl(root/'shortlist.jsonl', shortlist)
    for start in range(0, len(shortlist), 6):
        for full in (False, True):
            montage(root, shortlist[start:start+6], f'{"full" if full else "crop"}_{start+1:02d}.png', full)
    write_json(root/'diagnostic.json', dict(pools=data['pools'], rejections=data['rejected'],
        exclusions=data['excluded_diagnostic_counts'], selected=len(keys), class_counts=dict(Counter(data['rows'][k]['final_class_id'] for k in keys))))
    print(json.dumps(read_json(root/'diagnostic.json'), ensure_ascii=False, indent=2))


def page(requests, data, pose_url):
    esc = html.escape
    counts = Counter(r['class_id'] for r in requests)
    table = ''.join(f'<tr><td>{c}</td><td>{n}</td><td>{100-n}</td><td>{counts[c]}</td></tr>' for c, n in BASE_COUNTS.items())
    cards = []
    for r in requests:
        key, s = r['target_key'], r['source']
        preserve = (f'已有原始矩形位姿保存记录，最新修订 r{r["existing_pose_revision"]}，历史 {len(r["pose_history_flags"])} 条；'
            '全部历史掩膜未改动。必须保留当前位姿、选中标尺、面与传感器设置，只有人工主动决定时才可修改；不要静默覆盖。'
            if r['existing_pose_record'] else '无既有位姿当前保存记录或事件历史。')
        ref = (f'严格同类／划分／策略／视角的已保存人工参考：{r["closest_human_reference_key"]}；来源 {r["closest_human_reference_store"]}，'
            f'修订 r{r["closest_human_reference_revision"]}。只提供参考键，不复制顶点、不生成提案。' if r['closest_human_reference_key'] else
            '暂无严格同类／划分／策略／视角人工参考；请依据可见结构决定轮廓，不从其他划分借用。')
        cards.append(f'''<article id="{key}"><h2>{r['request_order']:02d} · Class {r['class_id']} · 待人工描绘</h2>
<p><code>{key}</code></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 class="notice">{esc(preserve)}</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>
<figure><img src="{r['contact_crop']}" alt="Class {r['class_id']} 原生局部与原始矩形"><figcaption>橙线仅为原始矩形，不是有意义的掩膜真值；本包没有轮廓提案。</figcaption></figure>
<p>逐张图像复查：{esc(r['source_visual_review_zh'])}（助手可描绘性检查，不是人工类别或真值确认。）</p>
<p>原生框 {s['bbox']['width']:.1f} × {s['bbox']['height']:.1f} 像素；同组合清晰图块代表性排名 {r['medoid_rank']}/{r['usable_compatible_neighbor_count']+1}；
严格兼容其他帧 {r['compatible_neighbor_count']}，清晰其他帧 {r['usable_compatible_neighbor_count']}。数量及评分不是成功率。</p>
<p>{esc(ref)}</p><p>候选类别未人工确认；原分类复核标记：<code>{esc(', '.join(r['classification_review_flags']) or '无附加标记')}</code>。</p>
<details><summary>完整原生图像</summary><img loading="lazy" src="{r['native_image']}" alt="完整原生强度图像"></details>
<p>needs_manual_tracing · 未激活 · 不计入378。仅在轮廓真实可见时人工描绘并保存；类别可疑、遮挡或边界模糊时暂缓。
有效人工模板需超过四个顶点，但不可为凑数添加点；拓扑完全由人工依据实际结构决定。</p></article>''')
    limits = '；'.join(f'Class {c}：清晰池 {v["usable"]}，其中无位姿当前及历史 {v["usable_no_pose_current_or_history"]}' for c, v in data['pools'].items())
    return f'''<!doctype html><html lang="zh-CN"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
<title>每类100帧目标 · 独立人工模板请求 · 未激活</title><style>
@font-face{{font-family:RequestSans;src:url('report-font.otf')}}*{{box-sizing:border-box}}body{{font:16px/1.65 RequestSans,sans-serif;background:#111923;color:#edf2f7;max-width:1200px;margin:auto;padding:20px}}
a{{color:#8ed7ff}}code{{font-family:monospace;user-select:all}}article,.notice{{border:1px solid #536479;border-radius:10px;padding:16px;margin:18px 0;background:#192432}}
p,code,li,h1,h2{{overflow-wrap:anywhere}}img{{max-width:100%;height:auto;display:block;margin:10px auto}}figure{{margin:12px 0}}figure img{{width:100%;image-rendering:pixelated}}figcaption{{color:#bdcbd8}}
.action{{display:inline-block;padding:8px 12px;border-radius:6px;background:#17496b}}table{{border-collapse:collapse;width:100%;table-layout:fixed}}td,th{{border:1px solid #536479;padding:6px;overflow-wrap:anywhere}}
@media(max-width:480px){{body{{padding:10px;font-size:15px}}article,.notice{{padding:10px}}td,th{{font-size:13px}}}}
</style></head><body><h1>每类100帧目标：{len(requests)}张独立人工模板请求</h1>
<div class="notice"><strong>建议先完成第七版独立核验并提供已验证的在线地址，默认查看新增84张机器候选；用户复查后，再按需要启动本独立清单。本包没有激活任何配置或服务。</strong>
<p>基准生成结果为378个不同帧：251份已保存人工轮廓、43份历史待复核机器候选、84份新增待复核机器候选。
基准 manifest 状态仍为待独立核验；本包不替代主会话独立验封，也不宣称已在线发布。已保存人工轮廓也不等于已确认真值。</p>
<p><strong>这{len(requests)}张人工模板不计入378直到保存。</strong>人工保存后仍须重新核验来源、修订、不同帧及原划分，才能在后续新版本计入每类100目标；不自动成为真值或训练数据。</p></div>
<table><tr><th>类别</th><th>基准生成帧数</th><th>距100缺额</th><th>本次请求</th></tr>{table}</table>
<p>Class 2 已达到100帧覆盖，本次没有请求；这不代表Class 2已有100份人工真值。原24张及随后13张请求均已完成，本清单没有重复包含。</p>
<h2>选择与保护边界</h2><p>排除全部378帧、图册任何当前及历史、位姿实际掩膜改动／删除／暂缓／确认历史、隔离目标、所有人工种子帧及原37个请求帧；同帧其他框也不入选。
新增84张不作种子或人工参考。沿用 annotation_inventory 原始资格判定。优先无任何位姿当前及历史，再补缺失的同类／划分／来源策略／视角人工覆盖，兼顾来源组与划分多样性。
只有同组合清晰图块参与 medoid 排序，结合原生对比度、边缘和较大框面积；这些是排序指标，不是概率。unknown仅与unknown匹配。</p>
<p>{esc(limits)}。无足够全新目标时，仅允许原始矩形、所有历史掩膜未变的已保存位姿记录；每张明确标注当前修订与保留要求。
连续帧不能视作独立场景；没有的新视角或划分不虚构覆盖。</p>
<p>位姿链接来自构建时受管 public_access.json 的当前 public_url 字段；临时隧道可能变化，沿用现有登录方式。本包没有密钥或访问码。</p>
{''.join(cards)}<footer><p>独立待办，不是已完成标注、候选发布、真值或训练集。仅原图和原始矩形；字体许可：<a href="FONT_LICENSE.txt">Noto 字体许可</a>。</p>
<p><a href="{esc(pose_url,quote=True)}">原位姿标注入口</a></p></footer></body></html>'''


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


def build():
    require((OUT/'internal/review/shortlist.jsonl').exists() and not (OUT/'manifest.json').exists(),
        'Stage review first; never overwrite a sealed package')
    data = prepare()
    decisions = read_json(OUT/'internal/source_visual_decisions.json')
    keys = ranked(data, decisions)
    staged = {r['target_key']: r for r in read_jsonl(OUT/'internal/review/shortlist.jsonl')}
    require(all(k in staged and decisions[k].get('crop_inspected') and decisions[k].get('full_image_inspected')
        and decisions[k].get('note_zh') for k in keys), 'Every selected crop and full image needs explicit review')
    before = protected_snapshot(data['formal'])
    require(len(before) == 20768, 'Protected formal inventory differs')
    pose_url = read_json(ACCESS)['public_url'].rstrip('/')
    require(pose_url.startswith('https://') and '?' not in pose_url, 'Unexpected managed public URL')
    (OUT/'images').mkdir(); (OUT/'cases').mkdir()
    requests = []
    for order, key in enumerate(keys, 1):
        row, v, old = data['rows'][key], data['usable'][key], data['current'].get(key)
        refs = v['exact_signature_human_template_keys']
        refkey = min(refs, key=lambda k: (float(np.sum((patch_vector(data['evidence'], key)-patch_vector(data['evidence'], k))**2)), k)) if refs else None
        ref = data['templates'].get(refkey)
        source = dict(row, image_sha256=digest(data['formal']/row['image']),
            formal_manifest_sha256=data['manifest']['formal_manifest_sha256'],
            classification_sha256=data['manifest']['classification_sha256'],
            classification_row_sha256=sha(data['original_rows'][key]),
            formal_source_record_sha256=sha(data['evidence'].sources[row['frame_id']]))
        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['exact_view_human_template_absent'] else '补充已有兼容组合的结构变化；')
        reason += f'同组合清晰图块代表性排名 {v["medoid_rank"]}/{v["usable_compatible_neighbor_count"]+1}，兼顾来源组、划分、原生清晰度和框面积。'
        if old:
            reason += '该类清晰池中的无位姿当前及历史目标不足，采用明确标记的原始矩形位姿记录，仅作人工请求。'
        requests.append(dict(schema='manual_mask_template_request_v1', request_order=order, target_key=key,
            class_id=row['final_class_id'], class_identity=dict(candidate_class=row['final_class'],
                final_class_id=row['final_class_id'], human_class_confirmed=False,
                classification_row_sha256=source['classification_row_sha256']),
            source=source, original_classification_row=data['original_rows'][key],
            source_label_kind='ORIGINAL_RECTANGLE', original_rectangle=rectangle(row),
            status='needs_manual_tracing', activation_state='independent_pending_not_activated',
            reason=reason, reason_zh=reason, source_visual_review_zh=decisions[key]['note_zh'],
            source_visual_review_kind='assistant_source_clarity_review_NOT_human_class_or_GT_confirmation',
            classification_review_flags=row.get('classification_review_flags', []),
            existing_pose_record=old is not None, existing_pose_revision=old['revision'] if old else 0,
            existing_pose_payload_sha256=sha(old) if old else None,
            existing_pose_current_payload=old,
            existing_pose_geometry_sha256=sha({k: old.get(k) for k in ('pose', 'ruler', 'sensor', 'selected_faces', 'exclusions')}) if old else None,
            pose_history_present=bool(data['history'].get(key)), pose_history_flags=data['history'].get(key, []),
            latest_pose_event_revision=max((e['revision'] for e in data['history'].get(key, [])), default=0),
            all_pose_history_masks_unmodified=True, preserve_existing_pose_until_intentional_human_edit=True,
            preserve_current_selected_ruler_sensor_faces_and_revision=True,
            existing_pose_revision_is_expected_not_overwrite_authorization=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 frames; not transfer success or probability',
            exact_view_human_template_absent=v['exact_view_human_template_absent'],
            diagnostic_compatible_template_ids=refs, exact_signature_human_template_keys=refs,
            medoid_rank=v['medoid_rank'], medoid_mean_squared_patch_distance=v['medoid_mean_squared_patch_distance'],
            image_quality=v['quality'], quality_metrics_are_not_probabilities=True,
            closest_human_reference_key=refkey, closest_human_reference_store=ref['origin'] if ref else None,
            closest_human_reference_revision=(ref.get('human_polygon_revision') if ref else None),
            closest_human_reference_payload_sha256=(ref.get('gallery_review', {}).get('payload_sha256') or ref.get('current_payload_sha256')) if ref else None,
            requested_required_vertex_count=None, topology_must_be_manually_determined=True,
            minimum_manual_template_vertices=5, reference_vertices_copied=False,
            pose_annotation_url=pose_url+'/?target='+key, native_image=f'images/{key}.png',
            contact_crop=f'cases/{key}.png', crop_native_bounds=bounds,
            human_mask_confirmed=False, human_pose_confirmed=False, accepted_candidate=False,
            ground_truth_eligible=False, automatic_training_eligible=False, robot_command_eligible=False,
            production_saved=False, counts_as_completed_annotation=False, counts_toward_378=False, generated_polygons=0))
    write_jsonl(OUT/'requests.jsonl', requests)
    text = page(requests, data, pose_url); (OUT/'report_zh.html').write_text(text)
    build_font(text)
    montage(OUT, requests, 'selection_contact.png')
    write_jsonl(OUT/'selection_ranking.jsonl', [dict(target_key=k, class_id=data['rows'][k]['final_class_id'], **v)
        for k, v in sorted(data['usable'].items())])
    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, 'Protected formal files changed')
    require(all(digest(PROJECT/name) == value for name, value in data['inputs'].items()), 'Frozen input changed')
    require(file_inventory(PROJECT/'configs') == data['configs'], 'Configuration changed concurrently')
    require(all(digest(data['formal']/name) == value for name, value in data['evidence'].used.items()), 'Evidence image changed')
    require(read_json(ACCESS)['public_url'].rstrip('/') == pose_url, 'Managed pose URL changed')
    for kind, live, name in [('pose', POSE, 'reviews_snapshot.sqlite3'), ('gallery', GALLERY, 'gallery_reviews_snapshot.sqlite3')]:
        verify_history_preserved(live, BASE/name)
        require(database_fingerprint(live) == data['fingerprints'][kind], 'Live reviews changed during build')
    require(len(keys) == len({r['source']['frame_id'] for r in requests}), 'Duplicate frame')
    for r in requests:
        key = r['target_key']
        require(key in data['eligible'] and key not in data['protected'] and r['source']['frame_id'] not in data['protected_frames'], 'Protected target selected')
        require(r['original_rectangle'] == rectangle(data['rows'][key]) and len(r['original_rectangle']) == 4 and
            digest(OUT/r['native_image']) == r['source']['image_sha256'], 'Source image/rectangle differs')
        if r['existing_pose_record']:
            require(unchanged_rectangle(r['existing_pose_current_payload']['polygon'], data['rows'][key]) and
                not any(e['mask_modified'] or e['state'] in ('deleted', 'deferred') or e['human_mask_confirmed'] or
                    e['human_pose_confirmed'] for e in r['pose_history_flags']), 'Existing pose history not safely original')
        if r['closest_human_reference_key']:
            require(signature(data['rows'][r['closest_human_reference_key']]) == signature(data['rows'][key]), 'Cross-signature reference')
    names = ['report_zh.html', 'report-font.otf', 'FONT_LICENSE.txt'] + [r[f] for r in requests for f in ('native_image', 'contact_crop')]
    public = {name: digest(OUT/name) for name in sorted(names)}
    require(len(public) == 3+2*len(requests) and all(re.fullmatch(
        r'(report_zh\.html|report-font\.otf|FONT_LICENSE\.txt|(?:cases|images)/[0-9a-f]{24}\.png)', n) for n in public), 'Public allowlist differs')
    require(not list(OUT.rglob('*.sqlite*')) and not list(OUT.rglob('*.db')) and not (OUT/'masks').exists()
        and not (OUT/'labelme').exists(), 'Unexpected database or generated mask')
    counts = Counter(r['class_id'] for r in requests)
    now = datetime.now(timezone.utc).isoformat()
    manifest = dict(schema='manual_mask_template_requests_v1', state='verified_static_manual_tracing_requests',
        activation_state='independent_pending_not_activated', created_at=now, request_count=len(requests),
        class_counts=dict(counts), requested_class_counts=QUOTAS,
        unmet_request_counts={c: QUOTAS[c]-counts[c] for c in QUOTAS}, class_selection_pools=data['pools'],
        baseline_directory=str(BASE.relative_to(PROJECT)), baseline_manifest_state=data['manifest']['state'],
        baseline_distinct_frames=378, baseline_class_counts=BASE_COUNTS, baseline_gaps={c: 100-n for c,n in BASE_COUNTS.items()},
        baseline_saved_human=251, baseline_old_pending=43, baseline_new_pending=84,
        independent_baseline_verification_or_online_activation_claimed=False,
        recommendation='First independently seal and publish v7 with new84 default; review those, then use these requests if necessary',
        requests_sha256=digest(OUT/'requests.jsonl'), existing_pose_request_count=sum(r['existing_pose_record'] for r in requests),
        no_pose_current_or_history_request_count=sum(not r['existing_pose_record'] and not r['pose_history_present'] for r in requests),
        missing_exact_human_compatibility_request_count=sum(r['exact_view_human_template_absent'] for r in requests),
        selected_group_counts=dict(Counter(r['source']['group_id'] for r in requests)),
        selected_split_counts=dict(Counter(r['source']['split'] for r in requests)),
        selected_policy_counts=dict(Counter(r['source']['policy_id'] for r in requests)),
        selected_view_counts=dict(Counter(r['source']['viewpoint_candidate'] for r in requests)),
        excluded_diagnostic_counts=data['excluded_diagnostic_counts'], image_quality_rejections=data['rejected'],
        direct_human_reference_inventory_count=256, new_candidates_used_as_seeds_or_references=0,
        selection_priority=['no_pose_current_or_history', 'missing_exact_class_split_policy_view_human_reference',
            'signature_diversity', 'group_diversity', 'split_diversity', 'medoid_clarity_larger_area', 'individual_visual_review'],
        ranking_score='0.45*(1-mean_squared_distance/4)+0.35*clarity+0.20*min(log1p(native_bbox_area)/log(10001),1)',
        medoid_objective='Mean squared distance between 64x28 zero-mean unit-L2 patches, same exact signature, different frame; not probabilities',
        native_quality_gates=dict(min_width=50,min_height=14,min_area=1000,min_margin=1,min_p95_p05=35,
            min_bright_fraction=.12,max_saturated_fraction=.65,min_gradient_fraction=.025),
        compatibility_policy='Exact class/split/source_policy/view; unknown matches unknown only',
        pose_public_url=pose_url, pose_public_url_authority='managed public_access.json public_url, current at build',
        frozen_input_sha256=data['inputs'], configuration_sha256=data['configs'],
        database_logical_fingerprints=data['fingerprints'], latest_snapshot_live_history_comparison=data['history_checks'],
        protected_formal_files_verified=len(before), evidence_images_verified=len(data['evidence'].used),
        source_visual_decisions_sha256=digest(OUT/'internal/source_visual_decisions.json'),
        production_database_writes=0, configuration_writes=0, service_writes=0, publication_changes=0,
        generated_polygons=0, completed_manual_labels=0, accepted_candidates=False, human_confirmation_inferred=False,
        counts_toward_baseline=0, ground_truth_eligible=False, automatic_training_eligible=False, public_assets=public)
    write_json(OUT/'manifest.json', manifest)
    verification = dict(schema='manual_mask_template_request_verification_v1', state='passed', verified_at=now,
        request_count=len(requests), class_counts=dict(counts), manifest_sha256=digest(OUT/'manifest.json'),
        requests_sha256=digest(OUT/'requests.jsonl'), public_assets=public, public_asset_count=len(public),
        all_request_targets_live_eligible=True, latest_quota_snapshots_match_live_logically=True,
        all_frozen_history_event_bytes_preserved=True, existing_pose_preservation_explicit=True,
        all_source_identities_and_hashes_verified=True, native_images_byte_identical_to_formal_sources=True,
        all_selected_crops_and_full_source_images_inspected=True, only_original_rectangle_annotations=True,
        no_generated_polygons_or_reference_vertex_proposals=True, no_protected_frames_selected=True,
        all_378_baseline_frames_and_37_old_requests_excluded=True, no_new84_seeds_or_references=True,
        exact_same_class_split_policy_view_references=True, no_private_databases_in_output=True,
        protected_formal_files_unchanged=True, active_config_files_unchanged=True,
        all_report_Chinese_present=True, pose_url_current_at_verification=True,
        production_database_writes=0, configuration_writes=0, service_writes=0, publication_changes=0,
        activated=False, generated_polygons=0, completed_manual_labels=0, ground_truth_eligible=False,
        independent_baseline_verification_claimed=False)
    write_json(OUT/'verification.json', verification)
    require(all(digest(OUT/n) == value for n, value in public.items()), 'Public asset changed')
    (OUT/'README.md').write_text('# 每类100帧：独立人工模板请求（未激活）\n\n'
        f'{len(requests)}张待描绘，不计入378直到人工保存并重新核验。报告 `report_zh.html`；任务 `requests.jsonl`。\n'
        '基准378=251已保存人工+43旧待核对+84新待核对，非500、非真值；应先核验并发布第七版新增84张供用户复查。\n'
        '只允许 verification.json 的 public_assets 对外提供；51个文件（24请求时）。内部联系表及元数据不可公开。\n'
        '无配置、服务、数据库写入；没有生成轮廓、接受候选或顶点提案。已有位姿记录需保留原位姿、标尺及修订。\n')
    write_json(OUT/'artifact_hashes.json', file_inventory(OUT))
    print(json.dumps(dict(state='passed', request_count=len(requests), class_counts=dict(counts),
        existing_pose_requests=manifest['existing_pose_request_count'], public_asset_count=len(public),
        manifest_sha256=digest(OUT/'manifest.json'), verification_sha256=digest(OUT/'verification.json'),
        diagnostics=data['pools'], activated=False), ensure_ascii=False, indent=2))


if __name__ == '__main__':
    parser = argparse.ArgumentParser(description=__doc__)
    mode = parser.add_mutually_exclusive_group(required=True)
    mode.add_argument('--review', action='store_true')
    mode.add_argument('--build', action='store_true')
    args = parser.parse_args()
    review() if args.review else build()
