#!/usr/bin/env bash
set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(cd "${SCRIPT_DIR}/../.." && pwd)"
PYTHON_BIN="${PYTHON_BIN:-python}"

# Launcher for batch exporting PDCL clips and running two-ROI inference.
#
# Usage:
#   bash tools/pdcl_inference/run_batch_two_roi_infer.sh
#
# Common env overrides:
#   CLIP_LIST_FILE, EXPORT_ROOT, VISUALIZATION_ROOT
#
# Optional env overrides:
#   OUTPUT_PREFIX, CAMERA_TOPIC, MAX_FRAMES_PER_CLIP, CALIB_FILE,
#   ROI0_MODEL, ROI1_MODEL, DEVICE, LIMIT_CLIPS, SKIP_DONE, HALF, EXTRA_ARGS

CLIP_LIST_FILE="${CLIP_LIST_FILE:-${SCRIPT_DIR}/clips_aeb.txt}"
EXPORT_ROOT="${EXPORT_ROOT:-${SCRIPT_DIR}/clip_exports}"
OUTPUT_PREFIX="${OUTPUT_PREFIX:-clip_export}"
CAMERA_TOPIC="${CAMERA_TOPIC:-camera4}"
MAX_FRAMES_PER_CLIP="${MAX_FRAMES_PER_CLIP:-0}"
CALIB_FILE="${CALIB_FILE:-}"
VISUALIZATION_ROOT="${VISUALIZATION_ROOT:-${SCRIPT_DIR}/visualization_aeb_20260403}"
ROI0_MODEL="${ROI0_MODEL:-${PROJECT_ROOT}/runs/detect/mono3d_roi0_20260403_epoch99.pt}"
ROI1_MODEL="${ROI1_MODEL:-${PROJECT_ROOT}/runs/detect/mono3d_roi1_20260403_epoch99.pt}"
DEVICE="${DEVICE:-0}"
LIMIT_CLIPS="${LIMIT_CLIPS:-0}"
SKIP_DONE="${SKIP_DONE:-1}"
HALF="${HALF:-0}"
EXTRA_ARGS="${EXTRA_ARGS:-}"

CMD=(
  "${PYTHON_BIN}" "${PROJECT_ROOT}/tools/pdcl_inference/run_batch_two_roi_infer.py"
  --clip-list-file "${CLIP_LIST_FILE}"
  --export-root "${EXPORT_ROOT}"
  --output-prefix "${OUTPUT_PREFIX}"
  --camera-topic "${CAMERA_TOPIC}"
  --max-frames-per-clip "${MAX_FRAMES_PER_CLIP}"
  --visualization-root "${VISUALIZATION_ROOT}"
  --roi0-model "${ROI0_MODEL}"
  --roi1-model "${ROI1_MODEL}"
  --device "${DEVICE}"
)

if [[ -n "${CALIB_FILE}" ]]; then
  CMD+=(--calib-file "${CALIB_FILE}")
fi

if [[ "${LIMIT_CLIPS}" != "0" ]]; then
  CMD+=(--limit-clips "${LIMIT_CLIPS}")
fi

if [[ "${SKIP_DONE}" == "1" ]]; then
  CMD+=(--skip-done)
fi

if [[ "${HALF}" == "1" ]]; then
  CMD+=(--half)
fi

if [[ -n "${EXTRA_ARGS}" ]]; then
  # shellcheck disable=SC2206
  EXTRA_ARR=(${EXTRA_ARGS})
  CMD+=("${EXTRA_ARR[@]}")
fi

CMD+=("$@")

"${CMD[@]}"


# /data1/dongying/Mono3d/G1Q3/feishu_project/downloaded_issue_data/issue_6841968325\pdcl_01\20260227163613