"""Package the frozen best learned models with pinned source and verified hashes."""
import hashlib
import json
from pathlib import Path
import shutil
import sys
from zipfile import ZipFile, ZIP_DEFLATED

PROJECT=Path(__file__).resolve().parents[1]
sys.path.insert(0,str(PROJECT))
from pallet.pose_benchmark import ROOT,SOURCE,sha,atomic_json
from pallet.pose_benchmark_models import PRETRAINED


def put(path,source):
    path.parent.mkdir(parents=True,exist_ok=True)
    content=source.read_bytes()
    if path.exists() and path.read_bytes()!=content:raise ValueError('Existing delivery differs: '+str(path))
    if not path.exists():path.write_bytes(content)


def main():
    selection=json.loads((ROOT/'selection_frozen.json').read_text())
    bundle=ROOT/'deployment';bundle.mkdir(exist_ok=True)
    profiles={}
    for branch,profile in selection['profiles'].items():
        best=profile['best_learning'];family=best['family']
        path=Path('refit')/branch/'selected.pt'
        put(bundle/path,ROOT/path)
        old=json.loads((SOURCE/'training'/branch/'profile.json').read_text())
        profiles[branch]=dict(**best,checkpoint=str(path),domains=old['domains'],
                              deployment_candidate=profile['deployment_candidate'])
        upstream=ROOT/'upstream'/family
        for p in upstream.rglob('*'):
            if not p.is_file() or any(part in ('.git','__pycache__') for part in p.relative_to(upstream).parts):continue
            if p.suffix in ('.py','.yaml','.yml','.toml') or p.name.lower().startswith(('license','copying')):
                put(bundle/'upstream'/family/p.relative_to(upstream),p)
        if family in PRETRAINED:
            filename={'utonia':'utonia_small.pth','sonata':'sonata.pth','concerto':'concerto_small.pth',
                      'litept':'litept_scan.pth','pointmae':'pointmae.pth'}[family]
            put(bundle/'weights'/filename,ROOT/'weights'/filename)
    dependencies=['__init__.py','pose_benchmark_models.py','pose_benchmark.py','pose_benchmark_inference.py',
                  'pose_refinement.py','pose_review_geometry.py','fork_geometry.py','cluster_targets.py',
                  'pose_annotations.py','pose_dataset.py','pose_model.py','pose_inference.py','devices.py',
                  'data/orientation.py','data/pcd.py']
    for name in dependencies:put(bundle/'pallet'/name,PROJECT/'pallet'/name)
    (bundle/'pallet/data/__init__.py').write_text('"""Portable registered point cloud I/O."""\n')
    for name in ('protocol.json','selection_frozen.json','shortlist.json','upstream_manifest.json','weights_manifest.json','final_results.json','REPORT_zh.md','environment.json','deployment_decision.json','final_source_manifest.json'):
        put(bundle/'reports'/name,ROOT/name)
    for name in ('refinement_protocol.json','throughput_fast16.json','throughput_fast24.json'):
        if (ROOT/name).exists():put(bundle/'reports'/name,ROOT/name)
    requirements='numpy==1.26.4\ntorch==2.6.0\ntimm==1.0.30\neinops==0.8.2\naddict==2.4.0\neasydict==1.13\ncolorhash==2.3.0\nscipy==1.15.3\nopencv-python-headless==4.11.0.86\npillow==11.0.0\nhuggingface-hub==1.33.0\n'
    (bundle/'requirements.txt').write_text(requirements)
    readme='''# 托盘位姿 v3 最佳学习模型

这是本轮原train分组评测选出的最佳学习方案，不代表已优于几何或已上线。
逐分支部署建议和完整分母结果见 reports/REPORT_zh.md。

使用包内代码，无须原始标签：

```bash
python -m pallet.pose_benchmark_inference --bundle . --cloud registered.npz \\
  --box X Y WIDTH HEIGHT --domain SENSOR_DOMAIN --scale-to-m SCALE --output pose.json
```

NPZ包含 points_xyzi[N,4] 与 pixel_to_source_index[H,W]。
未知单位去掉 --scale-to-m，显式增加 --allow-native。
输入框为原图像素坐标；检测器保持v1，可用其框作为此入口输入。
默认CUDA；稀疏Transformer另外需要匹配torch/CUDA的spconv、torch-scatter和flash-attn，
版本及本轮算子适配详见 reports/environment.json 与研究文档。
模型输出仍需人工审核，未包含z/完整6D/机器人外参。
'''
    (bundle/'README_zh.md').write_text(readme)
    files={str(p.relative_to(bundle)):sha(p) for p in bundle.rglob('*') if p.is_file() and p.name!='bundle_config.json' and '__pycache__' not in p.parts}
    atomic_json(bundle/'bundle_config.json',dict(schema='pose_benchmark_v3',profiles=profiles,files=files,
                robot_command_eligible=False,original_test_used_for_selection=False,
                source_label_kind='user_authorized_nonblind_research_drafts'))
    paths=[p for p in bundle.rglob('*') if p.is_file() and '__pycache__' not in p.parts]
    destination=ROOT/'pallet_pose_best_learning_models_v3.zip'
    with ZipFile(destination.with_suffix('.tmp'),'w',ZIP_DEFLATED,compresslevel=6) as z:
        for p in sorted(paths):z.write(p,str(p.relative_to(bundle)))
    destination.with_suffix('.tmp').replace(destination)
    with ZipFile(destination) as z:
        for name in z.namelist():assert hashlib.sha256(z.read(name)).hexdigest()==sha(bundle/name)
    atomic_json(ROOT/'delivery_manifest.json',dict(archive=str(destination),bytes=destination.stat().st_size,
                sha256=sha(destination),members_verified=len(paths),models=profiles,
                live_annotations_modified=False,active_entry_modified=False))


if __name__=='__main__':main()
