#!/usr/bin/env python3
"""Build a field-retaining LiDAR replay pack from immutable K1 capture evidence."""

from __future__ import annotations

import argparse
import json
from pathlib import Path

from k1link.compute import LidarReplayPackV2, build_lidar_replay_pack_v2


def arguments() -> argparse.Namespace:
    parser = argparse.ArgumentParser()
    parser.add_argument("--capture", type=Path, required=True)
    parser.add_argument("--output-root", type=Path, required=True)
    parser.add_argument("--session-id")
    parser.add_argument("--pose-coverage-threshold-ms", type=float, default=100.0)
    return parser.parse_args()


def main() -> int:
    args = arguments()
    output = build_lidar_replay_pack_v2(
        args.capture,
        args.output_root,
        session_id=args.session_id,
        pose_coverage_threshold_ms=args.pose_coverage_threshold_ms,
    )
    pack = LidarReplayPackV2(output)
    try:
        print(
            json.dumps(
                {
                    "pack_id": pack.pack_id,
                    "output": str(output),
                    "session_id": pack.identity["session_id"],
                    "point_frames": pack.point_frame_count,
                    "pose_frames": pack.pose_frame_count,
                    "points": pack.point_count,
                    "equivalence": pack.equivalence["status"],
                    "pose_coverage_fraction": pack.quality["pose_binding"][
                        "coverage_fraction"
                    ],
                },
                ensure_ascii=False,
                sort_keys=True,
            )
        )
    finally:
        pack.close()
    return 0


if __name__ == "__main__":
    raise SystemExit(main())
