#!/usr/bin/env python3
"""Run R1b/R2V/R2G/R3 on unified native-time G90/HI13 exports."""

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 rtk_imu.rtk_imu_multisource import (
    load_unified_sessions,
    result_to_jsonable,
    solve_r3,
)


def main(argv: list[str] | None = None) -> int:
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--manifest", type=Path, required=True)
    parser.add_argument("--output", type=Path, required=True)
    parser.add_argument("--session", action="append")
    parser.add_argument("--level-static", action="append", required=True)
    args = parser.parse_args(argv)
    selected = None if not args.session else set(args.session) | set(args.level_static)
    sessions = load_unified_sessions(args.manifest, selected_session_ids=selected)
    result = solve_r3(sessions, level_static_session_ids=set(args.level_static))
    payload = result_to_jsonable(result)
    args.output.parent.mkdir(parents=True, exist_ok=True)
    args.output.write_text(
        json.dumps(payload, ensure_ascii=False, indent=2) + "\n", encoding="utf-8"
    )
    print(json.dumps(payload, ensure_ascii=False, indent=2))
    return 0


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