from __future__ import annotations

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

from .realman_reference import RealManFkReference
from .validation import (
    Stage1Validator,
    ValidationSettings,
    load_project_tools,
    write_validation_report,
)


def _source_project_root() -> Optional[Path]:
    candidate = Path(__file__).resolve().parents[3]
    if (candidate / "xr_rm_bringup").is_dir():
        return candidate
    return None


def _default_output_dir() -> Path:
    package_root = Path(__file__).resolve().parents[2]
    if (package_root / "pyproject.toml").is_file():
        return package_root / "artifacts" / "stage1"
    return Path.cwd() / "stage1_artifacts"


def _default_tools_config() -> Optional[Path]:
    root = _source_project_root()
    if root is None:
        return None
    candidate = root / "xr_rm_bringup" / "config" / "peripherals_rm75.yaml"
    return candidate if candidate.is_file() else None


def build_parser() -> argparse.ArgumentParser:
    parser = argparse.ArgumentParser(
        description="Offline RM75-B stage-1 kinematics and QP IK validation"
    )
    parser.add_argument(
        "--sdk-root",
        type=Path,
        help="directory containing the RealMan Robotic_Arm Python package",
    )
    parser.add_argument(
        "--tools-config",
        type=Path,
        default=_default_tools_config(),
        help="peripherals_rm75.yaml used for tool-frame FK checks",
    )
    parser.add_argument(
        "--skip-tools",
        action="store_true",
        help="skip project tool-frame verification",
    )
    parser.add_argument(
        "--output-dir",
        type=Path,
        default=_default_output_dir(),
        help="directory for JSON, CSV and Markdown reports",
    )
    parser.add_argument("--seed", type=int, default=20260629)
    parser.add_argument(
        "--quick",
        action="store_true",
        help="run a small smoke-validation sample set",
    )
    parser.add_argument(
        "--report-only",
        action="store_true",
        help="always 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)
    settings = (
        ValidationSettings.quick(seed=args.seed, strict=not args.report_only)
        if args.quick
        else ValidationSettings(seed=args.seed, strict=not args.report_only)
    )
    tools = {}
    if not args.skip_tools:
        if args.tools_config is None:
            raise SystemExit(
                "tool validation requested but peripherals_rm75.yaml was not found; "
                "pass --tools-config or --skip-tools"
            )
        tools = load_project_tools(args.tools_config)

    reference = RealManFkReference(args.sdk_root)
    validator = Stage1Validator(reference, settings, tools)
    summary = validator.run()
    paths = write_validation_report(args.output_dir, summary, validator.failures)

    result_text = "PASS" if summary["passed"] else "FAIL"
    print(f"RM75-B stage-1 validation: {result_text}")
    for name, check in summary["checks"].items():
        print(f"  [{'PASS' if check['passed'] else 'FAIL'}] {name}")
    print("Reports:")
    for path in paths:
        print(f"  {path}")
    if args.report_only or summary["passed"]:
        return 0
    return 1


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

