"""Publication 10 draft: preserve counted humans, then run frozen guarded transfer.

Only a new output directory is written. Verification, publication, new manual
requests, live configuration and service changes are deliberately separate.
"""
from __future__ import annotations

import argparse
from collections import Counter, defaultdict
from concurrent.futures import ThreadPoolExecutor
from contextlib import closing
import hashlib
import html
import json
from pathlib import Path
import shutil

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

from . import mask_quota_100_complete as complete
from . import mask_quota_100_continue as prior
from . import mask_quota_completion as original
from . import mask_remaining_classes as remaining
from .cluster_targets import digest, protected_snapshot
from .mask_quota_saved_extension import file_inventory, indexed, load_formal_evidence
from .mask_template_continue import attempt_target, sha
from .mask_template_refined import (QUARANTINE, readonly, read_jsonl,
    snapshot_database, verify_history_preserved, write_jsonl)
from .mask_template_transfer import (PROJECT, annotation_inventory, compatible,
    overlay, write_json)
from .pose_review_geometry import canonical, polygon_value, raster_mask

VERSION = 'remaining_direct_saved_human_expand_v1'
PUBLICATION_VERSION = 10
CLASSES = remaining.CLASSES
ALL_CLASSES = tuple(range(1, 23))
TARGET_PER_CLASS = 100
GENERATION_NAMESPACE = 'remaining_expand_generation'
PARENT = remaining.PARENT
REUSE = remaining.OUTPUT
REQUESTS = PROJECT/'outputs/pallet_mask_remaining_requests_v2'
OUTPUT = PROJECT/'outputs/pallet_mask_remaining_expand_v1'
MANUAL_SCHEMA = prior.MANUAL_SCHEMA
FALSE_FLAGS = prior.FALSE_FLAGS
HISTORICAL_NAMESPACES = complete.HISTORICAL_NAMESPACES + ('quota100_complete_generation',)
REUSE_PINS = {
    'manifest.json': 'c343df29d0a5de57b9c224f41d186f8559b152ae3e55f827aeaaf9b2bd12dd8d',
    'artifact_hashes.json': 'bf3d63e88057b02f27e7b5900002c7a7d4eaf53beff817e02db3c62279df99b8',
    'independent_verification.json': '14446bf82465d1c06dfd1f7a2048e724a87eab2e6505372c6292683a744daaa6',
    'manual_proposals.jsonl': '09d564ec89bfa92ffa3b29c64baca7c5dda0cea4dbc83fd4e8f0b1429f9618ef',
}
REQUEST_PINS = {
    'manifest.json': 'b2a101ba5a60404835e08051bb49590988d8bc38c0dd2d19e03c99673f35becc',
    'verification.json': '619c88a23104c1541fff83fdc4b70c2a3c599858f6698709d4eeca62aff23a4a',
    'independent_verification.json': '8a195dc89e28916d7fafb5f6397f2cd705d24a06111545b507a3938f9a8c4eff',
    'requests.jsonl': '94818117ebe877035efe6a3bb7a6cd7b471d3bc020372125fd4fe2f3a9992dec',
}
read_json = remaining.read_json


def verified_inputs(parent, reuse, requests):
    manifest, parent_hashes = remaining.verified_parent(parent)
    reuse_hashes, request_hashes = file_inventory(reuse), file_inventory(requests)
    for hashes, pins in ((reuse_hashes, REUSE_PINS), (request_hashes, REQUEST_PINS)):
        if any(hashes.get(n) != h for n, h in pins.items()):
            raise ValueError('Pinned independently verified input changed')
    seal = read_json(reuse/'independent_verification.json')
    if (seal.get('state') != 'passed' or seal['manifest_sha256'] != reuse_hashes['manifest.json'] or
            seal['artifact_hashes_sha256'] != reuse_hashes['artifact_hashes.json']):
        raise ValueError('Remaining-source audit requires matching independent verification')
    for n, h in read_json(reuse/'artifact_hashes.json').items():
        if reuse_hashes.get(n) != h:
            raise ValueError('Frozen remaining-source audit changed: '+n)
    request_seal = read_json(requests/'independent_verification.json')
    if (request_seal.get('state') != 'passed' or request_seal.get('request_count') != 51 or
            request_seal.get('manifest_sha256') != request_hashes['manifest.json'] or
            request_seal.get('requests_sha256') != request_hashes['requests.jsonl']):
        raise ValueError('Completed 51-task source queue lacks matching independent verification')
    return manifest, parent_hashes, reuse_hashes, request_hashes


def protected_history(db, rows, current):
    """Protect any historical mask/state, even a later restored original rectangle."""
    protected = {k for k, v in current.items() if remaining.confirmed(v) or
        v.get('state') in ('deleted', 'deferred', 'confirmed') or
        (v.get('polygon') and not remaining.original_rectangle(v['polygon'], rows[k]))}
    for key, raw in db.execute('SELECT target_key,payload FROM events ORDER BY id'):
        v = json.loads(raw)
        if (remaining.confirmed(v) or v.get('state') in ('deleted', 'deferred', 'confirmed') or
                (v.get('polygon') and not remaining.original_rectangle(v['polygon'], rows[key]))):
            protected.add(key)
    return protected


def completed_manual_proposals(requests, candidates, rows, previous, pose_sha, formal_sha,
                               classification_sha, quarantine=(), gallery_keys=()):
    """Arbitrary-class exact-source branch; never call the frozen five-class seed filter."""
    indexed(requests)
    frames = {p['source']['frame_id'] for p in previous}
    keys = set(indexed(previous))
    result = []
    for request in sorted(requests, key=lambda v: v['target_key']):
        key = request['target_key']; row = rows[key]
        if (key in keys or row['frame_id'] in frames or key in quarantine or key in gallery_keys or
                row['final_class_id'] not in CLASSES):
            raise ValueError('Completed manual source repeats a locked/protected frame or target')
        if (request['class_id'] != row['final_class_id'] or
                request['source']['formal_manifest_sha256'] != formal_sha or
                any(request['source'].get(f) != row[f] for f in
                    prior.IDENTITY_FIELDS+('viewpoint_candidate',))):
            raise ValueError('Completed request formal/classification identity changed')
        if key not in candidates:
            raise ValueError('Completed request lacks a validated exact saved human source')
        p = remaining.saved_manual_proposal(key, row, candidates[key], pose_sha,
            formal_sha, classification_sha)
        p.update(generation_schema=VERSION, manual_source_kind='completed_manual_request',
            rendering_id=GENERATION_NAMESPACE+(':manual_source:' if p['manual_four_point_source'] else ':')+key,
            manual_request_sha256=sha(request), original_pose_url=request.get('pose_annotation_url'))
        result.append(p); frames.add(row['frame_id'])
    return result


def generation_templates(candidates, counted_keys, formal_sha, classification_sha):
    """Only explicitly counted remaining humans, never unrelated/old/gallery/machine seeds."""
    result = {}
    for key in sorted(counted_keys):
        value, metadata, record = candidates[key]
        if len(value['polygon']) <= 4:
            continue
        row = record['source']
        if row['final_class_id'] not in CLASSES:
            raise ValueError('Old five-class source cannot enter remaining generation')
        result[key] = dict(row=row, polygon=value['polygon'], revision=value['revision'],
            human_polygon_revision=record['human_polygon_revision'],
            human_event_sha256=record['human_event_sha256'],
            current_payload_sha256=record['current_payload_sha256'], human_mask_confirmed=False,
            origin=prior.POSE_ORIGIN, pose_review=metadata['pose_review'], propagation_seed_eligible=True,
            rendering_id=GENERATION_NAMESPACE+':'+key, formal_manifest_sha256=formal_sha,
            class_assignments_sha256=classification_sha)
    return result


def select_locked_diverse(locked, candidates, goal=TARGET_PER_CLASS):
    """Maximum residual frame/quota matching; locked proposals are never reallocated.

    Scarce classes first, then underrepresented collection groups, boundary NCC,
    ECC and key. Augmenting paths move only newly accepted machine frames.
    """
    indexed(locked); indexed(candidates)
    frames = {p['source']['frame_id'] for p in locked}
    if len(frames) != len(locked) or goal < 1:
        raise ValueError('Locked entries must be globally distinct; positive goal required')
    counts = Counter(p['class_id'] for p in locked)
    if any(n > goal for n in counts.values()):
        raise ValueError('Locked class exceeds quota')
    groups = {c: Counter(p['source']['group_id'] for p in locked if p['class_id'] == c) for c in CLASSES}
    by_class = {c: defaultdict(list) for c in CLASSES}
    for p in candidates:
        if p['class_id'] not in CLASSES:
            raise ValueError('Unexpected expansion class')
        if p['source']['frame_id'] not in frames:
            by_class[p['class_id']][p['source']['frame_id']].append(p)
    quality = lambda p: (-p.get('metrics', {}).get('boundary_ncc', 0),
        -p.get('metrics', {}).get('ecc', 0), p['target_key'])
    representatives = {c: {f: min(ps, key=quality) for f, ps in choices.items()}
        for c, choices in by_class.items()}
    order = sorted(CLASSES, key=lambda c: (len(representatives[c])/max(1, goal-counts[c]),
        len(representatives[c]), c))
    owners, held = {}, {c: set() for c in CLASSES}

    def give(frame, cls):
        old = owners.get(frame)
        if old is not None:
            held[old].remove(frame)
            groups[old][representatives[old][frame]['source']['group_id']] -= 1
        owners[frame] = cls; held[cls].add(frame)
        groups[cls][representatives[cls][frame]['source']['group_id']] += 1

    def augment(cls, visited):
        if cls in visited:
            return False
        visited.add(cls)
        preferences = sorted(representatives[cls], key=lambda f: (
            groups[cls][representatives[cls][f]['source']['group_id']], quality(representatives[cls][f])))
        for frame in preferences:
            if frame not in owners:
                give(frame, cls)
                return True
        for frame in preferences:
            old = owners[frame]
            if old != cls and augment(old, visited):
                give(frame, cls)
                return True
        return False

    for cls in order:
        while len(held[cls])+counts[cls] < goal and augment(cls, set()):
            pass
    selected = sorted((representatives[c][f] for f, c in owners.items()), key=lambda p: p['target_key'])
    keys = set(indexed(selected))
    dispositions = {p['target_key']: ('new_proposal' if p['target_key'] in keys else
        'accepted_duplicate_frame_not_selected' if p['source']['frame_id'] in frames | set(owners) else
        'accepted_quota_full_not_selected') for p in candidates}
    assignments = [dict(frame_id=f, class_id=c, target_key=representatives[c][f]['target_key'],
        phase='accepted_candidate_maximum_matching', locked=False) for f, c in sorted(owners.items())]
    return selected, dispositions, assignments, order


def target_inventory(rows, locked, status, pose_protected, gallery_keys, quarantine):
    keys = set(indexed(locked)); frames = {p['source']['frame_id'] for p in locked}
    work, outcomes = [], []
    for key, row in sorted(rows.items()):
        reason = ('quarantined' if key in quarantine else 'locked_counted_source' if key in keys else
            'locked_counted_frame' if row['frame_id'] in frames else
            'gallery_history_protected' if key in gallery_keys else
            'pose_mask_or_state_history_protected' if key in pose_protected else status[key])
        if reason == 'eligible' and row['final_class_id'] not in CLASSES:
            reason = 'class_not_requested'
        if reason == 'eligible':
            work.append((key, row))
        else:
            outcomes.append(dict(target_key=key, class_id=row['final_class_id'], reason=reason,
                registration_attempts=0))
    return work, outcomes


def proposal_from_attempt(key, row, accepted, templates, current, pose_sha, formal_sha, classification_sha):
    p = original.proposal_from_attempt(key, row, accepted, templates, current,
        pose_sha, formal_sha, classification_sha)
    return dict(p, schema=VERSION, machine_draft=True, human_edited=False,
        machine_transfer_performed=True, classification_is_candidate_not_truth=True,
        rendering_id=GENERATION_NAMESPACE+':'+accepted['template_key'], target_per_class=TARGET_PER_CLASS,
        continuation=dict(p['continuation'], batch=PUBLICATION_VERSION,
            all_compatible_templates_considered=True))


def class_counts(previous, reused, completed, new, reviews, source_records, dispositions,
                 templates, rows, work, outcomes, capacity):
    combined = previous+reused+completed+new
    bykey = indexed(combined)
    if len({p['source']['frame_id'] for p in combined}) != len(combined):
        raise ValueError('Cumulative proposal frames are not globally unique')
    pose = set(indexed(source_records)); acknowledged = set(indexed(dispositions))
    gallery = {k for k, v in reviews.items() if k in bykey and
        v.get('human_edited') is True and v.get('event_kind') == 'human_mask_gallery_revision' and
        v.get('state') not in ('deleted', 'deferred') and len(v.get('polygon', [])) >= 4}
    if acknowledged & (pose | gallery):
        raise ValueError('Old no-change dispositions overlap actual saved-human sources')
    four = {v['target_key'] for v in source_records if v['manual_four_point_source']}
    counts = {}
    for cls in ALL_CLASSES:
        keys = {p['target_key'] for p in combined if p['class_id'] == cls}
        old = {p['target_key'] for p in previous if p['class_id'] == cls}
        original_frames = {r['frame_id'] for r in rows.values() if r['final_class_id'] == cls}
        baseline_frames = {p['source']['frame_id'] for p in previous}
        additional_other_frames = {p['source']['frame_id'] for p in reused+completed if p['class_id'] != cls}
        raw_pending = keys-(pose | gallery)
        n = len(keys)
        if n > TARGET_PER_CLASS:
            raise ValueError('Cumulative class exceeds quota')
        counts[cls] = dict(class_id=cls, old_total=len(old),
            manual_existing_reused=sum(p['class_id'] == cls for p in reused),
            manual_requested=sum(p['class_id'] == cls for p in completed),
            manual_added=sum(p['class_id'] == cls for p in reused+completed),
            saved_gallery_human=len(keys & gallery), saved_pose_human=len(keys & pose),
            saved_human=len(keys & (gallery | pose)), manual_four_point_sources=len(keys & four),
            user_reviewed_no_change=len(keys & acknowledged), pending_machine_raw=len(raw_pending),
            old_pending_machine=len(old-(pose | gallery)), no_new_server_review=len(raw_pending-acknowledged),
            new_candidates=sum(p['class_id'] == cls for p in new),
            new_machine_pending=sum(p['class_id'] == cls for p in new),
            total=n, preview=n, distinct_frames=n, missing=TARGET_PER_CLASS-n,
            goal=TARGET_PER_CLASS, target_per_class=TARGET_PER_CLASS,
            templates=sum(t['row']['final_class_id'] == cls for t in templates.values()),
            eligible=sum(r['final_class_id'] == cls for _, r in work),
            original_targets=sum(r['final_class_id'] == cls for r in rows.values()),
            original_distinct_frames=len(original_frames),
            inherited_500_blocked_frames=len(original_frames & baseline_frames),
            additional_locked_other_class_frames=len((original_frames-baseline_frames) & additional_other_frames),
            capacity_matching_distinct_frames=capacity[cls],
            capacity_shortfall=TARGET_PER_CLASS-capacity[cls],
            outcomes=dict(Counter(v['reason'] for v in outcomes if v['class_id'] == cls)),
            classification_is_candidate_not_truth=True, human_mask_confirmed=0, ground_truth_eligible=0)
    return counts


def preserve_assets(parent, reuse, out, previous, reused):
    """Clone all source audit bytes, plus unchanged public assets/namespaces at root."""
    hashes = {}
    for source, dirname in ((parent, 'parent_evidence'), (reuse, 'remaining_source_audit_evidence')):
        shutil.copytree(source, out/dirname)
        for n, h in file_inventory(source).items():
            hashes[dirname+'/'+n] = h
    for source, proposals in ((parent, previous), (reuse, reused)):
        for p in proposals:
            for d, ext in (('cases', 'png'), ('images', 'png'), ('masks', 'png'), ('labelme', 'json')):
                n = f'{d}/{p["target_key"]}.{ext}'
                if (out/n).exists():
                    raise ValueError('Historical public asset collision')
                shutil.copyfile(source/n, out/n); hashes[n] = digest(source/n)
    for source, namespaces in ((parent, HISTORICAL_NAMESPACES),
            (reuse, (remaining.GENERATION_NAMESPACE,))):
        for d in namespaces:
            shutil.copytree(source/d, out/d)
            for n, h in file_inventory(source/d).items():
                hashes[d+'/'+n] = h
    for n in ('vertex2_before_after.png', 'FONT_LICENSE.txt', 'review_dispositions.jsonl',
            'review_disposition_statement.json'):
        shutil.copyfile(parent/n, out/n); hashes[n] = digest(parent/n)
    if any(digest(out/n) != h for n, h in hashes.items()):
        raise ValueError('Historical source audit/assets differ after copying')
    return hashes


def package_new_preview(out, new, templates, evidence):
    for p in new:
        key, row = p['target_key'], p['source']; t = templates[p['template']['target_key']]
        panel = Image.new('RGB', (1480, 305), '#121923'); draw = ImageDraw.Draw(panel)
        draw.text((15, 8), f'Class {p["class_id"]} | {p["vertex_count"]} vertices | direct saved human (left) -> machine draft (right)', fill='white')
        panel.paste(overlay(evidence.image(t['row']['frame_id']), t['row'], t['polygon'], '#55ceff'), (0, 30))
        panel.paste(overlay(evidence.image(row['frame_id']), row, p['polygon'], '#ffc247'), (740, 30))
        draw.text((15, 284), f'template {t["row"]["target_key"]} r{t["human_polygon_revision"]} | target {key} | {row["split"]} | pending review, NOT GT', fill='white')
        panel.save(out/'cases'/f'{key}.png')
        Image.fromarray(evidence.image(row['frame_id'])).save(out/'images'/f'{key}.png')
        Image.fromarray(raster_mask(p['polygon'], *row['size']).astype(np.uint8)*255).save(out/'masks'/f'{key}.png')
        flags = dict(human_confirmed=False, human_edited=False, machine_draft=True,
            **dict.fromkeys(FALSE_FLAGS, False))
        write_json(out/'labelme'/f'{key}.json', dict(version='5.0.0', imagePath=f'../images/{key}.png',
            imageData=None, imageWidth=row['size'][0], imageHeight=row['size'][1],
            annotation_scope='single_target_mask_review_not_full_frame', other_objects_unchanged=True,
            flags=flags, shapes=[dict(label='pallet', points=p['polygon'], shape_type='polygon',
                group_id=row['box_index'], flags=flags)], mask_template_provenance=p))


def rendering_inventory(parent_inventory, reuse_inventory, templates, completed, combined, new_keys):
    historical = parent_inventory['templates']+reuse_inventory['templates']
    generation = list(templates.values())
    sources = parent_inventory.get('manual_source_renderings', [])+reuse_inventory.get('manual_source_renderings', [])
    sources += [dict(target_key=p['target_key'], polygon=p['polygon'], rendering_id=p['rendering_id'],
        human_source=p['human_source'], propagation_seed_eligible=False, manual_four_point_source=True)
        for p in completed if p['manual_four_point_source']]
    ids = [v['rendering_id'] for v in historical+generation+sources]
    if len(ids) != len(set(ids)):
        raise ValueError('Rendering namespace collision')
    mapping = dict(parent_inventory['rendering_by_target'])
    mapping.update(reuse_inventory['rendering_by_target'])
    mapping.update({p['target_key']: p['rendering_id'] for p in completed})
    mapping.update({p['target_key']: p['rendering_id'] for p in combined if p['target_key'] in new_keys})
    if set(mapping) != set(indexed(combined)) or not set(mapping.values()) <= set(ids):
        raise ValueError('Cumulative rendering source missing')
    return dict(schema=VERSION, templates=historical+generation, manual_source_renderings=sources,
        rendering_by_target=mapping, generation_template_keys=sorted(templates),
        generation_templates=len(templates), generation_template_namespace=GENERATION_NAMESPACE,
        historical_templates=len(historical), generation_templates_by_origin={prior.POSE_ORIGIN: len(templates)},
        historical_snapshot_provenance=dict(parent='parent_evidence/snapshot_manifest.json',
            remaining_sources='remaining_source_audit_evidence/snapshot_manifest.json'),
        historical_templates_not_generation_authorization=True)


def build_report(out, combined, counts, new_keys, reused_keys, completed_keys, pose_keys, reviews,
                 disposition_keys, templates):
    total = lambda field: sum(v[field] for v in counts.values())
    rest = lambda field: sum(counts[c][field] for c in CLASSES)
    fields = ('old_total', 'manual_existing_reused', 'manual_requested', 'saved_human',
        'new_candidates', 'total', 'missing')
    table = ''.join(f'<tr><td>{c}</td>'+''.join(f'<td>{counts[c][f]}</td>' for f in fields)+'</tr>' for c in ALL_CLASSES)
    checked = ' checked' if new_keys else ''
    cards = []
    for p in sorted(combined, key=lambda v: (v['class_id'], v['target_key'])):
        key = p['target_key']
        if key in new_keys:
            label = '【本轮新增机器候选】待人工复核；不是人工标签或真值'
        elif key in completed_keys:
            label = '【已完成本轮人工请求】实际保存的人工草稿；未确认真值'
        elif key in reused_keys:
            label = '【原141份已计入人工轮廓】保留原始记录及图片，不重新分配帧'
        elif key in reviews:
            label = f'【已保存图册人工修订 r{reviews[key]["revision"]}】下图为保留的历史快照'
        elif key in pose_keys:
            label = '【既有原位姿人工来源】下图为保留的历史快照；最新来源单独审计'
        elif key in disposition_keys:
            label = '【用户已复核无需修改】原45份侧记原样保留；不是保存或种子授权'
        else:
            label = '【历史机器候选】未见新的服务器人工保存，不据此推断用户未查看'
        if p.get('manual_four_point_source'):
            label += '；真实四点，计覆盖但不作传播模板'
        is_manual = p.get('schema') == MANUAL_SCHEMA
        metrics = (f'<p>边界相关度 {p["metrics"]["boundary_ncc"]:.3f}；ECC '
            f'{p["metrics"]["ecc"]:.3f}，均为配准诊断，不是正确率或人工置信度。</p>' if key in new_keys else '')
        link = (f'<p><a href="{html.escape(p["original_pose_url"], quote=True)}">打开原位姿人工标注</a></p>'
            if p.get('original_pose_url') else '')
        hidden = ' hidden' if new_keys and key not in new_keys else ''
        cards.append(f'<article id="target-{key}" data-class="{p["class_id"]}" '
            f'data-batch="{"new" if key in new_keys else "previous"}" data-kind="{"manual" if is_manual else "machine"}"{hidden}>'
            f'<h2>类别 {p["class_id"]} · {label}</h2><img loading="lazy" src="cases/{key}.png?revision=10" '
            f'alt="{"实际人工来源快照" if is_manual else "历史快照或直接人工模板与机器候选对照"}">'
            f'<p>{html.escape(p["source"]["frame_id"])} ／ {p["source"]["split"]} ／ {key}</p>{metrics}{link}'
            f'<a href="labelme/{key}.json?revision=10">多边形（LabelMe）</a> · '
            f'<a href="masks/{key}.png?revision=10">掩膜</a></article>')
    page = '''<!doctype html><html lang="zh-CN"><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
<title>第十版 · 剩余十七类严格扩展草稿</title><style>@font-face{font-family:PreviewSans;src:url('report-font.otf?revision=10')}*{box-sizing:border-box}body{background:#101720;color:#e7edf5;font:16px PreviewSans,sans-serif;margin:auto;padding:20px;max-width:1090px}a{color:#77ceff}img{display:block;width:100%;max-width:100%;height:auto}article{border:1px solid #425269;margin:20px 0;padding:12px;min-width:0}p,h2{overflow-wrap:anywhere}.table-wrap{max-width:100%;overflow-x:auto}td,th{padding:9px;border:1px solid #425269;white-space:nowrap}table{border-collapse:collapse;min-width:1090px;width:100%}select{font:inherit;padding:6px}[hidden]{display:none!important}@media(max-width:700px){body{padding:10px}article{padding:7px}h2{font-size:18px}}</style>
<h1>第十版 · 剩余十七类扩展（待独立核验，尚未发布）</h1>
<p>旧五类500个不同帧和其余类别原141份实际人工轮廓原样保留；本次51项人工请求均核验数据库当前多边形及实际人工事件后计入。原692帧锁定，不重新分配或损失已计入人工标签。所有22类原始分类仍是候选类别，不是已确认语义真值。</p>
'''
    page += (f'<section id="new-batch"><h2>本轮新增机器候选 {len(new_keys)} 份</h2>'
        f'<p>其余17类进度：实际保存人工 {rest("saved_human")} + 新机器候选 {rest("new_candidates")} '
        f'= 覆盖 {rest("total")}/1700 个不同帧，仍缺 {rest("missing")}；覆盖不等于人工完成率。'
        f'全部22类累计 {total("total")}/2200，实际保存人工 {total("saved_human")} '
        f'= 原位姿 {total("saved_pose_human")} + 图册 {total("saved_gallery_human")}（目标去重）。</p></section>')
    page += (f'<p>本轮仅使用剩余192份人工来源中的 {len(templates)} 份超过四点的直接人工模板；'
        f'其中 {rest("manual_four_point_sources")} 份真实四点轮廓仍按四点计覆盖，绝不补造点。'
        '类别4、7、22没有超过四点的计入模板，后续须补充真实人工模板，不能自动扩展。'
        f'类别19原有96帧，旧500占4帧，另2帧受历史保护，原容量最多90；锁定已计入的其他类别人工帧后，'
        f'本轮实际容量为 {counts[19]["capacity_matching_distinct_frames"]}，不能伪填至100。</p>')
    page += '''<p>只用原始 attempt_target：同类、同划分、同传感器配置与兼容视角；初始相关度至少0.55、ECC至少0.84、边界相关度至少0.78、逐顶点往返误差不超过1.5，并通过全部横梁边界检查。保持顶点数及顺序，不递归使用机器草稿、不使用旧45份对话侧记、不放宽门槛、不强行补满。相关度不是正确率。</p>
<p>旧500份与原141份的规范记录、图片、掩膜、标注及全部历史资源命名空间逐字节保留。历史卡片不是最新修订渲染；最新原始人工与图册事件另行冻结。原45份无需修改侧记原样保留；其余未见服务器新保存不据此推断未查看。本轮不会新建人工请求、写入数据库、改动配置或服务。所有结果均未确认真值，不自动用于训练或机器人控制。</p>
'''
    page += '<div class="table-wrap"><table><tr><th>类别</th><th>旧500</th><th>原人工复用</th><th>完成请求</th><th>已保存人工</th><th>新增机器</th><th>累计不同帧</th><th>缺额</th></tr>'+table+'</table></div>'
    page += '<p>筛选类别 <select id="filter"><option value="">全部22类</option>'+''.join(
        f'<option value="{c}">{c}</option>' for c in ALL_CLASSES)+'</select> '
    page += f'<label><input type="checkbox" id="only-new"{checked}>只看本轮新增机器候选</label></p>'+''.join(cards)
    page += """<script>const cls=document.querySelector('#filter'),only=document.querySelector('#only-new');function filter(){document.querySelectorAll('article').forEach(a=>a.hidden=(!!cls.value&&a.dataset.class!==cls.value)||(only.checked&&a.dataset.batch!=='new'));}cls.onchange=only.onchange=filter;filter();</script></html>"""
    (out/'report_zh.html').write_text(page)
    from fontTools import subset
    from fontTools.ttLib import TTFont
    source = Path('/tmp/opencode/pallet_pose_design/NotoSansCJKsc-Regular.otf')
    required = {ord(c) for c in page if '\u3400' <= c <= '\u9fff'}
    with TTFont(source) as font:
        if not required <= set(font.getBestCmap()):
            raise ValueError('Report source font lacks required Chinese 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:
        if not required <= set(font.getBestCmap()):
            raise ValueError('Report subset font lacks required Chinese glyphs')
    write_json(out/'font_coverage.json', dict(chinese_glyphs=len(required), all_report_Chinese_present=True,
        font_source_sha256=digest(source), font_sha256=digest(out/'report-font.otf')))


def generate(output=OUTPUT, workers=4, parent=PARENT, reuse=REUSE, requests_directory=REQUESTS):
    out, parent, reuse, request_dir = map(lambda p: Path(p).resolve(),
        (output, parent, reuse, requests_directory))
    if out.exists() or not out.is_relative_to(PROJECT/'outputs'):
        raise ValueError('Use a new outputs directory; never overwrite frozen publications')
    if not 1 <= workers <= 8:
        raise ValueError('Workers must be 1–8')
    manifest, parent_hashes, reuse_hashes, request_hashes = verified_inputs(parent, reuse, request_dir)
    config_hashes = file_inventory(PROJECT/'configs')
    frozen_code = dict(manifest['frozen_code_sha256'])
    frozen_code.update({n: digest(PROJECT/n) for n in
        ('pallet/mask_remaining_classes.py', 'pallet/mask_remaining_expand.py')})
    formal, rows, evidence = load_formal_evidence(manifest)
    formal_sha, classification_sha = manifest['formal_manifest_sha256'], manifest['classification_sha256']
    if len(rows) != 12344 or {r['final_class_id'] for r in rows.values()} != set(ALL_CLASSES):
        raise ValueError('Original 22-class/12344-target inventory changed')
    previous, reused, requests = (read_jsonl(p) for p in
        (parent/'proposals.jsonl', reuse/'manual_proposals.jsonl', request_dir/'requests.jsonl'))
    inherited = [p for p in previous if p.get('schema') == MANUAL_SCHEMA]
    if (len(previous) != 500 or len(reused) != 141 or len(inherited) != 143 or len(requests) != 51 or
            Counter(p['class_id'] for p in previous) != {1: 100, 2: 100, 9: 100, 10: 100, 15: 100} or
            Counter(r['class_id'] for r in requests) != {c: 3 for c in CLASSES} or
            len({p['source']['frame_id'] for p in previous+reused}) != 641 or
            any(p['source'] != rows[p['target_key']] for p in previous+reused)):
        raise ValueError('Canonical inherited 500+141 / completed 51 source inventory changed')
    protected = protected_snapshot(formal)
    if (len(protected) != 20768 or protected != read_json(parent/'protected_formal_before.json') or
            protected != read_json(reuse/'protected_formal_after.json')):
        raise ValueError('Protected formal 20768-file inventory changed')
    out.mkdir(parents=True)
    for n, value in (('parent_file_inventory', parent_hashes), ('reuse_file_inventory', reuse_hashes),
            ('request_file_inventory', request_hashes), ('configuration_input_hashes', config_hashes),
            ('protected_formal_before', protected)):
        write_json(out/(n+'.json'), value)
    pose_live = PROJECT/'outputs/pallet_pose_human_review_v1/annotations.sqlite3'
    gallery_live = PROJECT/'outputs/pallet_mask_gallery_reviews_v1/mask_reviews.sqlite3'
    pose_snapshot, gallery_snapshot = out/'reviews_snapshot.sqlite3', out/'gallery_reviews_snapshot.sqlite3'
    pose_sha, gallery_sha = snapshot_database(pose_live, pose_snapshot), snapshot_database(gallery_live, gallery_snapshot)
    counted_remaining = set(indexed(reused)) | set(indexed(requests))
    explicit = set(indexed(inherited)) | counted_remaining
    candidates, source_audit = {}, []
    with closing(readonly(pose_snapshot, True)) as db:
        pose_metadata = dict(db.execute('SELECT key,value FROM metadata'))
        binding = json.loads(pose_metadata['binding'])
        if (binding.get('formal_manifest_sha256') != formal_sha or
                binding.get('formal_annotations_sha256') != digest(formal/'annotations/frames.jsonl') or
                binding.get('formal_frames_sha256') != digest(formal/'frames.jsonl')):
            raise ValueError('Pose formal binding changed')
        current = remaining.snapshot_rows(db, 'annotations', rows)
        remaining.snapshot_rows(db, 'events', rows)
        _, _, status = annotation_inventory(db, rows)
        pose_protected = protected_history(db, rows, current)
        pose_events = db.execute('SELECT COUNT(*) FROM events').fetchone()[0]
        oldbykey = indexed(inherited+reused)
        for key in sorted(explicit):
            candidate = remaining.validated_manual_source(db, key, rows[key], pose_sha, sha(binding))
            candidates[key] = candidate
            value, metadata, record = candidate
            old = oldbykey.get(key)
            source_audit.append(dict(target_key=key, class_id=rows[key]['final_class_id'],
                exact_current_direct_human_validated=True, current_revision=value['revision'],
                current_payload_sha256=sha(value), vertex_count=len(value['polygon']),
                historical_canonical_preserved=old is not None, canonical_proposal_sha256=sha(old) if old else None,
                historical_polygon_changed=old['polygon'] != value['polygon'] if old else False,
                current_template_selected=key in counted_remaining and len(value['polygon']) > 4,
                current_snapshot_sha256=pose_sha, human_event_sha256=record['human_event_sha256']))
    with closing(readonly(gallery_snapshot, True)) as db:
        gallery_metadata = dict(db.execute('SELECT key,value FROM metadata'))
        if gallery_metadata.get('formal_manifest_sha256') != formal_sha:
            raise ValueError('Gallery formal binding mismatch')
        reviews = remaining.snapshot_rows(db, 'reviews', rows)
        remaining.snapshot_rows(db, 'events', rows)
        events = [json.loads(raw) for raw, in db.execute('SELECT payload FROM events ORDER BY id')]
        gallery_keys = set(reviews) | {v['target_key'] for v in events}
        gallery_sources = []
        for key, revision, raw in db.execute('SELECT target_key,revision,payload FROM reviews ORDER BY target_key'):
            event_rows = list(db.execute('SELECT id,payload FROM events WHERE target_key=? AND revision=?', (key, revision)))
            if len(event_rows) != 1 or json.loads(event_rows[0][1]) != json.loads(raw):
                raise ValueError('Gallery current/exact event mismatch')
            event_id, event_raw = event_rows[0]
            gallery_sources.append(dict(target_key=key, revision=revision, current_payload_raw=raw,
                current_payload_raw_sha256=hashlib.sha256(raw.encode()).hexdigest(), current_payload=json.loads(raw),
                human_event_id=event_id, human_event_payload_raw=event_raw,
                human_event_sha256=hashlib.sha256(event_raw.encode()).hexdigest(), snapshot_sha256=gallery_sha))
    paths = dict(complete.SOURCE_PUBLICATIONS); paths[9] = parent
    source_publication_hashes = {v: file_inventory(p) for v, p in paths.items() if p != parent}
    # Validates the entire latest gallery against the actual historical editor
    # bindings. These validated gallery contours are NOT generation seeds here.
    original.gallery_templates(previous, reviews, events, current, rows, parent,
        formal_sha, gallery_sha, publication_paths=paths)
    quarantine = set(QUARANTINE) | set(manifest.get('preserved_quarantined_targets', []))
    completed = completed_manual_proposals(requests, candidates, rows, previous+reused,
        pose_sha, formal_sha, classification_sha, quarantine, gallery_keys)
    manual = sorted(reused+completed, key=lambda p: p['target_key'])
    locked = previous+manual
    templates = generation_templates(candidates, counted_remaining, formal_sha, classification_sha)
    all_sources = [candidates[k][2] for k in sorted(explicit)]
    manual_sources = [candidates[k][2] for k in sorted(counted_remaining)]
    if (len(locked) != 692 or len({p['source']['frame_id'] for p in locked}) != 692 or
            len(templates) != 41 or sum(p['manual_four_point_source'] for p in manual) != 151 or
            len(all_sources) != 335 or set(templates) - counted_remaining):
        raise ValueError('Exact 692 locked / 192 manual / 41 seed / 335 raw source contract changed')
    for p in manual:
        if p['target_key'] in quarantine or p['target_key'] in gallery_keys:
            raise ValueError('Manual source became protected by quarantine/gallery history')
    work, outcomes = target_inventory(rows, locked, status, pose_protected, gallery_keys, quarantine)
    capacity_candidates = [dict(target_key=k, class_id=r['final_class_id'], source=r, metrics={}) for k, r in work]
    potential, _, capacity_assignments, capacity_order = select_locked_diverse(locked, capacity_candidates)
    capacity = Counter(p['class_id'] for p in locked+potential)
    for c in ALL_CLASSES:
        capacity.setdefault(c, 0)
    if capacity[19] > 90:
        raise ValueError('Class19 cannot exceed its original 90-frame protected capacity')
    write_json(out/'protected_targets.json', dict(locked_keys=sorted(indexed(locked)),
        locked_frames=sorted(p['source']['frame_id'] for p in locked), quarantine=sorted(quarantine),
        pose_mask_history_or_noneligible=sorted(pose_protected), gallery_saved_or_history=sorted(gallery_keys),
        counted_manual_source_keys=sorted(explicit), newly_counted_manual_source_keys=sorted(counted_remaining),
        eligibility=status, conversation_dispositions_not_seed_authorization=True))
    write_json(out/'snapshot_manifest.json', dict(formal_manifest_sha256=formal_sha,
        pose=dict(path=pose_snapshot.name, sha256=pose_sha, saved=len(current), events=pose_events,
            immutable=True, metadata=pose_metadata, backup='backups/'+pose_snapshot.name),
        gallery=dict(path=gallery_snapshot.name, sha256=gallery_sha, saved=len(reviews), events=len(events),
            immutable=True, metadata=gallery_metadata, backup='backups/'+gallery_snapshot.name),
        historical_snapshots_retained_under=['parent_evidence', 'remaining_source_audit_evidence']))
    for name, values in (('manual_proposals', manual), ('reuse_old_manual_proposals', reused),
            ('completed_request_manual_proposals', completed), ('manual_source_records', manual_sources),
            ('all_manual_sources', all_sources), ('human_source_audit', source_audit),
            ('remaining_current_manual_source_records', manual_sources),
            ('gallery_source_records', gallery_sources), ('refined_annotations', [reviews[k] for k in sorted(reviews)]),
            ('capacity_frame_assignments', capacity_assignments)):
        write_jsonl(out/(name+'.jsonl'), values)
    for name in ('manual_source_records', 'all_manual_sources', 'remaining_current_manual_source_records', 'gallery_source_records'):
        (out/(name+'.jsonl')).chmod(0o600)
    shutil.copyfile(request_dir/'requests.jsonl', out/'requests.jsonl')
    for request in requests:
        row = rows[request['target_key']]
        evidence.image(row['frame_id'])
        if request['source']['image_sha256'] != evidence.used[request['source']['image']]:
            raise ValueError('Completed request formal image changed')
    for source, proposals in ((parent, previous), (reuse, reused)):
        for p in proposals:
            with Image.open(source/'images'/f'{p["target_key"]}.png') as image:
                if not np.array_equal(np.asarray(image), evidence.image(p['source']['frame_id'])):
                    raise ValueError('Inherited asset image differs from native formal pixels')
    print(json.dumps(dict(state='scanning', workers=workers, templates=len(templates),
        locked=len(locked), manual=len(manual), actual_human_before_machines=len(explicit | set(reviews)),
        eligible_targets=len(work), pose_saved=len(current), pose_events=pose_events,
        gallery_saved=len(reviews), gallery_events=len(events))), flush=True)
    attempts, accepted = [], []
    def worker(item):
        return item, attempt_target(*item, templates, evidence)
    with ThreadPoolExecutor(max_workers=workers) as pool:
        for number, ((key, row), (candidate, trials, outcome)) in enumerate(pool.map(worker, work), 1):
            attempts.extend(trials)
            outcomes.append(dict(outcome, registration_attempts=len(trials)))
            if candidate:
                accepted.append(proposal_from_attempt(key, row, candidate, templates,
                    current, pose_sha, formal_sha, classification_sha))
            if number % 200 == 0:
                print(json.dumps(dict(scanned=number, accepted=len(accepted), attempts=len(attempts))), flush=True)
    new, selections, assignments, scarcity_order = select_locked_diverse(locked, accepted)
    for outcome in outcomes:
        if outcome['target_key'] in selections:
            outcome['reason'] = selections[outcome['target_key']]
    if len(outcomes) != len(rows) or set(indexed(outcomes)) != set(rows):
        raise ValueError('Every original target requires an outcome')
    combined = sorted(locked+new, key=lambda p: p['target_key'])
    restored = indexed(combined)
    if any(canonical(restored[p['target_key']]) != canonical(p) for p in previous+reused):
        raise ValueError('Historical canonical source changed')
    dispositions = read_jsonl(parent/'review_dispositions.jsonl')
    counts = class_counts(previous, reused, completed, new, reviews, all_sources,
        dispositions, templates, rows, work, outcomes, capacity)
    for name, values in (('proposals', combined), ('new_proposals', new), ('registration_attempts', attempts),
            ('accepted_candidates', accepted), ('outcomes', sorted(outcomes, key=lambda v: v['target_key'])),
            ('frame_assignments', [dict(frame_id=p['source']['frame_id'], class_id=p['class_id'],
                target_key=p['target_key'], locked=True, phase='previously_counted_source') for p in locked]+assignments)):
        write_jsonl(out/(name+'.jsonl'), values)
    for d in ('cases', 'images', 'masks', 'labelme'):
        (out/d).mkdir()
    copied = preserve_assets(parent, reuse, out, previous, reused)
    package_new_preview(out, new, templates, evidence)
    prior.package_manual_preview(out, completed, evidence)
    (out/GENERATION_NAMESPACE/'templates').mkdir(parents=True)
    for key, template in templates.items():
        write_json(out/GENERATION_NAMESPACE/'templates'/f'{key}.json', template)
    inventory = rendering_inventory(read_json(parent/'template_inventory.json'),
        read_json(reuse/'template_inventory.json'), templates, completed, combined, set(indexed(new)))
    inventory.update(publication_version=PUBLICATION_VERSION, classes=counts, previous_proposals=500,
        manual_proposals=192, all_manual_sources=335, snapshot_saved=len(current), snapshot_events=pose_events,
        gallery_snapshot_saved=len(reviews), gallery_snapshot_events=len(events),
        eligibility=status, target_per_class=100, counted_manual_source_keys=sorted(explicit))
    write_json(out/'template_inventory.json', inventory)
    write_json(out/'preserved_parent_assets.json', copied)
    build_report(out, combined, counts, set(indexed(new)), set(indexed(reused)), set(indexed(completed)),
        explicit, reviews, set(indexed(dispositions)), templates)
    contact = Image.new('RGB', (1480, 305*len(ALL_CLASSES)), '#121923')
    for i, cls in enumerate(ALL_CLASSES):
        p = next(p for p in new+completed+reused+previous if p['class_id'] == cls)
        with Image.open(out/'cases'/f'{p["target_key"]}.png') as image:
            contact.paste(image, (0, i*305))
    contact.save(out/'preview_all_classes.png')
    used = read_json(parent/'used_image_hashes.json')
    for values in (read_json(reuse/'used_image_hashes.json'), evidence.used):
        for n, h in values.items():
            if n in used and used[n] != h:
                raise ValueError('Native source image hash conflict')
            used[n] = h
    if any(digest(formal/n) != h for n, h in used.items()):
        raise ValueError('Used native source image changed')
    write_json(out/'used_image_hashes.json', used)
    after = protected_snapshot(formal); write_json(out/'protected_formal_after.json', after)
    if after != protected:
        raise ValueError('Formal files changed')
    for live, frozen, table, metadata in ((pose_live, pose_snapshot, 'annotations', pose_metadata),
            (gallery_live, gallery_snapshot, 'reviews', gallery_metadata)):
        verify_history_preserved(live, frozen)
        prior.verify_sources_current(live, frozen, table)
        with closing(readonly(live)) as db:
            if dict(db.execute('SELECT key,value FROM metadata')) != metadata:
                raise ValueError('Live binding changed during generation')
    if (digest(pose_snapshot) != pose_sha or digest(gallery_snapshot) != gallery_sha or
            any(digest(out/'backups'/p.name) != digest(p) for p in (pose_snapshot, gallery_snapshot)) or
            file_inventory(parent) != parent_hashes or file_inventory(reuse) != reuse_hashes or
            file_inventory(request_dir) != request_hashes or file_inventory(PROJECT/'configs') != config_hashes or
            any(file_inventory(paths[v]) != hashes for v, hashes in source_publication_hashes.items()) or
            any(digest(PROJECT/n) != h for n, h in frozen_code.items()) or
            any(digest(out/n) != h for n, h in copied.items())):
        raise ValueError('Frozen source/code/configuration/snapshot/asset changed')
    write_json(out/'source_stability_check.json', dict(state='stable', source_current_stable=True,
        current_payloads_and_events_unchanged=True, metadata_unchanged=True, production_database_writes=0))
    write_json(out/'source_publication_file_inventories.json', source_publication_hashes)
    write_json(out/'shortfalls.json', {c: dict(missing=counts[c]['missing'],
        capacity=capacity[c], capacity_shortfall=100-capacity[c], templates=counts[c]['templates'],
        outcomes=counts[c]['outcomes'], manual_template_required=counts[c]['templates'] == 0,
        explanation='Only actual saved humans count as human coverage; frozen original guarded transfers, '
            'locked existing frames, scarcity-first maximum matching and distinct-frame quotas. No fake fill.') for c in CLASSES})
    total = lambda f: sum(v[f] for v in counts.values())
    result = dict(state='remaining_expand_pending_independent_verification', schema=VERSION, version=VERSION,
        publication_version=PUBLICATION_VERSION, published=False, independent_verification_performed=False,
        parent=str(parent), parent_manifest_sha256=parent_hashes['manifest.json'],
        parent_proposals_sha256=parent_hashes['proposals.jsonl'], parent_verification_sha256=parent_hashes['verification.json'],
        previous_proposals=500, reused_old_manual_proposals=141, completed_request_manual_proposals=51,
        manual_proposals=192, manual_added=192, manual_existing_reused=141, manual_requested=51,
        inherited_manual_sources=143, all_manual_sources=335, base_proposals=692,
        proposals=len(combined), new_proposals=len(new), new_machine_pending=len(new),
        new_by_class=dict(Counter(p['class_id'] for p in new)), manual_by_class=dict(Counter(p['class_id'] for p in manual)),
        manual_source_schema=MANUAL_SCHEMA, classes=counts, remaining_classes=list(CLASSES), all_classes=list(ALL_CLASSES),
        target_per_class=100, target_total=2200, remaining_target_total=1700,
        missing=total('missing'), saved_human=total('saved_human'), saved_pose_human=total('saved_pose_human'),
        saved_gallery_human=total('saved_gallery_human'), pending_machine_raw=total('pending_machine_raw'),
        old_pending_machine=total('old_pending_machine'), user_reviewed_no_change=len(dispositions),
        no_new_server_review=total('no_new_server_review'),
        counted_manual_source_keys=sorted(explicit), newly_counted_manual_source_keys=sorted(counted_remaining),
        requested_manual_keys=sorted(indexed(completed)), manual_four_point_sources=sum(p['manual_four_point_source'] for p in manual),
        all_pose_four_point_sources=sum(r['manual_four_point_source'] for r in all_sources),
        generation_templates=len(templates), generation_template_namespace=GENERATION_NAMESPACE,
        generation_templates_by_origin={prior.POSE_ORIGIN: len(templates)},
        generation_templates_by_class=dict(Counter(t['row']['final_class_id'] for t in templates.values())),
        generation_template_keys=sorted(templates), method='original', workers=workers,
        scanned_eligible_targets=len(work), registration_attempts=len(attempts), accepted_before_diversity=len(accepted),
        outcomes=dict(Counter(v['reason'] for v in outcomes)), scarcity_order=scarcity_order,
        capacity_matching_order=capacity_order, capacity_matching_total=sum(capacity.values()),
        formal_manifest_sha256=formal_sha, classification_sha256=classification_sha,
        snapshot_sha256=pose_sha, gallery_snapshot_sha256=gallery_sha,
        snapshot_saved=len(current), snapshot_events=pose_events,
        gallery_snapshot_saved=len(reviews), gallery_snapshot_events=len(events),
        protected_formal_files=len(protected), preserved_quarantined_targets=sorted(quarantine),
        original_splits_preserved=True, cross_split_template_transfers=0, recursive_candidate_propagation=False,
        thresholds_relaxed=False, forced_fill=False, duplicate_fill=False, research_candidates_added=0,
        new_human_edits_created=0, human_requests_created=0, production_database_writes=0,
        configuration_writes=0, service_writes=0, automatic_human_confirmation=False,
        automatic_training_eligible=False, robot_command_eligible=False, ground_truth_eligible=False,
        classification_is_candidate_not_truth=True, source_current_stable=True, public_archive_created=False,
        historical_canonical_preserved=641, inherited_resources_bytewise_preserved=True,
        manual_source_snapshots_imported_into_gallery_store=False,
        code_sha256=digest(__file__), frozen_code_sha256=frozen_code,
        transfer_code_sha256=frozen_code['pallet/mask_template_transfer.py'],
        boundary_code_sha256=frozen_code['pallet/mask_boundary_review.py'],
        attempt_code_sha256=frozen_code['pallet/mask_template_continue.py'])
    for path in sorted(out.glob('*.jsonl')):
        result[path.stem+'_sha256'] = digest(path)
    for name in ('template_inventory', 'snapshot_manifest', 'font_coverage'):
        result[name+'_sha256'] = digest(out/(name+'.json'))
    write_json(out/'manifest.json', result)
    write_json(out/'generation_validation.json', dict(state='self_checks_passed_not_independent_verification',
        publication_version=PUBLICATION_VERSION, published=False, independent_verification_performed=False,
        historical_canonical_preserved=641, locked_before_machines=692, global_distinct_frames=len(combined),
        preserved_source_files=len(copied), protected_formal_files=20768, no_production_writes=True))
    (out/'GENERATION_HANDOFF.md').write_text(
        '# Publication 10 draft — pending independent verification\n\n'
        f'{len(combined)} globally distinct frames = parent 500 + immutable reused human 141 + completed human 51 '
        f'+ new machine drafts {len(new)}. Actual saved-human coverage {result["saved_human"]}; not GT.\n\n'
        '`manual_proposals.jsonl`: 192 newly counted manual entries (141 reused canonical + 51 completed requests). '
        '`new_proposals.jsonl`: only newly selected machine drafts. `all_manual_sources.jsonl`: latest exact raw '
        'current/human-event evidence for all 335 explicit pose-human sources, not proposal objects. '
        '`remaining_current_manual_source_records.jsonl`: latest 192 remaining-human audits. '
        'Historical proposals retain original snapshot hashes; full original audits/snapshots/assets are retained '
        'under `parent_evidence/` and `remaining_source_audit_evidence/`.\n\n'
        '41 direct >4-point remaining sources only; 151 genuine four-point remaining humans count but never seed. '
        f'Classes 4/7/22 have no propagation templates. Class19 prior capacity was 90; after preserving all '
        f'692 locked frames its current maximum is {capacity[19]}. No new requests or ZIP '
        'created. Coordinator must independently verify before packaging, activating or publishing.\n')
    write_json(out/'artifact_hashes.json', file_inventory(out))
    return result


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('--output', type=Path, default=OUTPUT)
    parser.add_argument('--workers', type=int, default=4)
    args = parser.parse_args()
    cv2.setNumThreads(1)
    result = generate(args.output, args.workers)
    print(json.dumps({k: result[k] for k in ('state', 'proposals', 'new_proposals', 'new_by_class',
        'saved_human', 'missing', 'registration_attempts', 'accepted_before_diversity', 'code_sha256')},
        ensure_ascii=False), flush=True)


if __name__ == '__main__':
    main()
