"""Stage and seal the first representative manual tasks for 17 remaining classes.

Only a fresh worklist is written. Original rectangles are references, not masks;
live review databases, protected source files and active configurations are not edited.
"""
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 math
import os
from pathlib import Path
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,snapshot_database,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

CLASSES=(3,4,5,6,7,8,11,12,13,14,16,17,18,19,20,21,22)
BASE=PROJECT/'outputs/pallet_mask_quota_100_complete_v1'
DEFAULT=PROJECT/'outputs/pallet_mask_remaining_requests_v1'
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')
SOURCES=PROJECT/'outputs/pallet_mask_remaining_classes_v1'
OLD_REQUEST_DIRS=('pallet_mask_template_requests_v1','pallet_mask_class10_manual_supplement_v2',
    'pallet_mask_quota_100_requests_v2','pallet_mask_quota_100_final_requests_v2')


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


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


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


def protected_history(current,events,rows):
    protected=set()
    for key,value in list(current.items())+[(k,v) for _,k,_,_,v in events]:
        if ((value.get('polygon') and not unchanged_rectangle(value['polygon'],rows[key])) or
                value.get('state') in ('deleted','deferred') or
                any(value.get(f) for f in ('human_mask_confirmed','human_pose_confirmed','automatic_training_eligible','robot_command_eligible'))):
            protected.add(key)
    return protected


def medoid_statistics(keys,vectors,rows):
    """Exact average squared patch distance, excluding targets in the same frame."""
    array=np.asarray(vectors,np.float64);total=array.sum(axis=0);squared=np.sum(array*array,axis=1)
    frame_indices=defaultdict(list)
    for i,key in enumerate(keys):frame_indices[rows[key]['frame_id']].append(i)
    result={}
    for frame,indices in frame_indices.items():
        count=len(keys)-len(indices)
        for i in indices:
            if count:
                other_sum=total-array[indices].sum(axis=0)
                mean_squared=(squared.sum()-squared[indices].sum())/count
                distance=max(0.,float(squared[i]+mean_squared-2*array[i]@other_sum/count))
            else:distance=0.
            result[keys[i]]=distance
    return result


def select_tasks(rows,usable,per_class,decisions=None,approved_only=False):
    decisions=decisions or {};chosen=[];frames=set()
    order=sorted(CLASSES,key=lambda c:(len({r['frame_id'] for r in rows.values() if r['final_class_id']==c}),c))
    for cls in order:
        sigs,groups,splits=Counter(),Counter(),Counter()
        for _ in range(per_class):
            options=[k for k in usable if rows[k]['final_class_id']==cls and rows[k]['frame_id'] not in frames
                and decisions.get(k,{}).get('approved') is not False
                and rows[k]['group_id'] not in decisions.get('__excluded_class_groups__',{}).get(str(cls),[])
                and (str(cls) not in decisions.get('__preferred_class_native_size__',{}) or
                    rows[k]['size']==decisions['__preferred_class_native_size__'][str(cls)])
                and (not approved_only or decisions.get(k,{}).get('approved') is True)]
            if not options:break
            def rank(key):
                v,r=usable[key],rows[key]
                score=(.30*(1-v['medoid_mean_squared_patch_distance']/4)+.30*v['quality']['clarity_score']+
                    .20*min(math.log1p(v['quality']['bbox_area_native_pixels'])/math.log(10001),1)+
                    .20*min(math.log1p(v['usable_compatible_neighbor_count'])/math.log(101),1))
                return (not v['no_pose_current_or_history'],sigs[signature(r)],groups[r['group_id']],
                    splits[r['split']],not v['exact_view_human_template_absent'],-score,key)
            key=min(options,key=rank);r=rows[key];chosen.append(key);frames.add(r['frame_id'])
            sigs[signature(r)]+=1;groups[r['group_id']]+=1;splits[r['split']]+=1
    return sorted(chosen,key=lambda k:(rows[k]['final_class_id'],k))


def prepare(out,create=False,per_class=3):
    cv2.setNumThreads(1)
    parent=read_json(BASE/'manifest.json');seal=read_json(BASE/'verification.json')
    require(seal['state']=='passed' and seal['publication_version']==9 and seal['proposals_verified']==500 and
        seal['proposals_sha256']==digest(BASE/'proposals.jsonl') and seal['manifest_sha256']==digest(BASE/'manifest.json'),
        'Expected verified 500-frame baseline')
    formal,rows,evidence=load_formal_evidence(parent)
    original_rows={r['target_key']:r for r in read_jsonl(PROJECT/'outputs/pallet_appearance_center_reclassification_v1/targets.jsonl')}
    meta_path=out/'input_manifest.json'
    if create:
        require(not out.exists(),'Use a fresh worklist output; preserve existing evidence');out.mkdir()
        snapshot_database(POSE,out/'reviews_snapshot.sqlite3');snapshot_database(GALLERY,out/'gallery_reviews_snapshot.sqlite3')
        write_json(out/'protected_formal_before.json',protected_snapshot(formal))
        meta=dict(schema='remaining_classes_worklist_inputs_v1',per_class=per_class,classes=list(CLASSES),
            baseline_directory=str(BASE.relative_to(PROJECT)),parent_file_inventory=file_inventory(BASE),
            baseline_manifest_sha256=digest(BASE/'manifest.json'),baseline_verification_sha256=digest(BASE/'verification.json'),
            pose_snapshot_sha256=digest(out/'reviews_snapshot.sqlite3'),gallery_snapshot_sha256=digest(out/'gallery_reviews_snapshot.sqlite3'),
            configuration_sha256=file_inventory(PROJECT/'configs'),code_sha256=digest(__file__),
            original_request_files={str((PROJECT/'outputs'/d/'requests.jsonl').relative_to(PROJECT)):
                digest(PROJECT/'outputs'/d/'requests.jsonl') for d in OLD_REQUEST_DIRS},
            pose_public_url=read_json(ACCESS)['public_url'].rstrip('/'))
        write_json(meta_path,meta)
    else:meta=read_json(meta_path);per_class=meta['per_class']
    require(file_inventory(BASE)==meta['parent_file_inventory'],'The 500-frame baseline changed')
    require(file_inventory(PROJECT/'configs')==meta['configuration_sha256'],'Configuration changed during staging')
    for name,live in (('reviews_snapshot.sqlite3',POSE),('gallery_reviews_snapshot.sqlite3',GALLERY)):
        verify_history_preserved(live,out/name)
        require(database_fingerprint(live)==database_fingerprint(out/name,True),'Human review changed; freeze a fresh worklist instead of overwriting')
    with closing(readonly(out/'reviews_snapshot.sqlite3',True)) as db:
        current,templates,status=annotation_inventory(db,rows)
        current_raw=dict(db.execute('SELECT target_key,payload FROM annotations'))
        events=[(i,k,r,raw,read_json_value(raw)) for i,k,r,raw in db.execute('SELECT id,target_key,revision,payload FROM events ORDER BY id')]
    with closing(readonly(out/'gallery_reviews_snapshot.sqlite3',True)) as db:
        gallery_history={k for k, in db.execute('SELECT target_key FROM reviews')}|{k for k, in db.execute('SELECT target_key FROM events')}
    history=defaultdict(list)
    for i,k,rev,raw,v in events:
        history[k].append(dict(event_id=i,revision=rev,event_kind=v.get('event_kind'),payload_raw_sha256=hashlib.sha256(raw.encode()).hexdigest(),
            state=v.get('state'),original_rectangle=unchanged_rectangle(v.get('polygon'),rows[k]),
            mask_modified=bool(v.get('polygon')) and not unchanged_rectangle(v['polygon'],rows[k]),
            human_mask_confirmed=bool(v.get('human_mask_confirmed')),human_pose_confirmed=bool(v.get('human_pose_confirmed'))))
    base=read_jsonl(BASE/'proposals.jsonl');old_requests=[r for d in OLD_REQUEST_DIRS for r in read_jsonl(PROJECT/'outputs'/d/'requests.jsonl')]
    protected=(set(QUARANTINE)|{p['target_key'] for p in base}|gallery_history|protected_history(current,events,rows)|
        {r['target_key'] for r in old_requests}|{k for k,v in status.items() if v!='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 CLASSES and k not in protected and
        r['frame_id'] not in protected_frames and status[k]=='eligible' and
        (k not in history or k in current) and all(e['original_rectangle'] for e in history[k]) and
        (k not in current or unchanged_rectangle(current[k].get('polygon'),r))}
    all_groups,groups,refs=defaultdict(list),defaultdict(list),defaultdict(list)
    for k,t in templates.items():refs[signature(rows[k])].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=refs[signature(row)],
            exact_view_human_template_absent=not refs[signature(row)],no_pose_current_or_history=key not in current and not history.get(key))
        groups[signature(row)].append(key)
    for sig,keys in groups.items():
        distances=medoid_statistics(keys,[patch_vector(evidence,k) for k in keys],rows)
        for rank,key in enumerate(sorted(keys,key=lambda k:(distances[k],k)),1):
            frame=rows[key]['frame_id']
            usable[key].update(medoid_rank=rank,medoid_mean_squared_patch_distance=distances[key],
                compatible_neighbor_count=len({rows[k]['frame_id'] for k in all_groups[sig] if rows[k]['frame_id']!=frame}),
                usable_compatible_neighbor_count=len({rows[k]['frame_id'] for k in keys if rows[k]['frame_id']!=frame}))
    pools={c:dict(targets=sum(r['final_class_id']==c for r in rows.values()),
        distinct_frames=len({r['frame_id'] for r in rows.values() if r['final_class_id']==c}),
        distinct_frames_outside_baseline=len({r['frame_id'] for r in rows.values() if r['final_class_id']==c}-
            {p['source']['frame_id'] for p in base}),
        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_history=sum(rows[k]['final_class_id']==c and v['no_pose_current_or_history'] for k,v in usable.items())) for c in CLASSES}
    return dict(meta=meta,formal=formal,rows=rows,original_rows=original_rows,evidence=evidence,current=current,
        current_raw=current_raw,history=history,templates=templates,eligible=eligible,usable=usable,pools=pools,
        protected=protected,protected_frames=protected_frames,rejected=dict(rejected),per_class=per_class,parent=parent)


def read_json_value(raw):
    import json
    return json.loads(raw)


def contact(out,records,name,full=False):
    width,height=680,520 if full else 270
    image=Image.new('RGB',(width*2,height*math.ceil(len(records)/2)),'#111923');draw=ImageDraw.Draw(image)
    font=ImageFont.truetype(str(FONT),16)
    for i,r in enumerate(records):
        x,y=(i%2)*width,(i//2)*height;s=r['source'];key=r['target_key']
        draw.text((x+8,y+4),f'{r["request_order"]:02d} Class {s["final_class_id"]} {key}',font=font,fill='white')
        draw.text((x+8,y+28),f'{s["split"]} | {s["policy_id"]} | pose={r["existing_pose_record"]}',font=font,fill='#c3d8eb')
        with Image.open(out/r['native_image' if full else 'contact_crop']) as source:
            source=source.convert('RGB')
            if full:
                box=s['bbox'];ImageDraw.Draw(source).rectangle((box['x'],box['y'],box['x']+box['width'],box['y']+box['height']),outline='#ffb428',width=1)
            scale=min((width-20)/source.width,(height-60)/source.height)
            source=source.resize((round(scale*source.width),round(scale*source.height)),Image.Resampling.NEAREST)
            image.paste(source,(x+8,y+55))
    image.save(out/name)


def stage(out,per_class):
    data=prepare(out,not out.exists(),per_class)
    require(not (out/'manifest.json').exists(),'Never overwrite a sealed worklist')
    decision_path=out/'internal/source_visual_decisions.json'
    decisions=read_json(decision_path) if decision_path.exists() else {}
    keys=select_tasks(data['rows'],data['usable'],data['per_class'],decisions)
    root=out/'internal/review';(root/'cases').mkdir(parents=True,exist_ok=True);(root/'images').mkdir(exist_ok=True)
    records=[]
    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')
        records.append(dict(target_key=key,request_order=order,source=row,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',records)
    for start in range(0,len(records),6):
        for full in (False,True):contact(root,records[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'],selected=len(records),
        class_counts=dict(Counter(r['source']['final_class_id'] for r in records)),
        selected_no_pose=sum(not r['existing_pose_record'] for r in records),
        selected_splits=dict(Counter(r['source']['split'] for r in records))))
    print((root/'diagnostic.json').read_text(),flush=True)


def page(requests,data):
    e=html.escape;options=''.join(f'<option>{c}</option>' for c in CLASSES)
    table=''.join(f'<tr><td>{c}</td><td>{v["distinct_frames"]}</td><td>{min(v["distinct_frames"],100)}</td><td>{sum(r["class_id"]==c for r in requests)}</td></tr>' for c,v in data['pools'].items())
    cards=[]
    for r in requests:
        key,s=r['target_key'],r['source']
        protection=(f'已有原矩形位姿记录 r{r["existing_pose_revision"]}，请先查看并保留原位姿、选面、标尺、传感器设置；只有人工主动决定才修改。历史不覆盖。'
            if r['existing_pose_record'] else '无既有位姿保存记录或事件历史；本任务仅提供原图及原矩形。')
        cards.append(f'''<article id="{key}" data-class="{r['class_id']}"><h2>{r['request_order']:02d} · Class {r['class_id']} · 待人工描绘</h2>
<p><a class="action" target="_blank" rel="noopener" href="{e(r['pose_annotation_url'],quote=True)}">打开标注并保存掩膜</a> <code>{key}</code></p>
<p>{e(protection)}</p><p>来源：{e(s['frame_id'])}<br>原划分：{e(s['split'])} · 观察面：{e(str(s.get('viewpoint_candidate')))}<br>策略：{e(s['policy_id'])}<br>采集组：{e(s['group_id'])}</p>
<figure><img loading="lazy" src="{r['contact_crop']}" alt="Class {r['class_id']} 原生局部及原矩形"><figcaption>橙框仅是原始矩形，不是已完成轮廓。</figcaption></figure>
<p>来源可描绘性检查：{e(r['source_visual_review_zh'])}（助手检查，不等于人工类别或GT确认。）</p>
<p>严格同类／同划分／同传感器／同观察面清晰邻居：{r['usable_compatible_neighbor_count']} 张，非匹配成功率；保存后不承诺邻居增长。</p>
<p>分类复核提示：{e(', '.join(r['classification_review_flags']) or '无附加标记')}；类别仍为外观候选，不是型号真值。</p>
<details><summary>完整原生图像</summary><img loading="lazy" src="{r['native_image']}" alt="完整原生图像"></details>
<p>沿真实可见结构描绘；四点有效轮廓保留四点，不强行增点。保存前不计入已完成标签。类别可疑或遮挡严重请暂缓。</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>剩余17类 · 首批人工掩膜任务</title><style>
@font-face{{font-family:RequestSans;src:url('report-font.otf')}}*{{box-sizing:border-box}}body{{background:#111923;color:#edf2f7;font:16px/1.65 RequestSans,sans-serif;max-width:1280px;padding:20px;margin:auto}}a{{color:#8ed7ff}}p,code,h1,h2{{overflow-wrap:anywhere}}article,.notice{{padding:16px;margin:18px 0;border:1px solid #536479;border-radius:10px;background:#192432}}img{{display:block;max-width:100%;height:auto}}figure{{margin:12px 0}}figure img{{width:100%;image-rendering:pixelated}}figcaption{{color:#bdcbd8}}.action{{display:inline-block;background:#17496b;border-radius:6px;padding:9px}}select{{font:inherit;padding:6px}}table{{width:100%;border-collapse:collapse;table-layout:fixed}}td,th{{border:1px solid #536479;padding:6px;overflow-wrap:anywhere}}[hidden]{{display:none!important}}@media(max-width:480px){{body{{padding:10px;font-size:15px}}article,.notice{{padding:10px}}th,td{{font-size:13px}}}}</style></head><body>
<h1>剩余17类 · 首批{len(requests)}张人工掩膜任务</h1><div class="notice"><strong>每类先补充{data['per_class']}张代表性人工模板；这些是待描绘任务，不是已经完成的标签。</strong>
<p>目标类别：3–8、11–14、16–22。最终按每类100张不同图像推进。Class 19现有96张不同图像，其中4张已用于原500张；沿用全局图像去重后最多剩92张，当前数据不能凑到100张。其它跨类别同帧、保护历史或不可描绘来源还可能降低可用上限。</p>
<p>已有五类500张图册保持不变：<a href="/?revision=9">查看原500张图册</a>。此前45张无需修改复核已登记，不重复请求。</p>
<p>优先复用真实已保存人工轮廓，再用本批保存修订按原严格门槛扩展。未经人工保存的机器候选不递归作模板；配准与边界门槛不降低。</p>
<p>允许真实四点轮廓计直接人工覆盖，但不作超过四点传播模板；不能只保存原矩形或添无意义顶点。所有结果仍是研究草稿，不自动确认GT，不进入自动训练或机器人控制。</p>
<p>原位姿记录、选面、标尺、轴与快捷键保持。请沿原访问码登录，保存成功后再换图；原图、PCD、正式划分、原GT与全部历史不覆盖。</p></div>
<p>任务须经独立验收后上线，未激活版本不作为在线待办；每项实际保存前不计完成。</p>
<table><tr><th>类别</th><th>现有不同图像</th><th>原始数量上限（至100）</th><th>本批待描绘</th></tr>{table}</table>
<p>筛选类别 <select id="request-filter"><option value="">全部</option>{options}</select> <span id="request-count">{len(requests)}</span> 张</p>
{''.join(cards)}<script>const f=document.querySelector('#request-filter');f.addEventListener('change',()=>{{let n=0;for(const a of document.querySelectorAll('article')){{a.hidden=!!f.value&&a.dataset.class!==f.value;if(!a.hidden)n++;}}document.querySelector('#request-count').textContent=n;}});</script>
<footer><p>原生强度、尺寸、边缘清晰度与同组图块代表性用于任务排序，不是正确率。局部和完整原图均已逐项检查可描绘性；最终由人工决定轮廓及是否暂缓。
<a href="FONT_LICENSE.txt">字体许可</a> · <a href="{e(data['meta']['pose_public_url'],quote=True)}">位姿入口</a></p></footer></body></html>'''


def build(out):
    require(not (out/'manifest.json').exists(),'Never overwrite a sealed worklist')
    data=prepare(out);decisions=read_json(out/'internal/source_visual_decisions.json')
    keys=select_tasks(data['rows'],data['usable'],data['per_class'],decisions,True)
    staged={r['target_key']:r for r in read_jsonl(out/'internal/review/shortlist.jsonl')}
    require(Counter(data['rows'][k]['final_class_id'] for k in keys)=={c:data['per_class'] for c in CLASSES},'No unsafe quota fill: approve sufficient genuine sources first')
    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),'Inspect each crop and full source before sealing')
    require(data['meta']['pose_public_url']==read_json(ACCESS)['public_url'].rstrip('/'),'Managed pose URL changed')
    (out/'images').mkdir();(out/'cases').mkdir();requests=[]
    for order,key in enumerate(keys,1):
        row=data['rows'][key];v=data['usable'][key];old=data['current'].get(key)
        source=dict(row,image_sha256=digest(data['formal']/row['image']),formal_manifest_sha256=data['parent']['formal_manifest_sha256'],
            classification_sha256=data['parent']['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')
        refs=v['exact_signature_human_template_keys']
        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='verified_worklist_awaiting_activation',task_kind='remaining_class_representative_manual_template',
            reason_zh='补充剩余类别同划分／传感器／观察面代表性人工轮廓；保存前不计完成，后续扩展执行原严格门槛。',
            source_visual_review_zh=decisions[key]['note_zh'],source_visual_review_kind='assistant_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_payload_raw_sha256=hashlib.sha256(data['current_raw'][key].encode()).hexdigest() if old else None,
            existing_pose_geometry_sha256=sha({f:old.get(f) for f in ('pose','ruler','sensor','selected_faces','exclusions')}) if old else None,
            existing_pose_current_payload=old,pose_history_present=bool(data['history'][key]),pose_history_flags=data['history'][key],
            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'],
            exact_view_human_template_absent=v['exact_view_human_template_absent'],exact_signature_human_template_keys=refs,
            closest_human_reference_key=refs[0] if refs else None,image_quality=v['quality'],quality_metrics_are_not_probabilities=True,
            medoid_rank=v['medoid_rank'],medoid_mean_squared_patch_distance=v['medoid_mean_squared_patch_distance'],
            requested_required_vertex_count=None,topology_must_be_manually_determined=True,minimum_manual_template_vertices=5,
            minimum_direct_manual_coverage_vertices=3,valid_four_point_manual_contour_allowed=True,extra_vertices_must_not_be_forced=True,
            original_rectangle_alone_is_not_completed_manual_coverage=True,valid_four_point_manual_contour_is_not_transfer_seed=True,
            pose_annotation_url=data['meta']['pose_public_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_published_coverage=False,generated_polygons=0))
    write_jsonl(out/'requests.jsonl',requests);text=page(requests,data);(out/'report_zh.html').write_text(text)
    from fontTools import subset
    from fontTools.ttLib import TTFont
    with TTFont(FONT) as font:
        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({ord(c) for c in text if '\u3400'<=c<='\u9fff'}<=set(font.getBestCmap()),'Chinese font glyph missing')
    shutil.copyfile(PROJECT/'pallet/assets/pose_review/FONT_LICENSE.txt',out/'FONT_LICENSE.txt')
    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/'class_population.json',data['pools']);write_json(out/'used_image_hashes.json',data['evidence'].used)
    protected=protected_snapshot(data['formal']);write_json(out/'protected_formal_after.json',protected)
    require(protected==read_json(out/'protected_formal_before.json') and len(protected)==20768,'Formal protected files changed')
    require(len(requests)==len({r['source']['frame_id'] for r in requests}),'Worklist repeats an image')
    require(file_inventory(BASE)==data['meta']['parent_file_inventory'] and file_inventory(PROJECT/'configs')==data['meta']['configuration_sha256'],'Frozen parent/configuration changed')
    for name,live in (('reviews_snapshot.sqlite3',POSE),('gallery_reviews_snapshot.sqlite3',GALLERY)):
        verify_history_preserved(live,out/name);require(database_fingerprint(live)==database_fingerprint(out/name,True),'Review store changed before worklist sealing')
    names=['report_zh.html','report-font.otf','FONT_LICENSE.txt']+[r[f] for r in requests for f in ('native_image','contact_crop')]
    manifest=dict(schema='remaining_classes_manual_worklist_v1',state='prepared_for_independent_verification',
        classes=list(CLASSES),target_per_class=100,request_count=len(requests),requested_class_counts={c:data['per_class'] for c in CLASSES},
        class_counts=dict(Counter(r['class_id'] for r in requests)),baseline_directory=str(BASE.relative_to(PROJECT)),baseline_publication_version=9,
        baseline_distinct_frames=500,baseline_preserved=True,requests_sha256=digest(out/'requests.jsonl'),
        formal_manifest_sha256=data['parent']['formal_manifest_sha256'],classification_sha256=data['parent']['classification_sha256'],
        pose_snapshot_sha256=digest(out/'reviews_snapshot.sqlite3'),gallery_snapshot_sha256=digest(out/'gallery_reviews_snapshot.sqlite3'),
        input_manifest_sha256=digest(out/'input_manifest.json'),source_visual_decisions_sha256=digest(out/'internal/source_visual_decisions.json'),
        class_population=data['pools'],existing_pose_request_count=sum(r['existing_pose_record'] 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)),class19_population_shortfall_at_least=4,
        class19_baseline_disjoint_population_shortfall_at_least=8,
        created_at=datetime.now(timezone.utc).isoformat(),public_assets={n:digest(out/n) for n in sorted(names)},
        pose_public_url=data['meta']['pose_public_url'],configuration_sha256=data['meta']['configuration_sha256'],
        sources_manifest_sha256=digest(SOURCES/'manifest.json'),source_output_directory=str(SOURCES.relative_to(PROJECT)),
        production_database_writes=0,configuration_writes=0,service_writes=0,ground_truth_eligible=False,
        protected_formal_files_verified=20768,production_annotation_writes=0,generated_polygons=0,
        counts_as_completed_annotation=False,all_remaining_quotas_complete=False,human_confirmation_inferred=False,
        automatic_training_eligible=False,robot_command_eligible=False,code_sha256=digest(__file__))
    write_json(out/'manifest.json',manifest)
    print(canonical(dict(state='prepared_for_independent_verification',requests=len(requests),class_counts=manifest['class_counts'],existing_pose=manifest['existing_pose_request_count'])).decode(),flush=True)


def main():
    parser=argparse.ArgumentParser(description=__doc__);parser.add_argument('--output',type=Path,default=DEFAULT)
    parser.add_argument('--per-class',type=int,default=3);parser.add_argument('--stage',choices=('review','build'),required=True)
    args=parser.parse_args();out=args.output.resolve()
    require(out.is_relative_to(PROJECT/'outputs') and out.name.startswith('pallet_mask_remaining_requests_v'),'Use a fresh remaining-class worklist path')
    require(1<=args.per_class<=10,'Limit each representative manual batch to 1–10 per class')
    stage(out,args.per_class) if args.stage=='review' else build(out)


if __name__=='__main__':main()
