"""Fixed-vertex mask assistance from frozen human edits, never a GT publisher.

The preview command only writes its new output directory. It does not construct a
PoseApplication, change the live database, or feed annotations into pose models.
"""
from __future__ import annotations

import argparse
from collections import Counter, defaultdict
from contextlib import closing
from datetime import datetime, timezone
from functools import lru_cache
import hashlib
import html
import json
from pathlib import Path
import sqlite3
from zipfile import ZipFile, ZIP_DEFLATED

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

from .cluster_targets import digest, load_dataset, protected_snapshot, target_key
from .pose_review_geometry import canonical, polygon_value, raster_mask

PROJECT = Path(__file__).resolve().parents[1]
VERSION = 'same_class_fixed_vertex_preview_v1'
PATCH_SIZE = (256, 112)
AUTO_EVENTS = {'unit_normalization', 'axes_normalization', 'mask_template_proposal'}


def write_json(path, value):
    Path(path).write_bytes(canonical(value) + b'\n')


def rectangle(row):
    x, y, w, h = (row['bbox'][k] for k in ('x', 'y', 'width', 'height'))
    return [[x, y], [x+w, y], [x+w, y+h], [x, y+h]]


def unchanged_rectangle(polygon, row):
    return (polygon is not None and np.shape(polygon) == (4, 2)
            and np.allclose(polygon, rectangle(row), rtol=0, atol=1e-5))


def compatible(source, target):
    """No crossing classes, source policies, known viewing faces, or splits."""
    if source['frame_id'] == target['frame_id']:
        return False
    if any(source[k] != target[k] for k in ('final_class_id', 'split', 'policy_id')):
        return False
    a, b = source.get('viewpoint_candidate'), target.get('viewpoint_candidate')
    return not (a not in (None, 'unknown') and b not in (None, 'unknown') and a != b)


def annotation_inventory(db, rows):
    current = {k: json.loads(raw) for k, raw in db.execute('SELECT target_key,payload FROM annotations')}
    edited, last_human = set(), {}
    for key, revision, raw in db.execute('SELECT target_key,revision,payload FROM events ORDER BY id'):
        value = json.loads(raw)
        if key not in rows:
            raise ValueError('Unknown target in review history')
        if value.get('polygon') and not unchanged_rectangle(value['polygon'], rows[key]):
            edited.add(key)
        # A unit/axis revision is not evidence of a new human polygon edit.
        if value.get('event_kind') not in AUTO_EVENTS and value.get('state') != 'deleted':
            last_human[key] = dict(revision=revision, polygon=value.get('polygon'),
                                   event_payload_sha256=hashlib.sha256(raw.encode()).hexdigest())
    templates = {}
    for key, value in current.items():
        if value.get('state') in ('deleted', 'deferred') or len(value.get('polygon', [])) <= 4:
            continue
        human = last_human.get(key)
        if not human or human['polygon'] != value['polygon']:
            continue
        polygon_value(value['polygon'], *rows[key]['size'])
        templates[key] = dict(row=rows[key], polygon=value['polygon'], revision=value['revision'],
            human_polygon_revision=human['revision'], human_event_sha256=human['event_payload_sha256'],
            current_payload_sha256=hashlib.sha256(canonical(value)).hexdigest(),
            human_mask_confirmed=value.get('human_mask_confirmed', False))
    status = {}
    for key in rows:
        value = current.get(key)
        status[key] = ('deleted' if value and value.get('state') == 'deleted' else
                       'human_mask_history_protected' if key in edited else
                       'deferred_or_confirmed_protected' if value and (value.get('state') == 'deferred'
                           or value.get('human_mask_confirmed') or value.get('human_pose_confirmed')) else 'eligible')
    return current, templates, status


def patch_matrix(row):
    """Image edge coordinates -> canonical patch pixel-center coordinates."""
    x, y, w, h = (row['bbox'][k] for k in ('x', 'y', 'width', 'height'))
    pad_x, pad_y = .06*w, .22*h
    sx, sy = PATCH_SIZE[0]/(w+2*pad_x), PATCH_SIZE[1]/(h+2*pad_y)
    return np.array([[sx, 0, -(x-pad_x)*sx-.5], [0, sy, -(y-pad_y)*sy-.5]], np.float64)


def transform(points, matrix):
    return np.c_[points, np.ones(len(points))] @ np.asarray(matrix).T


def correlate(a, b):
    a, b = np.asarray(a, float).ravel(), np.asarray(b, float).ravel()
    a, b = a-a.mean(), b-b.mean()
    return float(a@b / max(np.linalg.norm(a)*np.linalg.norm(b), 1e-12))


class ImageEvidence:
    def __init__(self, dataset, rows, sources):
        self.dataset, self.rows, self.sources = Path(dataset), rows, sources
        self.used = {}

    @lru_cache(maxsize=512)
    def image(self, frame):
        source = self.sources[frame]; path = self.dataset/source['image']
        actual = digest(path)
        if actual != source['files'][source['image']]:
            raise ValueError('Source image hash changed')
        self.used[source['image']] = actual
        image = cv2.imread(str(path), cv2.IMREAD_GRAYSCALE)
        if image is None or image.shape[::-1] != tuple(source['size']):
            raise ValueError('Invalid native image dimensions')
        return image

    @lru_cache(maxsize=2048)
    def patch(self, key):
        row = self.rows[key]; m = patch_matrix(row)
        # OpenCV centers are index coordinates, while review polygons use edges.
        m[:, 2] += m[:, :2] @ np.array([.5, .5])
        image = cv2.warpAffine(self.image(row['frame_id']), m, PATCH_SIZE,
                               flags=cv2.INTER_LINEAR, borderMode=cv2.BORDER_REFLECT_101)
        lo, hi = np.percentile(image, [1, 99])
        image = np.clip((image.astype(float)-lo)*255/max(hi-lo, 1), 0, 255).astype(np.uint8)
        return cv2.GaussianBlur(image, (3, 3), .65)


def transfer(source_image, target_image, polygon, source_row, target_row):
    """Affine photometric alignment followed by per-vertex forward/backward LK.

    Vertex order/count are inherited, never manufactured by contour resampling.
    Failed tracking returns an explicit rejection, not an accepted box stretch.
    """
    matrix = np.eye(2, 3, dtype=np.float32)
    try:
        ecc, matrix = cv2.findTransformECC(source_image, target_image, matrix, cv2.MOTION_AFFINE,
            (cv2.TERM_CRITERIA_EPS | cv2.TERM_CRITERIA_COUNT, 100, 1e-5), None, 5)
    except cv2.error:
        return None, dict(rejection='affine_registration_failed')
    singular = np.linalg.svd(matrix[:, :2], compute_uv=False)
    if np.linalg.det(matrix[:, :2]) <= 0 or singular.min() < .7 or singular.max() > 1.4 or np.max(np.abs(matrix[:, 2])) > 28:
        return None, dict(rejection='excessive_affine_deformation', affine=matrix.tolist())
    p = transform(np.asarray(polygon), patch_matrix(source_row)).astype(np.float32).reshape(-1, 1, 2)
    guess = transform(p[:, 0], matrix).astype(np.float32).reshape(-1, 1, 2)
    opts = dict(winSize=(19, 19), maxLevel=3,
        criteria=(cv2.TERM_CRITERIA_EPS | cv2.TERM_CRITERIA_COUNT, 50, .005),
        flags=cv2.OPTFLOW_USE_INITIAL_FLOW, minEigThreshold=1e-5)
    forward, good, _ = cv2.calcOpticalFlowPyrLK(source_image, target_image, p, guess.copy(), **opts)
    backward, good_back, _ = cv2.calcOpticalFlowPyrLK(target_image, source_image, forward, p.copy(), **opts)
    fb = np.linalg.norm(backward[:, 0]-p[:, 0], axis=1)
    inverse = cv2.invertAffineTransform(patch_matrix(target_row))
    candidate = transform(forward[:, 0], inverse)
    affine_polygon = transform(guess[:, 0], inverse)
    displacement = np.linalg.norm(candidate-affine_polygon, axis=1)
    aligned = cv2.warpAffine(target_image, matrix, PATCH_SIZE, flags=cv2.INTER_LINEAR | cv2.WARP_INVERSE_MAP)
    boundary = np.zeros(source_image.shape, np.uint8)
    cv2.polylines(boundary, [np.round(p[:, 0]).astype(np.int32)], True, 255, 7)
    boundary_ncc = correlate(source_image[boundary > 0], aligned[boundary > 0])
    initial_ncc = correlate(source_image, target_image)
    metrics = dict(ecc=float(ecc), initial_ncc=initial_ncc, boundary_ncc=boundary_ncc,
        forward_backward_error_patch_pixels=fb.tolist(), max_vertex_refinement_native_pixels=float(displacement.max()),
        affine_patch_transform=matrix.tolist(), same_vertex_count=len(candidate) == len(polygon),
        quality_metrics_are_not_accuracy_probabilities=True)
    if not (good.all() and good_back.all()) or fb.max() > 1.5:
        return None, dict(metrics, rejection='unreliable_vertex_tracking')
    if ecc < .84 or boundary_ncc < .78:
        return None, dict(metrics, rejection='insufficient_image_correspondence')
    if displacement.max() > max(3., target_row['bbox']['height']*.16):
        return None, dict(metrics, rejection='vertex_refinement_too_large')
    try:
        candidate = polygon_value(candidate.tolist(), *target_row['size'])
    except ValueError as exc:
        return None, dict(metrics, rejection='invalid_transferred_polygon', validation_error=str(exc))
    old_area = abs(cv2.contourArea(np.array(affine_polygon, np.float32)))
    ratio = abs(cv2.contourArea(np.array(candidate, np.float32)))/max(old_area, 1.)
    if not .72 < ratio < 1.35:
        return None, dict(metrics, rejection='unstable_polygon_area', refinement_area_ratio=ratio)
    return candidate, dict(metrics, rejection=None, refinement_area_ratio=ratio)


def overlay(image, row, polygon, color):
    """Readable native image crop, nearest-neighbor enlarged; numbered vertices."""
    b = row['bbox']; pad = max(8, b['height']*.45)
    x0 = max(0, int(b['x']-pad)); y0 = max(0, int(b['y']-pad))
    x1 = min(image.shape[1], int(np.ceil(b['x']+b['width']+pad)))
    y1 = min(image.shape[0], int(np.ceil(b['y']+b['height']+pad)))
    crop = Image.fromarray(image[y0:y1, x0:x1]).convert('RGB')
    scale = min(6, 720/max(crop.width, 1), 225/max(crop.height, 1))
    crop = crop.resize((round(crop.width*scale), round(crop.height*scale)), Image.Resampling.NEAREST)
    canvas = Image.new('RGB', (740, 255), '#121923'); canvas.paste(crop, (10, 15))
    draw = ImageDraw.Draw(canvas)
    points = [((x-x0)*scale+10, (y-y0)*scale+15) for x, y in polygon]
    draw.line(points+[points[0]], fill=color, width=2)
    for n, (x, y) in enumerate(points, 1):
        draw.ellipse((x-2, y-2, x+2, y+2), fill=color)
        draw.text((x+3, y-10), str(n), fill=color, stroke_width=1, stroke_fill='black')
    return canvas


def package_preview(out, proposals, templates, rows, evidence, inventory):
    for folder in ('cases', 'labelme', 'masks', 'images', 'templates'):
        (out/folder).mkdir()
    cards = []
    for item in proposals:
        key, source_key = item['target_key'], item['template']['target_key']
        target, template = rows[key], templates[source_key]
        source = rows[source_key]
        panel = Image.new('RGB', (1480, 305), '#121923'); draw = ImageDraw.Draw(panel)
        draw.text((15, 8), f"Class {target['final_class_id']} | {len(item['polygon'])} vertices | human template (left) -> candidate (right)", fill='white')
        panel.paste(overlay(evidence.image(source['frame_id']), source, template['polygon'], '#55ceff'), (0, 30))
        panel.paste(overlay(evidence.image(target['frame_id']), target, item['polygon'], '#ffc247'), (740, 30))
        draw.text((15, 284), f"template {source_key} r{template['human_polygon_revision']} | target {key} | {target['split']} | pending", fill='white')
        panel.save(out/'cases'/f'{key}.png')
        Image.fromarray(evidence.image(target['frame_id'])).save(out/'images'/f'{key}.png')
        write_json(out/'templates'/f'{source_key}.json', template)
        mask = raster_mask(item['polygon'], *target['size'])
        Image.fromarray(mask.astype(np.uint8)*255).save(out/'masks'/f'{key}.png')
        write_json(out/'labelme'/f'{key}.json', dict(version='5.0.0', imagePath=f'../images/{key}.png',
            imageData=None, imageWidth=target['size'][0], imageHeight=target['size'][1],
            flags=dict(human_confirmed=False, machine_draft=True), shapes=[dict(label='pallet',
                points=item['polygon'], shape_type='polygon', group_id=target['box_index'],
                flags=dict(human_confirmed=False, machine_draft=True))], mask_template_provenance=item))
        cards.append(f'<article data-class="{target["final_class_id"]}"><h2>Class {target["final_class_id"]} · {len(item["polygon"])}顶点 · 待复核</h2>'
            f'<img loading="lazy" src="cases/{key}.png" alt="模板与候选对照">'
            f'<p>目标：{html.escape(target["frame_id"])} ／ {target["split"]}</p>'
            f'<p>模板：{html.escape(source["frame_id"])} ／人工多边形修订 {template["human_polygon_revision"]}</p>'
            f'<p>边界相关度 {item["metrics"]["boundary_ncc"]:.3f}（不是正确率）。'
            f'<a href="labelme/{key}.json">LabelMe</a> · <a href="masks/{key}.png">掩膜</a></p></article>')
    table = ''.join(f'<tr><td>{n}</td><td>{c["templates"]}</td><td>{c["eligible"]}</td><td>{c["compatible_targets"]}</td><td>{c["preview"]}</td></tr>'
                    for n, c in inventory.items())
    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')}body{background:#101720;color:#e7edf5;font:16px PreviewSans,sans-serif;margin:auto;padding:20px;max-width:1500px}a{color:#77ceff}img{width:100%;height:auto}article{border:1px solid #425269;margin:20px 0;padding:12px;border-radius:8px}p{overflow-wrap:anywhere}td,th{padding:7px;border:1px solid #425269}table{border-collapse:collapse}select{font:inherit;padding:6px}</style>
<h1>同类等顶点掩膜补充：首批待复核样例</h1><p>左侧蓝色为人工修正模板，右侧橙色为新候选。顶点数、顺序一致，位置由图像配准和逐顶点跟踪调整。当前未回写在线标注。机器相关度不是正确率，模板本身也是未确认人工草稿。</p>
<p>保留原正式划分；只匹配同类、同传感器配置、同划分；所有有过掩膜修改历史的目标均排除。每个文件只含当前目标，同图其他目标不作删除或负例解释。模板实际表达叉取面轮廓及开口凹槽，不沿用旧记录中“包含内部开口”的通用语义。</p>
<p>筛选类别 <select id="filter"><option value="">全部</option>'''
    page += ''.join(f'<option>{n}</option>' for n in inventory)
    no_match = [str(n) for n,c in inventory.items() if c['templates'] and not c['compatible_targets']]
    no_pass = [str(n) for n,c in inventory.items() if c['compatible_targets'] and not c['preview']]
    page += '</select></p><p>有模板但无同划分、同配置兼容目标的类别：'+('、'.join(no_match) or '无')+'。'
    page += '兼容目标中本轮图像匹配未通过的类别：'+('、'.join(no_pass) or '无')+'。其余无模板类别需先补人工模板。本轮是小样预览，未抽中的目标不等同于无法补标。</p><table><tr><th>Class</th><th>模板</th><th>未改掩膜/未保存</th><th>可匹配目标</th><th>首批候选</th></tr>'+table+'</table>'
    page += ''.join(cards)+'''<script>document.querySelector('#filter').onchange=e=>document.querySelectorAll('article').forEach(a=>a.hidden=!!e.target.value&&a.dataset.class!==e.target.value);</script></html>'''
    (out/'report_zh.html').write_text(page)
    from fontTools import subset
    from fontTools.ttLib import TTFont
    font_source=Path('/tmp/opencode/pallet_pose_design/NotoSansCJKsc-Regular.otf')
    font=TTFont(font_source);required={ord(c) for c in page if '\u3400'<=c<='\u9fff'}
    assert required<=set(font.getBestCmap())
    sub=subset.Subsetter();sub.populate(text=page);sub.subset(font);font.save(out/'report-font.otf')
    assert required<=set(TTFont(out/'report-font.otf').getBestCmap())
    (out/'FONT_LICENSE.txt').write_bytes((PROJECT/'pallet/assets/pose_review/FONT_LICENSE.txt').read_bytes())
    write_json(out/'font_coverage.json',dict(chinese_glyphs=len(required),all_report_Chinese_present=True,
        font_source_sha256=digest(font_source),font_sha256=digest(out/'report-font.otf')))
    # One compact contact sheet covers every represented class.
    first = {}
    for p in proposals:
        first.setdefault(p['class_id'], p['target_key'])
    contact = Image.new('RGB', (1480, max(1, len(first))*305), '#121923')
    for i, key in enumerate(first.values()):
        contact.paste(Image.open(out/'cases'/f'{key}.png'), (0, i*305))
    contact.save(out/'preview_all_classes.png')


def run(output, per_class=3, max_attempts=45):
    out = Path(output).resolve()
    if out.exists():
        raise ValueError('Use a new output directory; frozen previews are never overwritten')
    if not out.is_relative_to(PROJECT/'outputs'):
        raise ValueError('Preview output must be a new outputs subdirectory')
    out.mkdir(parents=True)
    formal = Path(json.loads((PROJECT/'configs/active_formal_dataset.json').read_text())['dataset'])
    classification = PROJECT/'outputs/pallet_appearance_center_reclassification_v1/targets.jsonl'
    annotations, sources = load_dataset(formal)
    rows = {r['target_key']: r for r in map(json.loads, classification.read_text().splitlines())}
    identities = {target_key(a['frame_id'], i): (a, b) for a in annotations for i, b in enumerate(a['boxes'])}
    if set(identities) != set(rows):
        raise ValueError('Class result does not cover the formal dataset')
    for key, row in rows.items():
        a, box = identities[key]; source = sources[a['frame_id']]
        if row['bbox'] != box or any(row[k] != a[k] for k in ('frame_id', 'split', 'group_id')):
            raise ValueError('Class result and formal identity disagree')
        row['size'] = source['size']
        if row['source_pcd_sha256'] != source['source_anchor_hash'] or row['policy_id'] != source['sensor_policy']['policy_id']:
            raise ValueError('Source provenance mismatch')
    protected = protected_snapshot(formal)
    write_json(out/'protected_formal_before.json', protected)
    live = PROJECT/'outputs/pallet_pose_human_review_v1/annotations.sqlite3'
    snapshot = out/'reviews_snapshot.sqlite3'
    with closing(sqlite3.connect(live.resolve().as_uri()+'?mode=ro', uri=True)) as src:
        with closing(sqlite3.connect(snapshot)) as dst:
            src.backup(dst)
    with closing(sqlite3.connect(snapshot.as_uri()+'?mode=ro', uri=True)) as db:
        current, templates, status = annotation_inventory(db, rows)
        events = db.execute('SELECT COUNT(*) FROM events').fetchone()[0]
        binding = json.loads(db.execute("SELECT value FROM metadata WHERE key='binding'").fetchone()[0])
    if binding['formal_manifest_sha256'] != digest(formal/'manifest.json'):
        raise ValueError('Snapshot does not belong to this formal dataset')
    evidence = ImageEvidence(formal, rows, sources)
    inventory = {n: dict(total=sum(r['final_class_id'] == n for r in rows.values()),
        templates=sum(t['row']['final_class_id'] == n for t in templates.values()),
        eligible=sum(r['final_class_id'] == n and status[k] == 'eligible' for k, r in rows.items()), preview=0,compatible_targets=0)
        for n in sorted({r['final_class_id'] for r in rows.values()})}
    # Rank every eligible pair cheaply, then spend registration effort on a small
    # diverse preview. This ranking is annotation assistance, not model training.
    pairs = defaultdict(list); coverage = Counter()
    for key, row in sorted(rows.items()):
        if status[key] != 'eligible':
            continue
        options = [k for k, t in templates.items() if compatible(t['row'], row)]
        if not options:
            coverage['no_compatible_template'] += 1
            continue
        coverage['has_compatible_template'] += 1
        inventory[row['final_class_id']]['compatible_targets'] += 1
        patch = evidence.patch(key)
        ranked = sorted(((correlate(evidence.patch(k), patch), k) for k in options), reverse=True)
        pairs[row['final_class_id']].append((ranked[0][0], key, ranked[:3]))
    proposals, attempts = [], []
    for cls, ranked_targets in sorted(pairs.items()):
        ranked_targets.sort(key=lambda r: (-r[0], r[1])); selected_groups = Counter()
        remaining = ranked_targets[:]
        for _ in range(min(max_attempts, len(remaining))):
            if inventory[cls]['preview'] >= per_class:
                break
            # Prefer a new collection group, then the strongest image match.
            remaining.sort(key=lambda r: (selected_groups[rows[r[1]]['group_id']], -r[0], r[1]))
            _, key, options = remaining.pop(0); row = rows[key]
            for similarity, template_key in options:
                if similarity < .55:
                    continue
                template = templates[template_key]
                poly, metrics = transfer(evidence.patch(template_key), evidence.patch(key), template['polygon'], template['row'], row)
                attempts.append(dict(target_key=key, template_key=template_key, class_id=cls, metrics=metrics))
                if poly is None:
                    continue
                old = current.get(key)
                proposal = dict(schema=VERSION, target_key=key, class_id=cls, source=row,
                    polygon=poly, vertex_count=len(poly), status='machine_draft_pending_visual_review',
                    human_mask_confirmed=False, automatic_training_eligible=False, robot_command_eligible=False,
                    production_saved=False, mask_semantics='inherited_human_fork_face_contour_with_aperture_notches',
                    template=dict(target_key=template_key, class_id=cls, split=template['row']['split'],
                        snapshot_revision=template['revision'], human_polygon_revision=template['human_polygon_revision'],
                        human_event_sha256=template['human_event_sha256'], vertex_count=len(template['polygon']),
                        template_human_confirmed=template['human_mask_confirmed']),
                    target_expected_revision=old['revision'] if old else 0,
                    target_snapshot_payload_sha256=hashlib.sha256(canonical(old)).hexdigest() if old else None,
                    snapshot_sha256=digest(snapshot), formal_manifest_sha256=binding['formal_manifest_sha256'],
                    class_assignments_sha256=digest(classification), metrics=metrics,
                    flags=['machine_mask_requires_review', 'template_is_unconfirmed_human_edit']+
                        (['class_assignment_requires_review'] if row.get('classification_review_required') else []),
                    geometry_pose_policy='no_pose_or_selected_points_copied; changing_live_mask_requires_new_geometry')
                proposals.append(proposal); inventory[cls]['preview'] += 1
                selected_groups[row['group_id']] += 1
                break
        print(json.dumps(dict(class_id=cls, preview=inventory[cls]['preview'], eligible_pairs=len(ranked_targets))), flush=True)
    (out/'proposals.jsonl').write_bytes(b''.join(canonical(v)+b'\n' for v in proposals))
    write_json(out/'template_inventory.json', dict(version=VERSION, classes=inventory,
        templates=list(templates.values()), snapshot_saved=len(current), snapshot_events=events,
        eligibility_counts=dict(Counter(status.values())), eligibility=status))
    (out/'registration_attempts.jsonl').write_bytes(b''.join(canonical(v)+b'\n' for v in attempts))
    package_preview(out, proposals, templates, rows, evidence, inventory)
    write_json(out/'used_image_hashes.json', evidence.used)
    if protected_snapshot(formal) != protected:
        raise ValueError('Protected formal files changed')
    # Verify snapshot events still exist unchanged; live concurrent human saves
    # may append new events, so comparing the whole SQLite file would be wrong.
    with closing(sqlite3.connect(live.resolve().as_uri()+'?mode=ro', uri=True)) as db:
        db.execute('ATTACH DATABASE ? AS frozen', (snapshot.as_uri()+'?mode=ro',))
        missing = db.execute('SELECT COUNT(*) FROM frozen.events f LEFT JOIN main.events e ON e.id=f.id '
                             'WHERE e.payload IS NULL OR e.payload!=f.payload OR e.target_key!=f.target_key OR e.revision!=f.revision').fetchone()[0]
        if missing:
            raise ValueError('Historical events no longer match snapshot')
    manifest = dict(state='preview_ready_pending_user_confirmation', version=VERSION,
        created_at=datetime.now(timezone.utc).isoformat(), snapshot_saved=len(current), snapshot_events=events,
        templates=len(templates), classes=inventory, coverage=dict(coverage), proposals=len(proposals),
        source_vertex_counts=dict(Counter(len(t['polygon']) for t in templates.values())),
        formal_manifest_sha256=binding['formal_manifest_sha256'], snapshot_sha256=digest(snapshot),
        classification_sha256=digest(classification), protected_files_verified=len(protected),
        original_history_events_verified=events, production_database_writes=0,
        original_splits_preserved=True, cross_split_template_transfers=0,
        pose_model_training_or_inference_changes=False, code_sha256=digest(__file__))
    write_json(out/'manifest.json', manifest)
    with ZipFile(out/'mask_template_preview.zip', 'w', ZIP_DEFLATED) as archive:
        for path in sorted(out.rglob('*')):
            if path.is_file() and path.suffix not in ('.sqlite3', '.zip') and '-shm' not in path.name and '-wal' not in path.name:
                archive.write(path, path.relative_to(out))
    print(json.dumps(dict(state=manifest['state'], proposals=len(proposals), output=str(out))), flush=True)


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('--output', type=Path, default=PROJECT/'outputs/pallet_mask_template_preview_v3')
    parser.add_argument('--per-class', type=int, default=3)
    args = parser.parse_args()
    if not 1 <= args.per_class <= 10:
        raise ValueError('Preview permits 1–10 samples per class')
    cv2.setNumThreads(1)
    run(args.output, args.per_class)


if __name__ == '__main__':
    main()
