#!/usr/bin/env python3
"""Export priority LiDAR–IMU windows from calibration_usable_20260808.

Does not push anything; writes local V1 sessions under --out-root.
"""

from __future__ import annotations

import argparse
import json
import sys
from pathlib import Path

ROOT = Path(__file__).resolve().parents[1]
if str(ROOT) not in sys.path:
    sys.path.insert(0, str(ROOT))

from tools.export_rscap_to_v1 import export_session

DEFAULT_DATA = Path(r"D:\data\calibration_usable_20260808")
LIDAR_ZIP = "lidar_dlog/dorec_recovered_20260808_171438_181422.zip"
IMU_MAIN = "imu_rscap/hi13r4-imu_20260808-092827.638_39783edb-e46e-4b28-a5e8-427b981c2fce.rscap"
IMU_TAIL = "imu_rscap/hi13r4-imu_20260808-101022.036_87ea5edc-cd3d-4192-809a-469fbc8cac01.rscap"

# From usable-segment chart (local wall clock).
WINDOWS = [
    {
        "name": "priority_174005_174515",
        "host_start": "2026-08-08T17:40:05",
        "host_end": "2026-08-08T17:45:15",
        "imu": [IMU_MAIN],
        "priority": True,
    },
    {
        "name": "priority_174905_175450",
        "host_start": "2026-08-08T17:49:05",
        "host_end": "2026-08-08T17:54:50",
        "imu": [IMU_MAIN],
        "priority": True,
    },
    {
        "name": "priority_175910_180530",
        "host_start": "2026-08-08T17:59:10",
        "host_end": "2026-08-08T18:05:30",
        "imu": [IMU_MAIN],
        "priority": True,
    },
    {
        "name": "usable_181035_181050",
        "host_start": "2026-08-08T18:10:35",
        "host_end": "2026-08-08T18:10:50",
        "imu": [IMU_TAIL],
        "priority": False,
    },
    {
        "name": "usable_181225_181300",
        "host_start": "2026-08-08T18:12:25",
        "host_end": "2026-08-08T18:13:00",
        "imu": [IMU_TAIL],
        "priority": False,
    },
    {
        "name": "usable_181350_181410",
        "host_start": "2026-08-08T18:13:50",
        "host_end": "2026-08-08T18:14:10",
        "imu": [IMU_TAIL],
        "priority": False,
    },
]


def main() -> int:
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--data-root", type=Path, default=DEFAULT_DATA)
    parser.add_argument(
        "--out-root",
        type=Path,
        default=DEFAULT_DATA / "sessions_v1",
    )
    parser.add_argument("--priority-only", action="store_true", default=True)
    parser.add_argument("--all-windows", action="store_true")
    parser.add_argument("--frame-stride", type=int, default=5)
    parser.add_argument("--max-points-per-frame", type=int, default=40000)
    args = parser.parse_args()
    priority_only = not args.all_windows
    lidar = args.data_root / LIDAR_ZIP
    if not lidar.is_file():
        raise SystemExit(f"missing lidar zip: {lidar}")

    selected = [w for w in WINDOWS if (not priority_only) or w["priority"]]
    results = []
    for window in selected:
        out = args.out_root / window["name"]
        imu_paths = [args.data_root / rel for rel in window["imu"]]
        print(f"=== exporting {window['name']} ===", flush=True)
        summary = export_session(
            imu_rscap=imu_paths,
            lidar_dlog=lidar,
            imu_kind="hi13",
            require_difop=True,
            host_start=window["host_start"],
            host_end=window["host_end"],
            out=out,
            frame_stride=args.frame_stride,
            max_points_per_frame=args.max_points_per_frame,
        )
        brief = {
            "name": window["name"],
            "imu_samples": summary["imu"]["samples"],
            "lidar_frames": summary["lidar"]["frames"],
            "angle_source": summary["lidar"]["angle_source"],
            "out": str(out),
        }
        results.append(brief)
        print(json.dumps(brief, ensure_ascii=False, indent=2), flush=True)

    manifest = args.out_root / "export_windows_manifest.json"
    args.out_root.mkdir(parents=True, exist_ok=True)
    manifest.write_text(json.dumps(results, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
    print(f"manifest: {manifest}")
    return 0


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