"""Independently seal publication 6; never generate proposals or write live stores.

Run after the generator has finished. Human request completions are audited as
direct saved polygons, not self-transfers. All machine attempts (including failed
ones) are replayed with the pinned original gates. Only the validation report and
the exclusively created success seal may be written by this program.
"""
from __future__ import annotations

import argparse
from collections import Counter
from contextlib import closing
from datetime import datetime, timezone
import hashlib
import json
from pathlib import Path
import re
import sqlite3
import sys

import cv2
import numpy as np
from PIL import Image

PROJECT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(PROJECT))
from scripts import verify_mask_template_refined_next as previous
from pallet.cluster_targets import digest, protected_snapshot
from pallet.mask_boundary_review import affine_reference, beam_boundary_audit
from pallet.mask_template_transfer import ImageEvidence, annotation_inventory, compatible, correlate, transfer
from pallet.pose_review_geometry import canonical, polygon_value, raster_mask

prior = previous.prior
require, sha = prior.require, prior.sha
read_json, read_jsonl, indexed = prior.read_json, prior.read_jsonl, prior.indexed
CLASSES, LIMIT, QUARANTINE = prior.CLASSES, prior.LIMIT, prior.QUARANTINE
POSE_ORIGIN = 'original_pose_human_revision'
GALLERY_ORIGIN = prior.ORIGIN
NAMESPACE = 'quota_generation'
PARENT = PROJECT/'outputs/pallet_mask_template_refined_v3'
OUTPUT = PROJECT/'outputs/pallet_mask_quota_completion_v1'
REQUESTS = PROJECT/'outputs/pallet_mask_template_requests_v1'
PINNED = {
    'manifest.json': '2e9e575b7dd2cc2adbb1321b709dc7c6efddc718facb4f9cfcab1d6acf7bf6a9',
    'proposals.jsonl': '9a9eda71e38fbaf9165181a5121509cacdf1027cedfb0c519ec8693ec2bec947',
    'verification.json': '5f67fa63ca26f61995a59eb6eab04169b60ac7fff7d0056dead44992aa2323ca',
    'artifact_hashes.json': 'aeb620ad846076664bc4d2fb78ed3dcb07d7c6376054289fcb69af55011a8365',
    'protected_formal_before.json': '02de366b0c0f691c2c11457c3f6976fe0bed32579992403bfbee3ea2be8ee4b1',
    'template_inventory.json': '9cd6507a47ef6de1bd21c0a6b06785b13ef4476c5b6ec7a662ffc95ef26009c2',
    'used_image_hashes.json': '25ec2fefdac4156ad5d216de253b3af1043159f69b42e1fba88503834b27bf7f',
}
REQUEST_PINS = {
    'manifest.json': '21ba201b469aeb9b8474dbafd77f872b6a141b6b1bf0e9bc025c8af8877fd82d',
    'requests.jsonl': '2c5409388bfaa41effd978ab644b64a4b9175b1d005e416500f19a4767f5c6f0',
    'verification.json': 'eb3593c29f854795a217f69b7b3338530ae0de4233b9bed12314e56f9762a2c7',
}
ORIGINAL_CODE = {
    **previous.ORIGINAL_CODE,
    'pallet/mask_template_refined_next.py': 'd030ea411006bb5aae4e921b361ad786662884adda3200212e1b92c282c54586',
    'scripts/verify_mask_template_refined_next.py': 'a44e59b6d09752dd9a161d49dbccc25034bef41e98768be2190e5e06e92082e9',
}
FALSE_FLAGS = ('human_mask_confirmed', 'human_pose_confirmed', 'automatic_training_eligible',
               'robot_command_eligible', 'ground_truth_eligible')


def check_frozen_inputs():
    publications = previous.check_frozen_inputs()
    for name, expected in PINNED.items():
        require(digest(PARENT/name) == expected, f'Frozen publication 5 changed: {name}')
    for name, expected in REQUEST_PINS.items():
        require(digest(REQUESTS/name) == expected, f'Frozen request worklist changed: {name}')
    for name, expected in ORIGINAL_CODE.items():
        require(digest(PROJECT/name) == expected, f'Frozen original code changed: {name}')
    manifest, verified = read_json(PARENT/'manifest.json'), read_json(PARENT/'verification.json')
    require(verified['state'] == 'passed' and verified['publication_version'] == 5
            and verified['proposals_verified'] == 140 and manifest['proposals'] == 140
            and verified['proposals_sha256'] == manifest['proposals_sha256'] == PINNED['proposals.jsonl']
            and verified['manifest_sha256'] == PINNED['manifest.json'], 'Publication 5 seal differs')
    proposals = indexed(read_jsonl(PARENT/'proposals.jsonl'))
    require(len(proposals) == 140, 'Expected 140 canonical parent objects')
    publications[5] = dict(path=PARENT, proposals=proposals, manifest=manifest)
    return publications


def independent_pose_templates(store, rows):
    """Recover human events from raw SQLite payloads, independently of inventory."""
    last_human = {}
    for event_id, key, revision, raw in store['events']:
        value = json.loads(raw)
        if value.get('event_kind') not in {'unit_normalization', 'axes_normalization', 'mask_template_proposal'} \
                and value.get('state') != 'deleted':
            last_human[key] = (event_id, revision, value, hashlib.sha256(raw.encode()).hexdigest())
    templates = {}
    for key, value in store['current'].items():
        if value.get('state') in ('deleted', 'deferred') or len(value.get('polygon', [])) <= 4:
            continue
        human = last_human.get(key)
        if human is None or human[2].get('polygon') != value['polygon']:
            continue
        require(key in rows, f'Unknown human template: {key}')
        polygon_value(value['polygon'], *rows[key]['size'])
        templates[key] = dict(row=rows[key], polygon=value['polygon'], revision=value['revision'],
            human_polygon_revision=human[1], human_event_sha256=human[3],
            current_payload_sha256=sha(value), human_mask_confirmed=value.get('human_mask_confirmed', False))
    return templates


def pose_provenance(template, snapshot_sha):
    return dict(target_key=template['row']['target_key'], revision=template['revision'],
                payload_sha256=template['current_payload_sha256'],
                human_polygon_revision=template['human_polygon_revision'],
                human_event_sha256=template['human_event_sha256'],
                polygon_sha256=sha(template['polygon']), snapshot_sha256=snapshot_sha)


def no_confirmation(value, context):
    for field in FALSE_FLAGS:
        require(value[field] is False, f'{context}: {field} must be false')


def check_partition(old, manual, new, combined, accepted):
    require(not (set(old) & set(manual) or set(old) & set(new) or set(manual) & set(new)),
            'Historical/manual/machine target sets overlap')
    require(set(combined) == set(old) | set(manual) | set(new), 'Cumulative inventory differs')
    require(set(manual).isdisjoint(accepted) and set(old).isdisjoint(accepted)
            and set(new) <= set(accepted), 'Manual/self-source or old object treated as accepted transfer')
    for inventory in (old, manual, new):
        for key, value in inventory.items():
            require(canonical(value) == canonical(combined[key]), f'Cumulative canonical object differs: {key}')
    for key in new:
        require(canonical(new[key]) == canonical(accepted[key]), f'Selected candidate differs: {key}')


def check_manual(proposal, request, pose, direct, row, pose_sha, formal_sha, classification_sha):
    key = proposal['target_key']
    value = pose['current'].get(key)
    require(value is not None and key in direct, f'Manual request has no current direct human polygon: {key}')
    template = direct[key]
    require(request['target_key'] == key and request['class_id'] == row['final_class_id']
            and proposal['class_id'] == row['final_class_id'] and proposal['source'] == row,
            f'Manual request identity/class differs: {key}')
    for field in ('target_key', 'target_id', 'frame_id', 'split', 'group_id', 'box_index', 'bbox',
                  'size', 'policy_id', 'source_pcd_sha256'):
        require(request['source'][field] == row[field] == value['source'][field],
                f'Manual request/pose source {field} differs: {key}')
    require(request['source']['formal_manifest_sha256'] == formal_sha
            and proposal['formal_manifest_sha256'] == formal_sha
            and proposal['class_assignments_sha256'] == classification_sha, f'Manual dataset binding differs: {key}')
    require(proposal['polygon'] == value['polygon'] == template['polygon']
            and proposal['vertex_count'] == len(value['polygon']) > 4, f'Manual polygon/topology differs: {key}')
    polygon_value(proposal['polygon'], *row['size'])
    require(proposal['status'] == 'human_edited_draft_pending_confirmation' and proposal['human_edited'] is True,
            f'Manual status must honestly describe saved unconfirmed human work: {key}')
    no_confirmation(proposal, f'Manual {key}')
    require('production_saved' not in proposal or proposal['production_saved'] is False,
            f'Manual cannot claim production write: {key}')
    for field in ('human_mask_confirmed', 'human_pose_confirmed', 'automatic_training_eligible', 'robot_command_eligible'):
        require(value[field] is False, f'Manual source {field} must be false: {key}')
    require(proposal['origin'] == POSE_ORIGIN and proposal['schema'] == 'saved_pose_mask_gallery_entry_v1'
            and proposal['manual_request_sha256'] == sha(request)
            and proposal['original_pose_url'] == request['pose_annotation_url']
            and proposal['rendering_id'] == NAMESPACE+':'+key
            and proposal['source_label_kind'] == 'human_mask_source_manual_template_draft'
            and proposal['pose_snapshot_saved'] is True
            and proposal['pose_store_written'] is False and proposal['gallery_store_written'] is False,
            f'Manual source/schema/save claims differ: {key}')
    require(request['source']['viewpoint_candidate'] == row['viewpoint_candidate'], f'Manual viewpoint differs: {key}')
    require(proposal['snapshot_sha256'] == pose_sha
            and proposal['target_expected_revision'] == value['revision']
            and proposal['target_snapshot_payload_sha256'] == sha(value), f'Manual current snapshot binding differs: {key}')
    binding = proposal['template']
    require(binding['target_key'] == key and binding['origin'] == POSE_ORIGIN
            and binding['class_id'] == row['final_class_id'] and binding['split'] == row['split']
            and binding['vertex_count'] == len(value['polygon'])
            and binding['snapshot_revision'] == template['revision']
            and binding['current_payload_sha256'] == template['current_payload_sha256']
            and binding['human_polygon_revision'] == template['human_polygon_revision']
            and binding['human_event_sha256'] == template['human_event_sha256']
            and binding['template_human_confirmed'] is False
            and binding['pose_review'] == pose_provenance(template, pose_sha), f'Manual self-source provenance differs: {key}')
    require('continuation' not in proposal and not proposal.get('metrics'), f'Manual polygon claims transfer metrics: {key}')


def check_diversity(base, accepted, new, outcomes):
    """Replay quota selection from the historical PLUS direct-manual frame base."""
    selected, frames = set(), {p['source']['frame_id'] for p in base.values()}
    for cls in CLASSES:
        previous_class = [p for p in base.values() if p['class_id'] == cls]
        groups = Counter(p['source']['group_id'] for p in previous_class)
        remaining = LIMIT-len(previous_class)
        require(remaining >= 0, f'Human/base quota already exceeds {LIMIT}: {cls}')
        pending = [p for p in accepted.values() if p['class_id'] == cls]
        while pending:
            candidate = min(pending, key=lambda p: (groups[p['source']['group_id']],
                -p['metrics']['boundary_ncc'], -p['metrics']['ecc'], p['target_key']))
            pending.remove(candidate)
            key, frame = candidate['target_key'], candidate['source']['frame_id']
            if frame in frames:
                reason = 'accepted_duplicate_frame_not_selected'
            elif remaining == 0:
                reason = 'accepted_quota_full_not_selected'
            else:
                reason = 'new_proposal'
                frames.add(frame)
                groups[candidate['source']['group_id']] += 1
                selected.add(key)
                remaining -= 1
            require(outcomes[key]['reason'] == reason, f'Diversity disposition differs: {key}')
    require(selected == set(new), 'Selected machine candidates differ from diversity/quota policy')


def audit_attempts(out, rows, status, gallery, old, manual, templates, accepted, outcomes, evidence):
    attempts = read_jsonl(out/'registration_attempts.jsonl')
    bytarget = {}
    for trial in attempts:
        key = trial['target_key']
        require(key in rows and trial['class_id'] == rows[key]['final_class_id'], 'Attempt identity differs')
        bytarget.setdefault(key, []).append(trial)
    eligible = set()
    for key, row in rows.items():
        protected = ('previously_quarantined' if key == QUARANTINE else 'already_published' if key in old else
                     'saved_manual_source_counted' if key in manual else
                     'gallery_history_protected' if key in gallery['history_keys'] else status[key])
        if protected == 'eligible' and row['final_class_id'] not in CLASSES:
            protected = 'class_not_requested'
        if protected != 'eligible':
            require(outcomes[key]['reason'] == protected and key not in bytarget and key not in accepted,
                    f'Protected outcome/attempt differs: {key}')
            continue
        eligible.add(key)
        choices = [k for k, t in templates.items() if compatible(t['row'], row)]
        if not choices:
            require(outcomes[key]['reason'] == 'no_compatible_template' and key not in bytarget and key not in accepted,
                    f'False no-compatible-template outcome: {key}')
            continue
        ranked = sorted(((correlate(evidence.patch(k), evidence.patch(key)), k) for k in choices), reverse=True)
        passing = [k for similarity, k in ranked if similarity >= .55]
        trials = bytarget.get(key, [])
        if key in accepted:
            source = accepted[key]['template']['target_key']
            require(source in passing, f'Accepted template below initial gate: {key}')
            expected = passing[:passing.index(source)+1]
            continuation = accepted[key]['continuation']
            require(continuation['batch'] == 6 and continuation['all_compatible_targets_scanned'] is True
                    and continuation['recursive_candidate_propagation'] is False
                    and continuation['template_rank'] == next(i for i, (_, k) in enumerate(ranked, 1) if k == source),
                    f'Original first-success rank/continuation differs: {key}')
        else:
            expected = passing
            reason = 'registration_or_boundary_rejected' if passing else 'image_similarity_below_gate'
            require(outcomes[key]['reason'] == reason, f'False rejection outcome: {key}')
        require([trial['template_key'] for trial in trials] == expected, f'Attempt coverage/order differs: {key}')
        for i, trial in enumerate(trials):
            if key in accepted and i == len(trials)-1:
                prior.equal_metrics(trial['metrics'], accepted[key]['metrics'], f'{key}.accepted_attempt')
                continue  # The accepted geometry and every metric leaf are recomputed separately.
            template = templates[trial['template_key']]
            polygon, metrics = transfer(evidence.patch(trial['template_key']), evidence.patch(key),
                                        template['polygon'], template['row'], row)
            if polygon is not None:
                reference = affine_reference(dict(source=row, metrics=metrics), template)
                guard = beam_boundary_audit(evidence.image(row['frame_id']), polygon, reference)
                metrics['boundary_guard'] = guard
                if guard['state'] != 'passed':
                    polygon = None
                    metrics['rejection'] = 'local_beam_boundary_review_required'
            require(polygon is None, f'Passing attempt falsely rejected: {key}/{trial["template_key"]}')
            prior.equal_metrics(trial['metrics'], metrics, f'{key}.{trial["template_key"]}.rejected_attempt')
    require(set(bytarget) <= eligible and set(accepted) <= eligible, 'Attempt/candidate outside eligible targets')
    accepted_reasons = {'new_proposal', 'accepted_duplicate_frame_not_selected', 'accepted_quota_full_not_selected'}
    require({k for k, v in outcomes.items() if v['reason'] in accepted_reasons} == set(accepted),
            'Accepted outcomes do not exactly cover machine candidates')
    return eligible, len(attempts)


def check_assets(out, proposal, row, evidence, manual=False):
    if not manual:
        prior.verify_assets(out, proposal, row, evidence)
        return
    key = proposal['target_key']
    require(re.fullmatch('[0-9a-f]{24}', key) is not None, 'Unsafe manual asset key')
    for folder, ext in (('images', 'png'), ('masks', 'png'), ('labelme', 'json'), ('cases', 'png')):
        path = out/folder/f'{key}.{ext}'
        require(path.is_file() and not path.is_symlink() and path.resolve().is_relative_to(out), f'Missing/unsafe asset: {path}')
    with Image.open(out/'images'/f'{key}.png') as image:
        require(image.format == 'PNG' and image.mode == 'L' and image.size == tuple(row['size']), f'Manual native image differs: {key}')
        np.testing.assert_array_equal(np.asarray(image), evidence.image(row['frame_id']))
    with Image.open(out/'masks'/f'{key}.png') as mask:
        require(mask.format == 'PNG' and mask.mode == 'L' and mask.size == tuple(row['size']), f'Manual native mask differs: {key}')
        np.testing.assert_array_equal(np.asarray(mask), raster_mask(proposal['polygon'], *row['size']).astype(np.uint8)*255)
    with Image.open(out/'cases'/f'{key}.png') as image:
        image.verify()
    label = read_json(out/'labelme'/f'{key}.json')
    require(label['imageWidth'] == row['size'][0] and label['imageHeight'] == row['size'][1]
            and label['imagePath'] == f'../images/{key}.png' and label['imageData'] is None
            and len(label['shapes']) == 1 and label['mask_template_provenance'] == proposal,
            f'Manual LabelMe identity/provenance differs: {key}')
    shape = label['shapes'][0]
    require(shape['points'] == proposal['polygon'] and shape['shape_type'] == 'polygon'
            and shape['group_id'] == row['box_index'] and shape['label'] == 'pallet', f'Manual LabelMe polygon differs: {key}')
    for flags in (label['flags'], shape['flags']):
        require(flags['human_confirmed'] is False and flags.get('human_edited') is True
                and flags.get('machine_draft') is False, f'Manual LabelMe misleading human/machine flags: {key}')
        for field in ('automatic_training_eligible', 'robot_command_eligible', 'ground_truth_eligible', 'independent_gallery_saved'):
            require(flags[field] is False, f'Manual LabelMe {field} must be false: {key}')


def check_live_dependencies(frozen, live, templates, accepted, manual, rows):
    for kind in frozen:
        prior.preserve_events(frozen[kind], live[kind])
    require(canonical(live['gallery']['current']) == canonical(frozen['gallery']['current']),
            'Gallery saved inventory changed since snapshot; regenerate quota counts')
    status = prior.pose_status(live['pose'], rows)
    for key in set(templates) | set(manual):
        for kind in ('pose', 'gallery'):
            require(canonical(live[kind]['current'].get(key)) == canonical(frozen[kind]['current'].get(key)),
                    f'{kind} human dependency changed since snapshot: {key}')
    for key in accepted:
        prior.require_target_eligible(key, status, live['gallery'], rows)
        require(canonical(live['pose']['current'].get(key)) == canonical(frozen['pose']['current'].get(key)),
                f'Machine target pose changed since snapshot: {key}')


def configuration_hashes():
    names = ['configs/active_formal_dataset.json', 'configs/active_mask_gallery.json',
             'configs/active_mask_template_proposals.json', 'configs/active_mask_template_requests.json',
             'configs/active_pose_review.json', 'configs/active_pose_annotations.json',
             'configs/active_pose_refinement.json', 'configs/active_pose_dataset.json',
             'pallet/mask_gallery.py', 'pallet/mask_gallery_review.py', 'pallet/pose_review.py',
             'outputs/pallet_pose_human_review_v1/access_key.txt']
    return {name: digest(PROJECT/name) for name in names}


def check_manual_records(out, manual, snapshot, pose_sha):
    records = indexed(read_jsonl(out/'manual_source_records.jsonl'))
    require(set(records) == set(manual), 'Manual frozen source-record coverage differs')
    with closing(sqlite3.connect(snapshot.resolve().as_uri()+'?mode=ro&immutable=1', uri=True)) as db:
        db.execute('PRAGMA query_only=ON')
        for key, proposal in manual.items():
            record = records[key]
            current_rows = db.execute('SELECT revision,payload FROM annotations WHERE target_key=?', (key,)).fetchall()
            event_rows = db.execute('SELECT id,revision,payload FROM events WHERE target_key=? AND revision=?',
                                    (key, proposal['template']['human_polygon_revision'])).fetchall()
            require(len(current_rows) == len(event_rows) == 1, f'Ambiguous manual SQLite source: {key}')
            revision, raw = current_rows[0]
            event_id, event_revision, event_raw = event_rows[0]
            expected = dict(schema='saved_pose_mask_source_freeze_v1', target_key=key,
                snapshot_sha256=pose_sha, current_revision=revision,
                current_payload_sha256=sha(json.loads(raw)), current_payload_raw=raw,
                current_payload=json.loads(raw), current_payload_raw_sha256=hashlib.sha256(raw.encode()).hexdigest(),
                human_event_id=event_id, human_polygon_revision=event_revision,
                human_event_sha256=hashlib.sha256(event_raw.encode()).hexdigest(),
                human_event_payload_raw=event_raw, human_event_payload=json.loads(event_raw),
                polygon_sha256=sha(proposal['polygon']))
            require(record == expected, f'Manual exact SQLite payload/event freeze differs: {key}')


def expected_counts(old, manual, new, gallery):
    """No generator quota helpers: count distinct source frames and explicit sets."""
    counts = prior.count_frames(list(old.values())+list(manual.values())+list(new.values()))
    result = {}
    for cls in CLASSES:
        historic = [p for p in old.values() if p['class_id'] == cls]
        human = [p for p in manual.values() if p['class_id'] == cls]
        machines = [p for p in new.values() if p['class_id'] == cls]
        saved = sum(p['target_key'] in gallery['current'] for p in historic)
        total = counts[str(cls)]['distinct_frames']
        result[str(cls)] = dict(old_total=len(historic), manual_added=len(human), added_saved_human=len(human),
            saved_gallery_human=saved, saved_pose_human=len(human), saved_human=saved+len(human),
            prior_machine_pending=len(historic)-saved, new_candidates=len(machines), total=total,
            missing=LIMIT-total, goal=LIMIT, distinct_frames=total,
            saved_fine_edits=sum(p['target_key'] in gallery['current'] and
                len(gallery['current'][p['target_key']].get('polygon', [])) > 4 for p in historic)+len(human))
    return result, counts


def check_rendering(out, inventory, parent_inventory, templates, old, manual, new):
    inherited = parent_inventory['templates']
    actual = indexed(inventory['templates'], 'rendering_id')
    old_templates = indexed(inherited, 'rendering_id')
    require(all(actual.get(k) == v for k, v in old_templates.items()), 'Historical rendering namespace/payload changed')
    latest = {NAMESPACE+':'+key: dict(template, rendering_id=NAMESPACE+':'+key) for key, template in templates.items()}
    require(not (set(latest) & set(old_templates)) and set(actual) == set(old_templates) | set(latest),
            'Historical/latest rendering namespace coverage differs')
    for key, value in latest.items():
        require(actual[key] == value, f'Latest direct-human template differs: {key}')
        source_key = value['row']['target_key']
        require(read_json(out/NAMESPACE/'templates'/f'{source_key}.json') == templates[source_key],
                f'Exported direct-human template differs: {source_key}')
    expected = {key: parent_inventory['rendering_by_target'][key] for key in old}
    expected.update({key: NAMESPACE+':'+p['template']['target_key'] for key, p in {**manual, **new}.items()})
    require(inventory['rendering_by_target'] == expected, 'Proposal rendering/source mapping differs')
    origins = dict(Counter(t['origin'] for t in templates.values()))
    require(inventory['historical_templates'] == len(inherited)
            and inventory['generation_template_namespace'] == NAMESPACE
            and inventory['generation_template_keys'] == sorted(templates)
            and inventory['generation_templates'] == len(templates)
            and inventory['generation_templates_by_origin'] == origins, 'Rendering inventory counts differ')


def check_preserved_assets(out, old):
    hashes = read_json(out/'preserved_parent_assets.json')
    names = {f'{folder}/{key}.{ext}' for key in old for folder, ext in
             (('cases', 'png'), ('images', 'png'), ('masks', 'png'), ('labelme', 'json'))}
    names |= {str(p.relative_to(PARENT)) for directory in ('templates', 'refined', 'generation')
              for p in (PARENT/directory).rglob('*') if p.is_file()}
    names.add('vertex2_before_after.png')
    require(set(hashes) == names, 'Preserved original-140 assets/namespaces inventory differs')
    parent_artifacts = read_json(PARENT/'artifact_hashes.json')
    for name, expected in hashes.items():
        require(expected == parent_artifacts[name] == digest(PARENT/name) == digest(out/name),
                f'Historical asset differs from parent frozen inventory: {name}')


def check_report(out, combined, old, manual, new, gallery, classes):
    from fontTools.ttLib import TTFont
    page = (out/'report_zh.html').read_text()
    parsed = prior.ReportInventory()
    parsed.feed(page)
    articles = indexed(parsed.articles, 'id')
    require(set(articles) == {'target-'+key for key in combined}, 'Report target inventory differs')
    for key, proposal in combined.items():
        article = articles['target-'+key]
        require(article['data-class'] == str(proposal['class_id'])
                and article['data-batch'] == ('new' if key in manual or key in new else 'previous')
                and article['data-kind'] == ('manual' if key in manual else 'machine'), f'Report card identity/kind differs: {key}')
    expected_cells = []
    for cls in CLASSES:
        c = classes[str(cls)]
        expected_cells.extend(str(v) for v in (cls, c['old_total'], c['manual_added'], c['new_candidates'], c['total'], c['missing']))
    require(parsed.cells == expected_cells, 'Report manual/machine/cumulative/shortfall totals differ')
    summaries = (f'历史候选共 {len(old)} 份', f'已保存人工修订 {len(set(old) & set(gallery["current"]))} 份',
                 f'机器候选待复核 {len(set(old)-set(gallery["current"]))} 份',
                 f'本轮计入已保存人工描绘 {len(manual)} 份', f'本轮新增机器候选 {len(new)} 份')
    require(all(value in page for value in summaries), 'Report summary conflates saved human work with machine drafts')
    require('不是机器迁移' in page and '未确认真值' in page and 'id="only-new" checked' in page,
            'Report lacks honest manual/draft status or new-only default')
    required = {ord(c) for c in page if '\u3400' <= c <= '\u9fff'}
    with TTFont(out/'report-font.otf') as font:
        require(required <= set(font.getBestCmap()), 'Chinese report font coverage incomplete')
    coverage = read_json(out/'font_coverage.json')
    require(coverage['all_report_Chinese_present'] is True and coverage['chinese_glyphs'] == len(required)
            and coverage['font_sha256'] == digest(out/'report-font.otf'), 'Font coverage evidence differs')
    require((out/'FONT_LICENSE.txt').is_file(), 'Missing report font license')


def check_snapshot_manifest(out, snapshots, frozen, publications, manifest, formal_sha):
    from pallet.mask_gallery_review import VERSION as EDITOR_VERSION
    snapshot_manifest = read_json(out/'snapshot_manifest.json')
    require(snapshot_manifest['formal_manifest_sha256'] == formal_sha, 'Snapshot manifest formal binding differs')
    for kind in ('pose', 'gallery'):
        path, store = snapshots[kind], frozen[kind]
        require(snapshot_manifest[kind] == dict(path=path.name, backup='backups/'+path.name,
                sha256=digest(path), saved=len(store['current']), events=len(store['events'])), f'{kind} snapshot manifest differs')
    request_hashes = {str(REQUESTS/name): value for name, value in REQUEST_PINS.items()}
    require(snapshot_manifest['manual_requests'] == dict(directory=str(REQUESTS), count=24, frozen_input_sha256=request_hashes)
            and manifest['manual_request_input_sha256'] == request_hashes
            and manifest['requests_sha256'] == REQUEST_PINS['requests.jsonl'], 'Manual request input freeze differs')
    expected_publications = {}
    for version, pub in publications.items():
        path = pub['path']
        proposal_sha = digest(path/'proposals.jsonl')
        expected_publications[str(version)] = dict(path=str(path), proposals_sha256=proposal_sha,
            manifest_sha256=digest(path/'manifest.json'), verification_sha256=digest(path/'verification.json'),
            binding=sha(dict(formal=formal_sha, proposals=proposal_sha, editor_version=EDITOR_VERSION)))
    require(snapshot_manifest['source_publications'] == expected_publications, 'Historical snapshot publication identities differ')


def audit(out, pose_live, gallery_live):
    verifier_sha = digest(__file__)
    config_hashes = configuration_hashes()
    pose_config = read_json(PROJECT/'configs/active_pose_review.json')
    gallery_config = read_json(PROJECT/'configs/active_mask_gallery.json')
    require(Path(pose_live).resolve() == (PROJECT/pose_config['database']).resolve()
            and Path(gallery_live).resolve() == (PROJECT/gallery_config['review_directory']/'mask_reviews.sqlite3').resolve(),
            'Live inputs must be the configured production review stores')
    publications = check_frozen_inputs()
    old = publications[5]['proposals']
    parent_manifest = publications[5]['manifest']
    manifest = read_json(out/'manifest.json')
    artifacts = read_json(out/'artifact_hashes.json')
    artifact_inventory_sha = digest(out/'artifact_hashes.json')
    prior.check_artifacts(out, artifacts)
    inventory_paths = {str(p.relative_to(out)) for p in out.rglob('*') if p.is_file()
                       and str(p.relative_to(out)) not in ('artifact_hashes.json', 'validation_report.json')}
    require(inventory_paths == set(artifacts), 'Frozen artifact inventory does not cover all generated files')
    require(manifest['publication_version'] == 6 and manifest['method'] == 'original', 'Expected publication 6 original method only')
    require(Path(manifest['parent']).resolve() == PARENT.resolve()
            and manifest['parent_proposals_sha256'] == PINNED['proposals.jsonl']
            and manifest['parent_verification_sha256'] == PINNED['verification.json'], 'Frozen parent binding differs')
    generator_sha = digest(PROJECT/'pallet/mask_quota_completion.py')
    require(manifest['code_sha256'] == generator_sha, 'Generator hash differs')
    for field, name in (('transfer_code_sha256', 'pallet/mask_template_transfer.py'),
                        ('boundary_code_sha256', 'pallet/mask_boundary_review.py'),
                        ('attempt_code_sha256', 'pallet/mask_template_continue.py')):
        require(manifest[field] == ORIGINAL_CODE[name], f'Original gate provenance differs: {field}')
    for name, expected in manifest['frozen_code_sha256'].items():
        require(name in ORIGINAL_CODE or name == 'pallet/mask_quota_completion.py', f'Unexpected frozen-code dependency: {name}')
        require(expected == (generator_sha if name == 'pallet/mask_quota_completion.py' else ORIGINAL_CODE[name])
                == digest(PROJECT/name), f'Frozen code hash differs: {name}')
    for field in ('thresholds_relaxed', 'recursive_candidate_propagation', 'automatic_human_confirmation',
                  'automatic_training_eligible', 'robot_command_eligible', 'ground_truth_eligible',
                  'manual_source_snapshots_imported_into_gallery_store'):
        require(manifest[field] is False, f'Manifest {field} must be false')
    require(manifest['production_database_writes'] == manifest['cross_split_template_transfers'] == 0
            and manifest['original_splits_preserved'] is True, 'Manifest write/split policy differs')
    for name, field in (('proposals.jsonl', 'proposals_sha256'), ('new_proposals.jsonl', 'new_proposals_sha256'),
                        ('manual_proposals.jsonl', 'manual_proposals_sha256'), ('manual_source_records.jsonl', 'manual_source_records_sha256'),
                        ('requests.jsonl', 'requests_sha256'), ('template_inventory.json', 'template_inventory_sha256'),
                        ('refined_annotations.jsonl', 'refined_annotations_sha256')):
        require(digest(out/name) == manifest[field], f'Artifact manifest binding differs: {name}')
    combined, manual, new, accepted = (indexed(read_jsonl(out/name)) for name in
        ('proposals.jsonl', 'manual_proposals.jsonl', 'new_proposals.jsonl', 'accepted_candidates.jsonl'))
    requests = indexed(read_jsonl(REQUESTS/'requests.jsonl'))
    require(read_jsonl(out/'requests.jsonl') == read_jsonl(REQUESTS/'requests.jsonl'), 'Copied manual request queue differs')
    require(len(requests) == len(manual) == 24 and set(manual) == set(requests), 'All 24 requested manual targets must be counted exactly once')
    require(Counter(p['class_id'] for p in manual.values()) == {1: 2, 2: 8, 9: 3, 10: 8, 15: 3}, 'Manual requested class counts differ')
    check_partition(old, manual, new, combined, accepted)
    require(manifest['previous_proposals'] == len(old) == 140 and manifest['manual_proposals'] == manifest['manual_added'] == len(manual)
            and manifest['base_proposals'] == len(old)+len(manual) and manifest['new_proposals'] == len(new)
            and manifest['proposals'] == len(combined) and manifest['accepted_before_diversity'] == len(accepted), 'Manifest proposal counts differ')
    require(manifest['manual_source_schema'] == 'saved_pose_mask_gallery_entry_v1', 'Manifest manual schema differs')
    require(QUARANTINE not in combined and manifest['preserved_quarantined_targets'] == [QUARANTINE], 'Quarantine not preserved')
    check_preserved_assets(out, old)
    formal = Path(read_json(PROJECT/'configs/active_formal_dataset.json')['dataset']).resolve()
    classification = PROJECT/'outputs/pallet_appearance_center_reclassification_v1/targets.jsonl'
    formal_sha, classification_sha = digest(formal/'manifest.json'), digest(classification)
    require(formal_sha == parent_manifest['formal_manifest_sha256'] == manifest['formal_manifest_sha256']
            and classification_sha == parent_manifest['classification_sha256'] == manifest['classification_sha256'], 'Frozen formal/classification binding differs')
    rows, sources = prior.formal_rows(formal, classification)
    protected = read_json(out/'protected_formal_before.json')
    require(protected == read_json(PARENT/'protected_formal_before.json') == protected_snapshot(formal)
            and read_json(out/'protected_formal_after.json') == protected, 'Protected formal files differ')
    snapshots = prior.find_snapshots(out, manifest)
    frozen = {kind: prior.read_store(path, kind, frozen=True) for kind, path in snapshots.items()}
    pose, gallery = frozen['pose'], frozen['gallery']
    pose_sha, gallery_sha = digest(snapshots['pose']), digest(snapshots['gallery'])
    require(json.loads(pose['metadata']['binding'])['formal_manifest_sha256'] == formal_sha
            and gallery['metadata']['formal_manifest_sha256'] == formal_sha, 'Review dataset binding differs')
    require(set(gallery['current']) == gallery['history_keys'] == set(publications[4]['proposals'])
            and len(gallery['current']) == 97 and len(gallery['events']) == 104, 'Expected unchanged gallery 97 saved / 104 events')
    require(len(pose['current']) >= 4758 and len(pose['events']) >= 10290, 'Pose snapshot predates completed manual work')
    for kind, prefix in (('pose', 'snapshot'), ('gallery', 'gallery_snapshot')):
        require(manifest[prefix+'_saved'] == len(frozen[kind]['current'])
                and manifest[prefix+'_events'] == len(frozen[kind]['events']), f'{kind} snapshot counters differ')
    check_snapshot_manifest(out, snapshots, frozen, publications, manifest, formal_sha)
    for kind, path in prior.find_snapshots(PARENT, parent_manifest).items():
        prior.preserve_events(prior.read_store(path, kind, frozen=True), frozen[kind])
    status = prior.pose_status(pose, rows)
    direct = independent_pose_templates(pose, rows)
    with closing(sqlite3.connect(snapshots['pose'].resolve().as_uri()+'?mode=ro&immutable=1', uri=True)) as db:
        db.execute('PRAGMA query_only=ON')
        original_current, original_templates, original_status = annotation_inventory(db, rows)
    require(status == original_status and direct == original_templates and pose['current'] == original_current,
            'Independent pose history/templates differ from frozen original reference')
    templates = {k: dict(t, origin=POSE_ORIGIN, pose_review=pose_provenance(t, pose_sha)) for k, t in direct.items()}
    parent_inventory = read_json(PARENT/'template_inventory.json')
    require(digest(PARENT/'template_inventory.json') == parent_manifest['template_inventory_sha256'], 'Parent template inventory changed')
    inventory = read_json(out/'template_inventory.json')
    latest = {t['row']['target_key']: t for t in inventory['templates'] if t['rendering_id'].startswith(NAMESPACE+':')}
    for key, value in gallery['current'].items():
        if pose['current'].get(key, {}).get('state') in ('deleted', 'deferred'):
            templates.pop(key, None)
            continue
        template = latest.get(key)
        require(template is not None, f'Latest saved gallery seed missing: {key}')
        provenance = template['gallery_review']
        base_provenance = {k: v for k, v in provenance.items() if k not in ('proposal_publication', 'publication_proposals_sha256')}
        previous.gallery_template(dict(template, gallery_review=base_provenance), pose, gallery, rows, old,
                                  formal_sha, gallery_sha, publications)
        require(provenance == dict(base_provenance, proposal_publication=value['proposal_publication'],
                publication_proposals_sha256=previous.PUBLICATIONS[value['proposal_publication']][1]['proposals.jsonl']),
                f'Gallery historical publication provenance differs: {key}')
        templates[key] = previous.template_payload(template)
    templates.pop(QUARANTINE, None)
    require(set(latest) == set(templates), 'Seed union must contain exactly latest direct pose/gallery humans, gallery preferred')
    require(not (set(old)-set(gallery['current'])) & set(templates), 'Prior pending machine proposal used as a seed')
    origins = dict(Counter(t['origin'] for t in templates.values()))
    require(manifest['generation_templates'] == len(templates) and manifest['generation_templates_by_origin'] == origins
            and manifest['generation_template_namespace'] == NAMESPACE, 'Direct-human seed totals/origins differ')
    require(indexed(read_jsonl(out/'refined_annotations.jsonl')) == gallery['current'], 'Latest gallery annotation export differs')
    for key, proposal in manual.items():
        check_manual(proposal, requests[key], pose, direct, rows[key], pose_sha, formal_sha, classification_sha)
        source = sources[rows[key]['frame_id']]
        require(requests[key]['source']['image'] == source['image']
                and requests[key]['source']['image_sha256'] == digest(formal/source['image']), f'Manual request original image changed: {key}')
    check_manual_records(out, manual, snapshots['pose'], pose_sha)
    check_rendering(out, inventory, parent_inventory, templates, old, manual, new)
    evidence = ImageEvidence(formal, rows, sources)
    for key, proposal in combined.items():
        check_assets(out, proposal, rows[key], evidence, manual=key in manual)
        require(proposal['formal_manifest_sha256'] == formal_sha
                and proposal['class_assignments_sha256'] == classification_sha, f'Proposal frozen dataset binding differs: {key}')
    for key, proposal in accepted.items():
        prior.require_target_eligible(key, status, gallery, rows)
        require(key not in old and key not in manual and proposal['source'] == rows[key]
                and proposal['class_id'] == rows[key]['final_class_id'], f'Accepted machine identity differs: {key}')
        no_confirmation(proposal, f'Machine {key}')
        require(proposal['production_saved'] is False and proposal['status'] == 'machine_draft_pending_visual_review', f'Accepted machine status differs: {key}')
        require(proposal['formal_manifest_sha256'] == formal_sha and proposal['class_assignments_sha256'] == classification_sha,
                f'Accepted dataset binding differs: {key}')
        binding = proposal['template']
        require(binding['target_key'] in templates, f'Machine uses non-direct template: {key}')
        template = templates[binding['target_key']]
        require(compatible(template['row'], rows[key]), f'Cross-class/split/policy/view or self-frame transfer: {key}')
        provenance_field = 'gallery_review' if template['origin'] == GALLERY_ORIGIN else 'pose_review'
        expected_binding = dict(target_key=template['row']['target_key'], class_id=template['row']['final_class_id'],
            split=template['row']['split'], snapshot_revision=template['revision'],
            current_payload_sha256=template['current_payload_sha256'], 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'], origin=template['origin'],
            **{provenance_field: template[provenance_field]})
        require(binding == expected_binding and proposal['vertex_count'] == len(proposal['polygon']) == len(template['polygon']) > 4,
                f'Machine template binding/topology differs: {key}')
        value = pose['current'].get(key)
        require(proposal['snapshot_sha256'] == pose_sha
                and proposal['target_expected_revision'] == (value['revision'] if value else 0)
                and proposal['target_snapshot_payload_sha256'] == (sha(value) if value else None), f'Machine target snapshot binding differs: {key}')
        require(proposal['generation_method'] == dict(name='original', version='attempt_target_v1',
                code_sha256=ORIGINAL_CODE['pallet/mask_template_continue.py']), f'Non-original transfer method: {key}')
        prior.recompute(proposal, template, evidence)
    outcomes = indexed(read_jsonl(out/'outcomes.jsonl'))
    require(set(outcomes) == set(rows) and all(v['class_id'] == rows[k]['final_class_id'] for k, v in outcomes.items()), 'Outcomes identity/coverage differs')
    require(manifest['outcomes'] == dict(Counter(v['reason'] for v in outcomes.values())), 'Manifest outcome counts differ')
    for prefix, values in (('new', new), ('manual', manual)):
        require(manifest[prefix+'_by_class'] == {str(k): v for k, v in Counter(p['class_id'] for p in values.values()).items()}, f'{prefix} class counts differ')
    eligible, attempt_count = audit_attempts(out, rows, status, gallery, old, manual, templates, accepted, outcomes, evidence)
    require(manifest['scanned_eligible_targets'] == len(eligible), 'Eligible scan count differs')
    check_diversity({**old, **manual}, accepted, new, outcomes)
    classes, counts = expected_counts(old, manual, new, gallery)
    base_classes, _ = expected_counts(old, manual, {}, gallery)
    require(manifest['base_classes'] == base_classes, 'Historical-plus-manual base quota counts differ')
    shortfalls = read_json(out/'shortfalls.json')
    require(set(shortfalls) == set(classes) == set(manifest['classes']), 'Class/shortfall inventory differs')
    for cls, values in classes.items():
        n = int(cls)
        class_outcomes = Counter(v['reason'] for v in outcomes.values() if v['class_id'] == n)
        values.update(templates=sum(t['row']['final_class_id'] == n for t in templates.values()),
            eligible=sum(rows[k]['final_class_id'] == n for k in eligible),
            compatible_targets=sum(class_outcomes[r] for r in ('new_proposal', 'image_similarity_below_gate',
                'registration_or_boundary_rejected', 'accepted_duplicate_frame_not_selected', 'accepted_quota_full_not_selected')),
            preview=values['total'], outcomes=dict(class_outcomes))
        require(manifest['classes'][cls] == values, f'Class {cls} independent quota/scan counters differ')
        require(shortfalls[cls]['missing'] == values['missing'] and shortfalls[cls]['outcomes'] == values['outcomes'], f'Class {cls} shortfalls differ')
    require(inventory['classes'] == classes and inventory['eligibility'] == status
            and inventory['snapshot_saved'] == len(pose['current']) and inventory['snapshot_events'] == len(pose['events'])
            and inventory['gallery_snapshot_saved'] == len(gallery['current']) and inventory['previous_proposals'] == len(old)
            and inventory['manual_proposals'] == len(manual) and inventory['counted_manual_source_keys'] == sorted(manual)
            and manifest['counted_manual_source_keys'] == sorted(manual), 'Inventory snapshot/class/manual counts differ')
    require(read_json(out/'protected_targets.json') == dict(previous=sorted(old), counted_manual_source_keys=sorted(manual),
            pose_mask_history_or_noneligible=sorted(k for k, v in status.items() if v != 'eligible'),
            gallery_saved_or_history=sorted(gallery['history_keys']), quarantine=[QUARANTINE], eligibility=status), 'Protected target inventory differs')
    check_report(out, combined, old, manual, new, gallery, classes)
    used = read_json(out/'used_image_hashes.json')
    for name, expected in {**read_json(PARENT/'used_image_hashes.json'), **evidence.used}.items():
        require(used.get(name) == expected, f'Original/used source image hash missing: {name}')
    for name, expected in used.items():
        path = (formal/name).resolve()
        require(path.is_relative_to(formal) and digest(path) == expected, f'Original source image changed: {name}')
    require(protected_snapshot(formal) == protected and digest(classification) == classification_sha, 'Frozen dataset changed during verification')
    for kind, path in snapshots.items():
        require(digest(path) == (pose_sha if kind == 'pose' else gallery_sha), f'{kind} immutable snapshot changed during verification')
    prior.check_artifacts(out, artifacts)
    require(digest(out/'artifact_hashes.json') == artifact_inventory_sha, 'Artifact hash inventory changed during verification')
    check_frozen_inputs()
    require(digest(PROJECT/'pallet/mask_quota_completion.py') == generator_sha, 'Generator changed during verification')
    live = {'pose': prior.read_store(pose_live, 'pose'), 'gallery': prior.read_store(gallery_live, 'gallery')}
    check_live_dependencies(frozen, live, templates, accepted, manual, rows)
    require(configuration_hashes() == config_hashes, 'Live configuration/authorization dependencies changed during verification')
    require(digest(__file__) == verifier_sha, 'Independent verifier changed during verification')
    return dict(state='passed', publication_version=6, proposals_verified=len(combined),
        new_verified=len(new), manual_verified=len(manual), manual_added=len(manual), old_canonical_objects_preserved=len(old),
        proposals_sha256=manifest['proposals_sha256'], new_proposals_sha256=manifest['new_proposals_sha256'],
        manual_proposals_sha256=manifest['manual_proposals_sha256'], manifest_sha256=digest(out/'manifest.json'),
        artifact_hashes_sha256=artifact_inventory_sha,
        classes=counts, all_new_registrations_and_metrics_recomputed=True, all_rejected_attempts_and_metrics_recomputed=True,
        accepted_before_diversity_recomputed=len(accepted), registration_attempts_verified=attempt_count,
        templates_verified=len(templates), templates_by_origin=origins, metric_absolute_tolerance=prior.ATOL,
        manual_exact_sqlite_payloads_and_human_events_verified=True, manual_sources_not_machine_transfers=True,
        manual_snapshots_not_imported_into_gallery_store=True, diversity_base_includes_manual_frames=True,
        thresholds_relaxed=False, forced_fill=False, method='original', production_database_writes=0,
        human_confirmation_inferred=False, ground_truth_eligible=False, automatic_training_eligible=False, robot_command_eligible=False,
        extra_public_images=['vertex2_before_after.png'], pose_snapshot_sha256=pose_sha, gallery_snapshot_sha256=gallery_sha,
        original_events_preserved={kind: len(store['events']) for kind, store in frozen.items()},
        outcomes_verified=len(outcomes), protected_formal_files_verified=len(protected),
        live_dependencies_unchanged=True, authorization_dependencies_unchanged=True,
        verification_script_sha256=verifier_sha, verified_at=datetime.now(timezone.utc).isoformat())


def main(argv=None):
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('--output', type=Path, default=OUTPUT)
    parser.add_argument('--pose-live', type=Path, default=PROJECT/'outputs/pallet_pose_human_review_v1/annotations.sqlite3')
    parser.add_argument('--gallery-live', type=Path, default=PROJECT/'outputs/pallet_mask_gallery_reviews_v1/mask_reviews.sqlite3')
    args = parser.parse_args(argv)
    out = args.output.resolve()
    require(not OUTPUT.is_symlink() and out == OUTPUT.absolute() and out.is_dir(),
            'Use the completed publication-6 outputs directory only')
    require(out not in {PARENT.resolve(), previous.PARENT.resolve(), prior.PARENT.resolve(),
            (PROJECT/'outputs/pallet_mask_template_refined_v1').resolve()}, 'Cannot verify over a frozen/diagnostic publication')
    require(not (out/'verification.json').exists(), 'Refusing to overwrite a frozen verification')
    require((out/'manifest.json').is_file(), 'Generation is not complete: manifest.json missing')
    require(not (out/'validation_report.json').is_symlink() and not (out/'verification.json').is_symlink(), 'Unsafe verification/report path')
    cv2.setNumThreads(1)
    try:
        result = audit(out, args.pose_live, args.gallery_live)
    except Exception as exc:
        report = dict(state='failed', publication_version=6, error_type=type(exc).__name__, error=str(exc),
                      verification_script_sha256=digest(__file__))
        (out/'validation_report.json').write_bytes(canonical(report)+b'\n')
        raise
    (out/'validation_report.json').write_bytes(canonical(result)+b'\n')
    result['validation_report_sha256'] = digest(out/'validation_report.json')
    with (out/'verification.json').open('xb') as stream:
        stream.write(canonical(result)+b'\n')
    print(json.dumps(result, ensure_ascii=False), flush=True)


if __name__ == '__main__':
    main()
