from __future__ import annotations

import argparse
import os
import sys
from pathlib import Path
from typing import Optional, Sequence


os.environ.setdefault("MUJOCO_GL", "egl")


def _source_root() -> Path:
    return Path(__file__).resolve().parents[3]


def build_parser() -> argparse.ArgumentParser:
    root = _source_root()
    parser = argparse.ArgumentParser(
        description="Validate right-arm and dual-grip QP control in MuJoCo"
    )
    parser.add_argument("--sdk-root", type=Path)
    parser.add_argument(
        "--teleop-config",
        type=Path,
        default=root / "xr_rm_bringup/config/dual_arm_rm75.yaml",
    )
    parser.add_argument(
        "--peripheral-config",
        type=Path,
        default=root / "xr_rm_bringup/config/peripherals_rm75.yaml",
    )
    parser.add_argument(
        "--output-dir",
        type=Path,
        default=root / "ik_qp/artifacts/stage3",
    )
    parser.add_argument("--seed", type=int, default=20260630)
    parser.add_argument("--quick", action="store_true")
    parser.add_argument("--report-only", action="store_true")
    return parser


def main(argv: Optional[Sequence[str]] = None) -> int:
    args = build_parser().parse_args(argv)
    from .realman_reference import RealManFkReference
    from .stage3_validation import (
        Stage3Settings,
        Stage3Validator,
        write_stage3_report,
    )

    settings = (
        Stage3Settings.quick(args.seed)
        if args.quick
        else Stage3Settings(seed=args.seed)
    )
    validator = Stage3Validator(
        RealManFkReference(args.sdk_root),
        args.teleop_config,
        args.peripheral_config,
        settings,
    )
    summary = validator.run()
    paths = write_stage3_report(
        args.output_dir, summary, validator.failures, validator.images
    )
    print(f"RM75-B stage-3 validation: {'PASS' if summary['passed'] else 'FAIL'}")
    for name, check in summary["checks"].items():
        print(f"  [{'PASS' if check['passed'] else 'FAIL'}] {name}")
    print("Reports:")
    for path in (*paths[:3], *paths[3]):
        print(f"  {path}")
    return 0 if args.report_only or summary["passed"] else 1


if __name__ == "__main__":
    sys.exit(main())
