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 _default_output_dir() -> Path:
    package_root = Path(__file__).resolve().parents[2]
    if (package_root / "pyproject.toml").is_file():
        return package_root / "artifacts" / "stage2"
    return Path.cwd() / "stage2_artifacts"


def build_parser() -> argparse.ArgumentParser:
    parser = argparse.ArgumentParser(
        description="Headless single-arm IK validation in the normalized dual RM75 scene"
    )
    parser.add_argument("--arm", choices=("left", "right"), default="left")
    parser.add_argument(
        "--sdk-root",
        type=Path,
        help="directory containing the RealMan Robotic_Arm Python package",
    )
    parser.add_argument("--output-dir", type=Path, default=_default_output_dir())
    parser.add_argument("--seed", type=int, default=20260630)
    parser.add_argument("--quick", action="store_true")
    parser.add_argument(
        "--report-only",
        action="store_true",
        help="return exit code zero while preserving failed checks in reports",
    )
    return parser


def main(argv: Optional[Sequence[str]] = None) -> int:
    args = build_parser().parse_args(argv)
    from .realman_reference import RealManFkReference
    from .stage2_validation import (
        Stage2Settings,
        Stage2Validator,
        write_stage2_report,
    )

    settings = (
        Stage2Settings.quick(seed=args.seed)
        if args.quick
        else Stage2Settings(seed=args.seed)
    )
    validator = Stage2Validator(
        RealManFkReference(args.sdk_root),
        controlled_arm=args.arm,
        settings=settings,
    )
    summary = validator.run()
    json_path, csv_path, markdown_path, image_paths = write_stage2_report(
        args.output_dir,
        summary,
        validator.failures,
        validator.images,
    )
    print(f"RM75-B stage-2 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 (json_path, csv_path, markdown_path, *image_paths):
        print(f"  {path}")
    if args.report_only or summary["passed"]:
        return 0
    return 1


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

