"""Read-only machine pose sidecars for every existing human detection target.

Only the frozen planar pose head is applied to original boxes; no detector is
rerun, no negative frame is converted to positive, no missing 6D component or
calibration is invented. All predictions remain unreviewed and non-training GT.
"""
from __future__ import annotations

import argparse
from collections import Counter
from concurrent.futures import ProcessPoolExecutor, ThreadPoolExecutor
from copy import deepcopy
import csv
import fcntl
import io
import json
import multiprocessing
import os
from pathlib import Path
import time
from zipfile import ZIP_DEFLATED, ZipFile

import numpy as np
import torch

from .cluster_targets import (digest, load_dataset, protected_snapshot,
    target_id, target_key)
from .data.orientation import orient_grid, rotation_degrees
from .data.pcd import read_pcd
from .devices import device_metadata
from .pose_dataset import (PROJECT, now, protected_write, read_rows, safe_path,
    write_json, write_rows)
from .pose_inference import bundle_path, partial_document
from .pose_model import TASKS, PointNetResidual, box_array, roi_features


def validate_config(config):
    if (config['version'] != 1 or config['task'] != TASKS[0]
            or config['roi_source'] != 'unchanged_original_human_boxes'
            or config['unverified_units'] != 'research_numeric_assumption_with_explicit_flags_no_metric_pose'
            or not config['all_predictions_require_human_review']
            or config['automatic_training_eligibility'] or config['normal_head_enabled']
            or config['replace_existing_pose_gt']):
        raise ValueError('Unsupported or unsafe pose annotation policy')
    if not 1 <= config['workers'] <= 16 or not 1 <= config['batch'] <= 256:
        raise ValueError('Invalid extraction workers or inference batch')


def independent_output(output, protected_roots):
    output = Path(output).resolve()
    for root in protected_roots:
        root = Path(root).resolve()
        if output == root or output.is_relative_to(root) or root.is_relative_to(output):
            raise ValueError('Annotation output must be independent of protected inputs')


def load_head(bundle, device):
    bundle = Path(bundle).resolve()
    spec = json.loads((bundle/'inference_config.json').read_text())
    if spec['selected_planar_family'] != 'pointnet':
        raise ValueError('This exporter is bound to the frozen selected PointNet head')
    for name, expected in spec['files'].items():
        if digest(bundle_path(bundle, name)) != expected:
            raise ValueError('Model bundle hash mismatch')
    state = torch.load(bundle_path(bundle, spec['pointnet_weights'][TASKS[0]]),
        map_location='cpu', weights_only=True)
    if state['task'] != TASKS[0]:
        raise ValueError('Wrong partial-pose checkpoint task')
    model = PointNetResidual(TASKS[0])
    model.load_state_dict(state['model'])
    return model.to(device).eval(), spec


def extract_frame(job):
    """CPU-only extraction; returns one entry for every original box, even failures."""
    formal, source, annotation, feature_config, seed = job
    formal = Path(formal)
    for field in ('image', 'annotation', 'yolo_label'):
        relative = source[field]
        if digest(safe_path(formal, relative)) != source['files'][relative]:
            raise ValueError(f'Frozen detection asset changed: {relative}')
    pcd = Path(source['source_paths']['pcd'])
    stat = pcd.stat()
    if digest(pcd) != source['source_anchor_hash']:
        raise ValueError(f'Original PCD identity changed: {source["frame_id"]}')
    source_stat = {'path': str(pcd), 'size': stat.st_size, 'mtime_ns': stat.st_mtime_ns,
        'sha256': source['source_anchor_hash']}
    features, globals_, metadata = [], [], []
    frame_error = None
    if annotation['boxes']:
        try:
            _, points = read_pcd(pcd)
            width, height = source['size']
            if len(points) != width*height or source['sensor_policy'].get('grid') != [height, width]:
                raise ValueError('PCD/grid registration does not match the frozen image')
            if rotation_degrees(source['sensor_policy']) != source['pixel_rotation_degrees']:
                raise ValueError('Frozen pixel orientation disagreement')
            mapping = orient_grid(np.arange(len(points), dtype=np.int32).reshape(height, width),
                source['sensor_policy'])
            scale = source['sensor_policy'].get('scale_to_mm')
            scale_to_m = scale/1000. if scale is not None else None
        except ValueError as error:
            frame_error = str(error)
        for box in annotation['boxes']:
            try:
                if frame_error:
                    raise ValueError(frame_error)
                f, g, meta = roi_features(points, mapping, box_array(box), width, height,
                    feature_config, scale_to_m=scale_to_m, seed=seed)
                meta['error'] = None
            except ValueError as error:
                f = g = None
                meta = {'error': str(error)}
            features.append(f)
            globals_.append(g)
            metadata.append(meta)
    after = pcd.stat()
    if after.st_size != stat.st_size or after.st_mtime_ns != stat.st_mtime_ns:
        raise ValueError('Source PCD changed during extraction')
    return features, globals_, metadata, source_stat


def bounded_map(executor, function, jobs, capacity):
    """Deterministic order, bounded pending results, safe CUDA/spawn separation."""
    iterator = iter(jobs)
    pending = []
    for _ in range(capacity):
        try:
            pending.append(executor.submit(function, next(iterator)))
        except StopIteration:
            break
    while pending:
        future = pending.pop(0)
        yield future.result()
        try:
            pending.append(executor.submit(function, next(iterator)))
        except StopIteration:
            pass


def flags_for(source, metadata, g, model, profile, config):
    flags = []
    policy = source['sensor_policy']
    if policy.get('scale_to_mm') is None:
        flags.append('point_units_unverified_research_assumption')
    if policy.get('depth_axis') != 0:
        flags.append('source_forward_axis_unverified_for_x_facing_model')
    if source['domain'] not in profile['domains']:
        flags.append('sensor_domain_not_in_pose_training')
    if source['group_id'] not in profile['groups']:
        flags.append('capture_group_not_in_pose_training')
    if source['instances'] > 1:
        flags.append('multi_target_scene_not_in_pose_training')
    if metadata.get('error'):
        flags.append('pose_input_unavailable')
        return flags, None
    if not metadata['plane_success']:
        flags.append('front_plane_fit_failed_no_usable_angle')
    if metadata['roi_valid_points'] < config['minimum_roi_valid_points']:
        flags.append('few_measured_roi_points')
    if metadata['plane_inlier_fraction'] < config['minimum_plane_inlier_fraction']:
        flags.append('weak_front_plane_support')
    # This is an input-domain diagnostic, not a calibrated pose confidence.
    # Unit-known bit is excluded because a binary channel is not a distance.
    mean = model.global_mean.detach().cpu().numpy()
    std = model.global_std.detach().cpu().numpy()
    zscore = float(np.max(np.abs((np.asarray(g)[:15]-mean[:15])/std[:15])))
    if zscore > config['maximum_training_feature_zscore']:
        flags.append('input_geometry_outside_training_feature_envelope')
    return flags, zscore


def make_target(source, index, box, metadata, g, prediction, model, profile, config, known):
    flags, zscore = flags_for(source, metadata, g, model, profile, config)
    key = target_key(source['frame_id'], index)
    gt = known.get(key)
    usable = prediction is not None and metadata.get('plane_success', False)
    estimate = partial_document(prediction, TASKS[0]) if usable else None
    verified_units = source['sensor_policy'].get('scale_to_mm') is not None
    if estimate is not None:
        estimate.update(position_unit='m' if verified_units else 'research_assumed_m_not_calibrated',
            angle_unit='degrees', reference_point='learned_source_GT_reference_not_geometric_center',
            reference_frame_semantics_verified=False)
    state = 'machine_pose_pending_review' if usable else 'unavailable_pending_review'
    review_flags = flags+(['existing_pose_gt_kept_separate_never_overwritten'] if gt else [])
    if source['split'] != 'train':
        review_flags.append('original_holdout_annotation_not_a_training_label')
    return {'target_id': target_id(source['frame_id'], index), 'target_key': key,
        'frame_id': source['frame_id'], 'box_index': index, 'bbox': box,
        'split': source['split'], 'original_split': source['original_split'],
        'group_id': source['group_id'], 'domain': source['domain'],
        'image': source['image'], 'source_pcd': source['source_paths']['pcd'],
        'source_pcd_sha256': source['source_anchor_hash'],
        'roi_source': 'original_human_detection_box_unchanged',
        'pose_task': TASKS[0], 'pose_estimate': estimate,
        'metric_pose_estimate': estimate if verified_units else None,
        'raw_model_output_diagnostic_only': prediction.tolist() if prediction is not None else None,
        'pose_estimate_mask': {'x': usable, 'y': usable, 'theta_degrees': usable,
            'z': False, 'normal': False, 'roll': False, 'pitch': False, 'yaw': False},
        'pose_gt_supervision_mask': {k: False for k in ('x', 'y', 'theta_degrees',
            'z', 'normal', 'roll', 'pitch', 'yaw')},
        'input_quality': metadata, 'max_training_input_zscore': zscore,
        'model_pose_fit_exposure': source['frame_id'] in profile['fit_frame_ids'],
        'detector_rerun': False, 'model_pose_confidence': None,
        'pose_label_origin': 'machine_prediction_not_ground_truth',
        'human_pose_confirmed': False, 'human_detection_box_confirmed': True,
        'review_state': state, 'review_required': True, 'review_flags': sorted(set(review_flags)),
        'point_units_verified': verified_units,
        'existing_pose_gt_reference': gt, 'existing_pose_gt_replaced': False,
        'automatic_training_eligible': False, 'evaluation_ground_truth_eligible': False,
        'robot_command_eligible': False, 'full_six_dof': False}


def sidecar(original, source, targets, image_path):
    document = deepcopy(original)
    shapes = [shape for shape in document['shapes']
        if shape.get('label') == 'pallet' and shape.get('shape_type') == 'rectangle']
    if len(shapes) != len(targets):
        raise ValueError('Original rectangle/target count disagreement')
    for shape, target in zip(shapes, targets):
        b = target['bbox']
        expected = np.array([[b['x'], b['y']], [b['x']+b['width'], b['y']+b['height']]])
        if not np.allclose(np.sort(np.asarray(shape['points']), axis=0), expected,
                atol=1e-7, rtol=0):
            raise ValueError('Original JSON rectangle identity differs')
        shape['pose_machine_annotation'] = target
        # Existing human_reviewed flags refer to 2D boxes only; make it explicit.
        shape.setdefault('flags', {}).update(pose_machine_generated=True, human_pose_confirmed=False)
        note = json.dumps({'machine_pose': target['pose_estimate'],
            'pose_state': target['review_state'], 'human_pose_confirmed': False},
            ensure_ascii=False, allow_nan=False)
        shape['description'] = (shape.get('description', '')+'\n'+note).lstrip('\n')
    document['imagePath'] = image_path
    document['imageData'] = None
    document.setdefault('flags', {}).update(pose_machine_generated=bool(targets), human_pose_confirmed=False)
    document['pallet_pose_annotation'] = {'task': TASKS[0], 'frame_id': source['frame_id'],
        'split': source['split'], 'group_id': source['group_id'],
        'detection_boxes_unchanged': True, 'negative_frame_preserved': not bool(targets),
        'pose_label_origin': 'machine_prediction_not_ground_truth',
        'human_detection_review_flags_do_not_apply_to_pose': True,
        'automatic_training_eligible': False, 'robot_command_eligible': False}
    return document


def infer_targets(extracted, source, annotation, model, profile, config, known, device):
    features, globals_, metadata, stat = extracted
    indices = [i for i, f in enumerate(features) if f is not None]
    predictions = {}
    with torch.inference_mode():
        for start in range(0, len(indices), config['batch']):
            ids = indices[start:start+config['batch']]
            f = torch.from_numpy(np.stack([features[i] for i in ids])).to(device)
            g = torch.from_numpy(np.stack([globals_[i] for i in ids])).to(device)
            values = model(f, g).cpu().numpy()
            if not np.isfinite(values).all():
                raise ValueError('Nonfinite frozen model inference')
            predictions.update(zip(ids, values))
    targets = [make_target(source, i, box, metadata[i], globals_[i], predictions.get(i),
        model, profile, config, known) for i, box in enumerate(annotation['boxes'])]
    return targets, stat


def write_exports(out, frame_records, targets):
    write_rows(out/'annotations/targets.jsonl', targets)
    write_rows(out/'annotations/frames.jsonl', frame_records)
    columns = ('target_id', 'target_key', 'frame_id', 'box_index', 'split', 'group_id', 'domain',
        'review_state', 'x_estimate', 'y_estimate', 'theta_degrees_estimate', 'position_unit',
        'point_units_verified', 'review_flags', 'human_pose_confirmed', 'automatic_training_eligible')
    stream = io.StringIO(newline='')
    writer = csv.DictWriter(stream, fieldnames=columns)
    writer.writeheader()
    for row in targets:
        pose = row['pose_estimate'] or {}
        value = {k: row[k] for k in columns if k in row}
        value.update(x_estimate=pose.get('x'), y_estimate=pose.get('y'),
            theta_degrees_estimate=pose.get('theta_degrees'), position_unit=pose.get('position_unit'),
            review_flags=';'.join(row['review_flags']))
        writer.writerow(value)
    protected_write(out/'annotations/targets.csv', ('\ufeff'+stream.getvalue()).encode())
    for split in ('train', 'val', 'test'):
        write_rows(out/f'indices/{split}.jsonl', [r for r in targets if r['split'] == split])
    # No train-ready view: unconfirmed predictions must not silently become GT.
    write_rows(out/'indices/automatic_training_eligible.jsonl', [])
    return {'frames': len(frame_records), 'targets': len(targets),
        'negative_frames_preserved': sum(not r['target_keys'] for r in frame_records),
        'pose_estimates': sum(r['pose_estimate'] is not None for r in targets),
        'metric_unit_pose_estimates_pending_review': sum(r['metric_pose_estimate'] is not None for r in targets),
        'research_unit_pose_estimates_pending_review': sum(r['pose_estimate'] is not None and not r['point_units_verified'] for r in targets),
        'pose_unavailable': sum(r['pose_estimate'] is None for r in targets),
        'frame_split_counts': dict(Counter(r['split'] for r in frame_records)),
        'target_split_counts': dict(Counter(r['split'] for r in targets)),
        'review_flag_counts': dict(Counter(flag for r in targets for flag in r['review_flags'])),
        'input_failure_counts': dict(Counter(r['input_quality']['error'] for r in targets if r['input_quality'].get('error'))),
        'existing_pose_gt_references_preserved': sum(r['existing_pose_gt_reference'] is not None for r in targets),
        'all_require_human_review': True, 'automatic_training_eligible': 0}


def publish(out, summary):
    portable_roots = ('annotations', 'indices', 'labelme', 'reproduction')
    paths = [p for folder in portable_roots for p in (out/folder).rglob('*') if p.is_file()]
    paths += [out/'summary.json', out/'README_zh.md']
    files = {str(p.relative_to(out)): digest(p) for p in sorted(paths)}
    manifest = {'kind': 'machine_partial_pose_annotations_on_existing_human_boxes',
        'state': 'complete', 'version': 1, 'summary': summary, 'files': files,
        'run_manifest_sha256': digest(out/'run_manifest.json'),
        'human_pose_confirmed': False, 'automatic_training_eligible': False,
        'original_detection_labels_modified': False, 'full_six_dof_available': False}
    write_json(out/'annotation_manifest.json', manifest)
    files['annotation_manifest.json'] = digest(out/'annotation_manifest.json')
    protected_write(out/'checksums.sha256', ''.join(f'{sha}  {name}\n' for name, sha in sorted(files.items())).encode())
    paths += [out/'annotation_manifest.json', out/'checksums.sha256']
    archive = out/'pallet_pose_annotations_v1.zip'
    if not archive.exists():
        temporary = archive.with_suffix('.zip.tmp')
        with ZipFile(temporary, 'w', ZIP_DEFLATED, compresslevel=6) as z:
            for path in sorted(paths):
                z.write(path, str(path.relative_to(out)))
        temporary.replace(archive)
    import hashlib
    with ZipFile(archive) as z:
        if set(z.namelist()) != {str(p.relative_to(out)) for p in paths}:
            raise ValueError('Published annotation archive member set differs')
        for name in z.namelist():
            if hashlib.sha256(z.read(name)).hexdigest() != digest(safe_path(out, name)):
                raise ValueError('Published annotation archive member hash differs')
    result = {'state': 'complete', 'archive': str(archive), 'archive_bytes': archive.stat().st_size,
        'archive_sha256': digest(archive), 'archive_members_verified': len(paths),
        'summary': summary, 'original_detection_labels_modified': False,
        'production_review_database_accessed': False, 'training_started': False}
    write_json(out/'delivery_manifest.json', result)
    protected_write(archive.with_suffix('.zip.sha256'), f'{result["archive_sha256"]}  {archive.name}\n'.encode())
    return result


def run(config_path, resume=False):
    config_path = Path(config_path).resolve()
    config = json.loads(config_path.read_text())
    validate_config(config)
    formal = Path(json.loads((PROJECT/config['formal_config']).read_text())['dataset']).resolve()
    active_pose = json.loads((PROJECT/config['pose_dataset_config']).read_text())
    pose_root = (PROJECT/active_pose['dataset']).resolve()
    bundle = (PROJECT/config['model_bundle']).resolve()
    out = (PROJECT/config['output']).resolve()
    independent_output(out, (formal, pose_root.parent, bundle.parent,
        PROJECT/'outputs/pallet_structure_human_review_v1'))
    annotations, sources = load_dataset(formal)
    device_info = device_metadata(config['device'])
    device = torch.device(device_info['device'])
    torch.set_num_threads(1)
    torch.backends.cudnn.benchmark = False
    model, spec = load_head(bundle, device)
    train_root = PROJECT/config['pose_training_run']
    training = json.loads((train_root/'completed.json').read_text())
    frozen = json.loads((train_root/'frozen_evaluation_plan.json').read_text())
    if digest(pose_root/'manifest.json') != active_pose['manifest_sha256'] or active_pose['manifest_sha256'] != frozen['pose_manifest_sha256']:
        raise ValueError('Source pose dataset differs from frozen trained input')
    fit_rows = read_rows(pose_root/'indices/overlap/planar_xy_theta/train.jsonl')
    pose_files = json.loads((pose_root/'manifest.json').read_text())['files']
    for name in ('indices/overlap/planar_xy_theta/train.jsonl', 'annotations.jsonl'):
        if digest(pose_root/name) != pose_files[name]:
            raise ValueError('Frozen pose training identity/reference index changed')
    fit = json.loads((train_root/'planar_final/completed.json').read_text())
    if set(fit['train_ids']) != {r['sample_id'] for r in fit_rows} or training['selected_planar_family'] != 'pointnet':
        raise ValueError('Frozen training profile mismatch')
    profile = {'fit_frame_ids': sorted(r['frame_id'] for r in fit_rows),
        'groups': sorted({r['group_id'] for r in fit_rows}),
        'domains': sorted({r['sensor_policy']['domain_id'] for r in fit_rows})}
    known = {}
    for row in read_rows(pose_root/'annotations.jsonl'):
        if row['subset'] == 'overlap':
            known[row['detection_target_key']] = {'sample_id': row['sample_id'], 'task': row['pose']['kind'],
                'split': row['split'], 'annotation_index': str(pose_root/'annotations.jsonl'),
                'original_GT_only_no_values_used_by_predictor': True}
    snapshot = protected_snapshot(formal)
    frozen_formal = json.loads((formal/'manifest.json').read_text())['files']
    if any(name in frozen_formal and frozen_formal[name] != sha for name, sha in snapshot.items()):
        raise ValueError('Formal labels/metadata differ from frozen manifest')
    binding = {'config_sha256': digest(config_path), 'formal_manifest_sha256': digest(formal/'manifest.json'),
        'source_pose_manifest_sha256': digest(pose_root/'manifest.json'),
        'inference_config_sha256': digest(bundle/'inference_config.json'),
        'weights': spec['files'], 'trained_plan_sha256': digest(train_root/'frozen_evaluation_plan.json'),
        'code': {name: digest(Path(__file__).parent/name) for name in
            ('pose_annotations.py', 'pose_model.py', 'pose_inference.py', 'data/pcd.py', 'data/orientation.py')},
        'device': device_info, 'frames': len(annotations), 'targets': sum(len(a['boxes']) for a in annotations)}
    run_path = out/'run_manifest.json'
    if run_path.exists():
        old = json.loads(run_path.read_text())
        if not resume or old['binding'] != binding or old['protected_formal_files'] != snapshot:
            raise ValueError('Resume requires identical source, config, weights and device')
    else:
        if out.exists() and any(out.iterdir()):
            raise ValueError('New annotation output directory is not empty')
        out.mkdir(parents=True, exist_ok=True)
        write_json(run_path, {'kind': 'machine_partial_pose_annotation_run', 'created_at': now(),
            'binding': binding, 'config': config, 'profile': profile,
            'protected_formal_files': snapshot, 'pose_GT_used_for_prediction': False,
            'roi_source': config['roi_source'], 'all_predictions_require_review': True})
    with (out/'run.lock').open('a') as lock:
        try:
            fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
        except BlockingIOError:
            raise ValueError('Annotation exporter already running')
        for name in ('pose_annotations.py', 'pose_model.py', 'pose_inference.py', 'data/pcd.py', 'data/orientation.py'):
            protected_write(out/'reproduction/pallet'/name, (Path(__file__).parent/name).read_bytes())
        protected_write(out/'reproduction/config.json', config_path.read_bytes())
        run_sha256 = digest(run_path)
        (out/'frames').mkdir(exist_ok=True)
        targets, frame_records, stats = [], [], []
        missing = [a for a in annotations if not (out/'frames'/Path(sources[a['frame_id']]['image']).with_suffix('.json').name).exists()]
        jobs = ((str(formal), sources[a['frame_id']], a, spec['pose_features'], config['seed']) for a in missing)
        started = time.monotonic()
        with ProcessPoolExecutor(max_workers=config['workers'], mp_context=multiprocessing.get_context('spawn')) as pool:
            values = bounded_map(pool, extract_frame, jobs, 2*config['workers'])
            for count, (annotation, extracted) in enumerate(zip(missing, values), 1):
                source = sources[annotation['frame_id']]
                rows, stat = infer_targets(extracted, source, annotation, model, profile, config, known, device)
                stem = Path(source['image']).stem
                write_json(out/'frames'/f'{stem}.json', {'frame_id': source['frame_id'],
                    'split': source['split'], 'group_id': source['group_id'], 'targets': rows,
                    'source_stat': stat, 'input_binding_sha256': run_sha256})
                if count == 1 or count % 250 == 0 or count == len(missing):
                    print(json.dumps({'stage': 'pose_annotations', 'completed': len(annotations)-len(missing)+count,
                        'total': len(annotations), 'seconds': time.monotonic()-started}), flush=True)
        for annotation in annotations:
            source = sources[annotation['frame_id']]
            stem = Path(source['image']).stem
            cached = json.loads((out/'frames'/f'{stem}.json').read_text())
            rows = cached['targets']
            if (cached['frame_id'] != source['frame_id'] or cached['input_binding_sha256'] != run_sha256
                    or cached['source_stat']['sha256'] != source['source_anchor_hash']
                    or cached['source_stat']['path'] != source['source_paths']['pcd']
                    or cached['split'] != source['split'] or cached['group_id'] != source['group_id']
                    or len(rows) != len(annotation['boxes'])
                    or any(r['bbox'] != annotation['boxes'][i] or r['target_key'] != target_key(source['frame_id'], i)
                        for i, r in enumerate(rows))):
                raise ValueError('Cached frame target identity differs from frozen source')
            targets.extend(rows)
            stats.append(cached['source_stat'])
            label_path = out/f'labelme/{source["split"]}/{stem}.json'
            image_path = os.path.relpath(safe_path(formal, source['image']), label_path.parent)
            original = json.loads(safe_path(formal, source['annotation']).read_text())
            write_json(label_path, sidecar(original, source, rows, image_path))
            frame_records.append({'frame_id': source['frame_id'], 'group_id': source['group_id'],
                'split': source['split'], 'original_split': source['original_split'],
                'domain': source['domain'], 'image': source['image'], 'native_size': source['size'],
                'source_pcd_sha256': source['source_anchor_hash'],
                'original_status': source['status'], 'original_instances': source['instances'],
                'target_keys': [r['target_key'] for r in rows],
                'labelme': str(label_path.relative_to(out)), 'human_pose_confirmed': False})
        # Second full hash pass, including raw PCDs and negative frames, after inference.
        def unchanged(stat):
            if digest(stat['path']) != stat['sha256']:
                raise ValueError('Source PCD changed before delivery')
            return True
        with ThreadPoolExecutor(max_workers=8) as pool:
            list(pool.map(unchanged, stats))
        if protected_snapshot(formal) != snapshot:
            raise ValueError('Formal detection labels/metadata changed')
        write_json(out/'source_stats.json', stats)
        summary = write_exports(out, frame_records, targets)
        summary.update(original_detection_labels_and_metadata_unchanged=len(snapshot),
            original_raw_PCDs_rehashed_unchanged=len(stats), all_original_boxes_preserved=True,
            pose_GT_never_overwritten=True, normal_head_applied=False, detector_rerun=False,
            source_pose_manifest_unchanged=digest(pose_root/'manifest.json') == binding['source_pose_manifest_sha256'])
        write_json(out/'summary.json', summary)
        text = f'''# 原正式检测集：机器平面位姿预标注 v1

覆盖{summary['frames']}帧、{summary['targets']}个人工框；{summary['negative_frames_preserved']}帧原负例保持空框。
可生成待审x/y/theta的有{summary['pose_estimates']}个目标，无法生成{summary['pose_unavailable']}个；
其中单位有原登记比例的估计{summary['metric_unit_pose_estimates_pending_review']}个，
未登记单位而仅使用显式研究数值假设的估计{summary['research_unit_pose_estimates_pending_review']}个。

## 不能当作真值或完整6D

使用刚训练的冻结PointNet平面位姿头，对原人工框及像素注册点云逐框预测；没有重新检测、改框或转移划分。
所有结果human_pose_confirmed=false、review_required=true、automatic_training_eligible=false。
metric_pose_estimate仅表示输入单位比例有来源登记，不代表机器人外参或参考点已核验。
研究单位预测单列，metric_pose_estimate=null；不凭数值大小猜测新比例、不换XYZ轴。
法向量头缺少独立验证，故本轮不全量外推；z/normal/roll/pitch/yaw等缺失项不补0。
平面失败时不将默认朝向写为有效标注，原始模型输出至多留作diagnostic。
模型只在65帧/9组平面GT上训练，新传感器、多目标、训练范围外几何均有待审标志，未给出虚构的位姿置信度。

## 文件

- annotations/targets.jsonl、targets.csv：逐目标预标注、原框、原划分、来源、单位与待审原因。
- annotations/frames.jsonl：全帧索引，包含原负例和无法预测目标。
- labelme/train|val|test/*.json：保留原矩形、类别及2D人工审核记录，新增pose_machine_annotation；human_reviewed仅指原2D框，不指机器位姿。
- indices/train.jsonl、val.jsonl、test.jsonl：沿用原划分的预标注；**并非训练/评估GT**。
- indices/automatic_training_eligible.jsonl：刻意为空；本任务不启动训练。
- reproduction/：绑定的配置和相关源码；模型本体仍使用已交付pallet_pose_models_v1.zip。

这是轻量标注包，不重复复制原图/PCD；每条记录保留来源和哈希。labelme内imagePath指向本机正式原图；
迁移机器后按frame索引重连原数据目录。原有154条GT仅附引用、不会被机器预测替换；负例不会因预测失败变成新目标。
原train/val/test均可用于人工查看预标注，但val/test预标注不得回流训练或作为独立评估真值。
原数据、结构属性、正在运行的人工审核库不被写入。
'''
        protected_write(out/'README_zh.md', text.encode())
        result = publish(out, summary)
        print(json.dumps(result, ensure_ascii=False), flush=True)
        return result


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('--config', type=Path, default=PROJECT/'configs/pallet_pose_annotations_v1.json')
    parser.add_argument('--resume', action='store_true')
    args = parser.parse_args()
    run(args.config, args.resume)


if __name__ == '__main__':
    main()
