import argparse
import sys
from pathlib import Path

FILE = Path(__file__).resolve()
ROOT = FILE.parents[2]
if str(ROOT) not in sys.path:
    sys.path.append(str(ROOT))

from tools.pdcl_inference.run_batch_two_roi_infer import (
    add_inference_args,
    build_two_roi_inference_context_from_args,
)
from tools.pdcl_inference.two_roi_inference import (
    DEFAULT_VISUALIZATION_ROOT,
    run_case_inference,
    run_video_case_inference,
)


def parse_args() -> argparse.Namespace:
    parser = argparse.ArgumentParser(description="Run two-ROI Detect3D inference on one exported PDCL case or image directory.")
    parser.add_argument("--case-dir", type=str, default="", help="Case directory containing images/ and calib/L2_calib/camera4.json")
    parser.add_argument("--video-case-dir", type=str, default="", help="Video case path or camera4.bin path with nearby camera4.json")
    parser.add_argument("--video-stride", type=int, default=1, help="Read every Nth frame from camera4.bin inputs")
    parser.add_argument("--images-dir", type=str, default="", help="Input image directory when --case-dir is not used")
    parser.add_argument("--calib-file", type=str, default="", help="Input camera4.json path when --case-dir is not used")
    parser.add_argument("--glob", type=str, default="*.png", help="Image glob inside the case images directory")
    parser.add_argument("--max-images", type=int, default=0, help="Maximum number of images/frames to process; 0 means all")
    parser.add_argument(
        "--output-dir",
        type=str,
        default=str(DEFAULT_VISUALIZATION_ROOT),
        help="Visualization output directory or root",
    )
    add_inference_args(parser)
    return parser.parse_args()


def main() -> None:
    args = parse_args()
    context = build_two_roi_inference_context_from_args(args)
    output_dir = Path(args.output_dir)
    output_root = output_dir if output_dir != DEFAULT_VISUALIZATION_ROOT else DEFAULT_VISUALIZATION_ROOT
    if args.video_case_dir:
        result = run_video_case_inference(
            context=context,
            video_case_dir=args.video_case_dir,
            output_dir=output_root,
            max_images=args.max_images,
            video_stride=args.video_stride,
        )
    else:
        result = run_case_inference(
            context=context,
            case_dir=args.case_dir,
            images_dir=args.images_dir,
            calib_file=args.calib_file,
            output_dir=output_root,
            glob_pattern=args.glob,
            max_images=args.max_images,
        )
    print(f"Saved {result['num_frames']} visualizations to {result['output_dir']}")
    print(f"Predictions JSON: {result['predictions_path']}")


if __name__ == "__main__":
    main()
