#!/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 undistorting decoded PDCL clip data.
#
# Usage:
#   bash tools/pdcl_inference/undistort_decoded_clip_data.sh
#
# Preferred env overrides:
#   CASE_DIR, OUTPUT_DIR
#
# Optional env overrides:
#   IMAGES_DIR, CALIB_FILE, GLOB, TARGET_SIZE_W, TARGET_SIZE_H,
#   CROP_CENTER_X, CROP_CENTER_Y, TARGET_FX, EXTRA_ARGS

CASE_DIR="${CASE_DIR:-}"
# OUTPUT_DIR="${OUTPUT_DIR:-${CASE_DIR}_undist}"

IMAGES_DIR="${IMAGES_DIR:-/data1/dongying/Mono3d/G1M3/cases_coding/249/2025-09-09_11-49-49_voice_经过旁车是大车误制动/sigmastar.1/images_1616}"
CALIB_FILE="${CALIB_FILE:-/data1/dongying/Mono3d/G1M3/cases_coding/249/2025-09-09_11-49-49_voice_经过旁车是大车误制动/sigmastar.1/calibs/camera4.json}"
GLOB="${GLOB:-*.jpg}"
TARGET_SIZE_W="${TARGET_SIZE_W:-}"
TARGET_SIZE_H="${TARGET_SIZE_H:-}"
CROP_CENTER_X="${CROP_CENTER_X:-}"
CROP_CENTER_Y="${CROP_CENTER_Y:-}"
TARGET_FX="${TARGET_FX:-}"
EXTRA_ARGS="${EXTRA_ARGS:-}"

OUTPUT_DIR="${OUTPUT_DIR:-${IMAGES_DIR}_undist}"

CMD=(
  "${PYTHON_BIN}" "${PROJECT_ROOT}/tools/pdcl_inference/undistort_decoded_clip_data.py"
  --output-dir "${OUTPUT_DIR}"
  --glob "${GLOB}"
  --overwrite
)

if [[ -n "${CASE_DIR}" ]]; then
  CMD+=(--case-dir "${CASE_DIR}")
else
  if [[ -z "${IMAGES_DIR}" || -z "${CALIB_FILE}" ]]; then
    echo "Error: set CASE_DIR, or set both IMAGES_DIR and CALIB_FILE."
    exit 1
  fi
  CMD+=(--images-dir "${IMAGES_DIR}" --calib-file "${CALIB_FILE}")
fi

if [[ -n "${TARGET_SIZE_W}" && -n "${TARGET_SIZE_H}" ]]; then
  CMD+=(--target-size "${TARGET_SIZE_W}" "${TARGET_SIZE_H}")
fi

if [[ -n "${CROP_CENTER_X}" ]]; then
  CMD+=(--crop-center-x "${CROP_CENTER_X}")
fi

if [[ -n "${CROP_CENTER_Y}" ]]; then
  CMD+=(--crop-center-y "${CROP_CENTER_Y}")
fi

if [[ -n "${TARGET_FX}" ]]; then
  CMD+=(--target-fx "${TARGET_FX}")
fi

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

"${CMD[@]}"
