"""Publish the already-frozen pilot models, code, evidence and a train-only demo."""
from __future__ import annotations

import argparse
from importlib.metadata import version
import json
import os
from pathlib import Path
import subprocess
import sys
from zipfile import ZIP_DEFLATED,ZipFile

PROJECT=Path(__file__).resolve().parents[1]
sys.path.insert(0,str(PROJECT))
from pallet.cluster_targets import digest,protected_snapshot
from pallet.pose_dataset import protected_write,read_rows,write_json


def publish(config_path):
    config_path=Path(config_path).resolve();config=json.loads(config_path.read_text())
    out=PROJECT/config['output'];bundle=out/'deployment'
    detector=json.loads((out/'detector_completed.json').read_text())
    pose=json.loads((out/'pose/completed.json').read_text())
    result=json.loads((out/'evaluation/results.json').read_text())
    plan=json.loads((out/'pose/frozen_evaluation_plan.json').read_text())
    det_run=json.loads((out/'detector_run.json').read_text())
    binding=json.loads((out/'evaluation/binding.json').read_text())
    if any(v['state']!='complete' for v in (detector,pose,result)):
        raise ValueError('Cannot publish an incomplete experiment')
    if result['selected_family_before_test']!=pose['selected_planar_family']:
        raise ValueError('Primary family changed after test')
    if digest(config_path)!=det_run['binding']['config_sha256'] or digest(config_path)!=plan['config_sha256']:
        raise ValueError('Experiment config changed')
    for name,expected in plan['source_hashes'].items():
        if digest(PROJECT/'pallet'/name)!=expected:raise ValueError('Pose model/trainer source changed')
    for name,expected in binding['source_hashes'].items():
        if digest(PROJECT/'pallet'/name)!=expected:raise ValueError('Evaluation/inference source changed')
    if digest(PROJECT/'pallet/pose_detector_training.py')!=det_run['binding']['source_code_sha256']:
        raise ValueError('Detector trainer source changed')
    if digest(detector['best'])!=detector['best_sha256']:raise ValueError('Detector changed')
    for value in pose['weights'].values():
        if digest(value['path'])!=value['sha256']:raise ValueError('Pose checkpoint changed')
    formal=Path(json.loads((PROJECT/config['formal_config']).read_text())['dataset'])
    if protected_snapshot(formal)!=det_run['protected_formal_files']:
        raise ValueError('Formal labels or metadata changed')
    for name in ('pallet/__init__.py','pallet/pose_model.py','pallet/pose_inference.py'):
        protected_write(bundle/name,(PROJECT/name).read_bytes())
    protected_write(bundle/'requirements.txt',b'numpy==1.26.4\ntorch==2.6.0\ntorchvision==0.21.0\nultralytics==8.4.163\nopencv-python-headless==4.11.0.86\n')
    root=PROJECT/config['pose_dataset']
    examples=read_rows(root/'indices/overlap/planar_xy_theta/train.jsonl')
    example=next(r for r in examples if r['pointcloud_scale_to_m']==1.)
    protected_write(bundle/'example/image.png',(root/example['image']).read_bytes())
    protected_write(bundle/'example/cloud.npz',(root/example['points']).read_bytes())
    write_json(bundle/'example/input_metadata.json',{'source_split':'original_train',
        'sample_id':example['sample_id'],'scale_to_m':example['pointcloud_scale_to_m'],
        'native_size':example['native_size'],'ground_truth_pose_or_box_supplied_to_predictor':False})
    demo=out/'bundle_demo_prediction.json'
    if not demo.exists():
        env=dict(os.environ,OPENBLAS_NUM_THREADS='1',OMP_NUM_THREADS='2',
            YOLO_CONFIG_DIR='/tmp/opencode/pallet_pose_yolo_settings')
        command=[str(PROJECT/'.venv/bin/python'),'-m','pallet.pose_inference','--bundle',str(bundle),
            '--image',str(bundle/'example/image.png'),'--cloud',str(bundle/'example/cloud.npz'),
            '--scale-to-m','1','--output',str(demo),'--device','cpu']
        process=subprocess.run(command,cwd=PROJECT,env=env,capture_output=True,text=True,timeout=120)
        protected_write(out/'bundle_demo.log',(process.stdout+process.stderr).encode())
        if process.returncode:raise ValueError('Portable inference demo failed; inspect bundle_demo.log')
    demo_value=json.loads(demo.read_text())
    if not demo_value['detections'] or not any(r['pose'] is not None for r in demo_value['detections']):
        raise ValueError('The train-only portable demo produced no partial pose')
    if demo_value['ground_truth_used_for_inference'] or demo_value['robot_command_eligible']:
        raise ValueError('Unsafe inference metadata')
    protected_write(bundle/'example/prediction.json',demo.read_bytes())
    evidence=('detector_completed.json','detector/args.yaml','detector/results.csv',
        'pose/completed.json','pose/cv_results.json','pose/original_val_diagnostic.json',
        'pose/normal_training_fit_only.json','pose/frozen_evaluation_plan.json',
        'evaluation/binding.json','evaluation/results.json','evaluation/predictions.jsonl',
        'evaluation/pipeline_predictions.csv')
    for name in evidence:protected_write(bundle/'reports'/name,(out/name).read_bytes())
    for name in ('docs/pallet_pose_model_research_v1.md','docs/pallet_pose_training_v1.md'):
        protected_write(bundle/'reports'/Path(name).name,(PROJECT/name).read_bytes())
    source=('configs/pallet_pose_training_v1.json','pallet/pose_model.py','pallet/pose_training.py',
        'pallet/pose_detector_training.py','pallet/pose_evaluation.py','pallet/pose_inference.py',
        'tests/test_pose_model.py','tests/test_pose_detector_training.py','tests/test_pose_inference.py')
    for name in source:protected_write(bundle/'training_source'/name,(PROJECT/name).read_bytes())
    pipeline=result['pipeline'];metrics=pipeline['conditional_matched_pose_metrics']['overall']
    readme=f'''# 托盘部分位姿模型先导包 v1

已完成真实训练：YOLOv8s（COCO初始化，6552 train/1455 val，20轮）；几何先验＋PointNet风格残差（65帧平面GT、9组、3折内部CV，每折200轮，最终按CV中位数1轮重拟合）；参考点＋法向量网络（38帧同一组、固定200轮）。不是完整6D，不构造缺失旋转。

## 冻结后的测试

49帧/3个独立采集组的平面位姿测试：检测匹配{pipeline['matched_gt_boxes_at_iou_0_5']}/49，实际检测框驱动的XY平均欧氏误差{metrics['position_mae_mm']:.2f}mm、角度平均绝对误差{metrics['angle_mae_degrees']:.3f}°，50mm且5°通过{pipeline['end_to_end_successes_50mm_5deg']}/49。43帧集中在同一组，6帧单位尚未核验，数据量不足以证明可靠部署。真值框ROI结果另列，不与全流程混淆。几何基线与神经网络接近，未证明神经网络显著更优。

法向量只测训练拟合，未获得独立验证/测试成绩。所有输出robot_command_eligible=false；不作为直接叉取控制模型。

## 安装与运行（Python 3.11）

在解压目录中：

```bash
pip install -r requirements.txt
OPENBLAS_NUM_THREADS=1 OMP_NUM_THREADS=2 python -m pallet.pose_inference \\
  --bundle . --image example/image.png --cloud example/cloud.npz \\
  --scale-to-m 1 --device cpu --output my_prediction.json
```

example仅来自原train，推理不读取GT或人工框。新输入必须是相同像素网格的原生强度图和注册点云NPZ，含points_xyzi与pixel_to_source_index；--scale-to-m须由标定给出，不能凭大小猜测。未知单位默认拒绝位姿，仅研究可显式--allow-unverified-units。参考点＋法向量头需--task reference_xyz_normal，不能当完整6D姿态。

文件：detector.pt、planar_pointnet.pt、normal_pointnet.pt、ridge.json及inference_config.json；pallet/含可直接执行的最小推理源码，training_source/保存本轮训练/评估源码快照，reports/含调研、逐组/单位分层结果与逐帧CSV。训练原始数据不重复打包，另使用已交付的pallet_pose_dataset_v2及正式检测集。

```bash
sha256sum -c checksums.sha256
```

本轮为单seed、固定预算先导，不是完整研究对比。框架采用Ultralytics/PyTorch及其各自许可，使用或再发布需遵守相应许可。
'''
    protected_write(bundle/'README_zh.md',readme.encode())
    files={str(p.relative_to(bundle)):digest(p) for p in sorted(bundle.rglob('*'))
        if p.is_file() and p.name not in ('manifest.json','checksums.sha256')}
    manifest={'kind':'partial_pallet_pose_pipeline_pilot','version':1,'state':'trained_pilot_complete',
        'files':files,'pose_manifest_sha256':plan['pose_manifest_sha256'],
        'frozen_plan_sha256':digest(out/'pose/frozen_evaluation_plan.json'),
        'selected_before_test':plan['selected_planar_family'],
        'packages':{k:version(k) for k in ('numpy','torch','torchvision','ultralytics','opencv-python-headless')},
        'detector_gpu':detector['gpu'],'pose_gpu':pose['device'],
        'result_summary':{'test_samples':49,'groups':3,'xy_mae_mm':metrics['position_mae_mm'],
            'theta_mae_degrees':metrics['angle_mae_degrees'],
            'successes_50mm_5deg':pipeline['end_to_end_successes_50mm_5deg']},
        'test_used_for_selection':False,'full_six_dof_available':False,
        'normal_generalization_evaluated':False,'robot_command_eligible':False}
    write_json(bundle/'manifest.json',manifest)
    checks={**files,'manifest.json':digest(bundle/'manifest.json')}
    protected_write(bundle/'checksums.sha256',''.join(f'{sha}  {name}\n' for name,sha in sorted(checks.items())).encode())
    archive=out/'pallet_pose_models_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(bundle.rglob('*')):
                if path.is_file():z.write(path,str(path.relative_to(bundle)))
        temporary.replace(archive)
    all_paths={str(p.relative_to(bundle)) for p in bundle.rglob('*') if p.is_file()}
    with ZipFile(archive) as z:
        if set(z.namelist())!=all_paths:raise ValueError('Model archive member set differs')
        import hashlib
        for name in z.namelist():
            if hashlib.sha256(z.read(name)).hexdigest()!=digest(bundle/name):raise ValueError('Model archive member hash differs')
    record={'state':'complete','kind':'trained_partial_pose_pilot','bundle':str(bundle),'archive':str(archive),
        'archive_sha256':digest(archive),'archive_bytes':archive.stat().st_size,
        'files_verified':len(all_paths),'model_manifest_sha256':digest(bundle/'manifest.json'),
        'real_cpu_inference_demo_passed':True,'source_detection_files_unchanged':len(det_run['protected_formal_files']),
        'source_pose_manifest_unchanged':digest(root/'manifest.json')==plan['pose_manifest_sha256'],
        'summary':manifest['result_summary'],'full_six_dof_available':False,'robot_command_eligible':False}
    write_json(out/'model_delivery_manifest.json',record)
    protected_write(archive.with_suffix('.zip.sha256'),f'{record["archive_sha256"]}  {archive.name}\n'.encode())
    print(json.dumps(record,ensure_ascii=False))
    return record


def main():
    parser=argparse.ArgumentParser(description=__doc__)
    parser.add_argument('--config',type=Path,default=PROJECT/'configs/pallet_pose_training_v1.json')
    args=parser.parse_args();publish(args.config)


if __name__=='__main__':main()
