"""One-click synthetic reproduce: generate → calibrate → report → pytest."""

from __future__ import annotations

import argparse
import subprocess
import sys
from pathlib import Path


def _repo_root() -> Path:
    return Path(__file__).resolve().parents[1]


def _run(cmd: list[str], cwd: Path) -> None:
    print("+", " ".join(cmd), flush=True)
    completed = subprocess.run(cmd, cwd=str(cwd), check=False)
    if completed.returncode != 0:
        raise SystemExit(completed.returncode)


def main(argv: list[str] | None = None) -> int:
    parser = argparse.ArgumentParser(
        description="Generate synthetic LiDAR–IMU data, run calibration, show report, run tests."
    )
    parser.add_argument(
        "--mode",
        choices=["rotation_only", "full_se3"],
        default="rotation_only",
    )
    parser.add_argument("--skip-pytest", action="store_true")
    args = parser.parse_args(argv)

    root = _repo_root()
    session = root / "examples" / "synthetic_session"
    imu = session / "imu.csv"
    lidar = session / "lidar"
    calib_out = session / "out"
    config = root / "config" / "vehicle_installation.template.yaml"

    print("=== 1/4 generate synthetic session ===", flush=True)
    _run([sys.executable, str(root / "tools" / "generate_synthetic_session.py")], cwd=root)

    print("=== 2/4 run calibration ===", flush=True)
    _run(
        [
            sys.executable,
            "-m",
            "imu_lidar.cli",
            "run",
            "--vehicle-config",
            str(config),
            "--imu",
            str(imu),
            "--lidar",
            str(lidar),
            "--output",
            str(calib_out),
            "--mode",
            args.mode,
            "--time-offset-search-s",
            "0.5",
            "--min-pair-rotation-deg",
            "2.0",
            "--min-pair-translation-m",
            "0.05",
            "--max-iterations",
            "1",
        ],
        cwd=root,
    )

    print("=== 3/4 show report ===", flush=True)
    _run(
        [
            sys.executable,
            str(root / "tools" / "show_calibration_report.py"),
            "--summary",
            str(calib_out / "summary.json"),
            "--truth-meta",
            str(session / "meta.json"),
            "--plot",
            str(calib_out / "report_preview.png"),
        ],
        cwd=root,
    )

    if args.skip_pytest:
        print("=== 4/4 pytest skipped ===", flush=True)
    else:
        print("=== 4/4 pytest ===", flush=True)
        _run([sys.executable, "-m", "pytest", "-q"], cwd=root)

    print("\nDone.")
    print("  INPUT")
    print(f"    IMU CSV     : {imu}")
    print(f"    LiDAR dir   : {lidar}")
    print(f"    vehicle YAML: {config}")
    print("  OUTPUT")
    print(f"    directory   : {calib_out}")
    print(f"    T           : {calib_out / 'T_IMU_lidar.json'}")
    print(f"    δt          : {calib_out / 'time_offset.json'}")
    print(f"    summary     : {calib_out / 'summary.json'}")
    print(f"    preview PNG : {calib_out / 'report_preview.png'}")
    return 0


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