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

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
MODEL_INFERENCE_DIR="$(cd "${SCRIPT_DIR}/.." && pwd)"
BASE_SCRIPT="${SCRIPT_DIR}/run_two_roi_exported_onnx_infer_event_json.sh"

# Launcher for CNCAP scene/rawid batch inference based on scene-grouped JSON
# records that contain direct clip-id lists.

PYTHON_BIN="${PYTHON_BIN:-/deeplearning_team/ydong/dongying/miniconda/envs/dev/bin/python}"
EVENT_JSON_FILE="${EVENT_JSON_FILE:-${MODEL_INFERENCE_DIR}/examples/cncap/aeb_clips-20260429.json}"
SCENE="${SCENE:-SCP}"
EVENT_ID_FIELD="${EVENT_ID_FIELD:-rawid}"
EVENT_CLIP_IDS_FIELD="${EVENT_CLIP_IDS_FIELD:-clips}"
CONDITION_FIELDS="${CONDITION_FIELDS:-偏置 目标速度 自车速度}"
MAX_RECORDS_PER_CONDITION="${MAX_RECORDS_PER_CONDITION:-1}"
CONDITION_SELECT_STRATEGY="${CONDITION_SELECT_STRATEGY:-first}"
SELECTION_ONLY="${SELECTION_ONLY:-0}"
MAX_EVENTS="${MAX_EVENTS:-0}"
EVENT_CACHE_FILE="${EVENT_CACHE_FILE:-${MODEL_INFERENCE_DIR}/.cache/event_clip_cache.json}"
EVENT_RESOLVE_WORKERS="${EVENT_RESOLVE_WORKERS:-4}"
EVENT_REQUEST_TIMEOUT="${EVENT_REQUEST_TIMEOUT:-60}"
EVENT_REQUEST_RETRIES="${EVENT_REQUEST_RETRIES:-3}"
EVENT_REQUEST_RETRY_BACKOFF_SEC="${EVENT_REQUEST_RETRY_BACKOFF_SEC:-2.0}"
EXPORT_ROOT="${EXPORT_ROOT:-/data1/dongying/Mono3d/G1Q3/model_inference/cncap/aeb_clips_20260429_selected/event_exports}"
OUTPUT_PREFIX="${OUTPUT_PREFIX:-clip}"
CAMERA_TOPIC="${CAMERA_TOPIC:-camera4}"
MAX_FRAMES_PER_CLIP="${MAX_FRAMES_PER_CLIP:-0}"
LIMIT_CLIPS="${LIMIT_CLIPS:-0}"
SKIP_DONE="${SKIP_DONE:-1}"
EXPORTED_MODEL="${EXPORTED_MODEL:-${MODEL_INFERENCE_DIR}/../../runs/export/train_mono3d_two_roi_20260506-drop_fake_3d_branch/merged_model.torchscript}"
OUTPUT_DIR="${OUTPUT_DIR:-/data1/dongying/Mono3d/G1Q3/model_inference/cncap/aeb_clips_20260429_selected/model_20260506_vis_distance}"
ENABLE_ATTR="${ENABLE_ATTR:-0}"
ENABLE_CROSS_CLASS_MERGE_PRIOR="${ENABLE_CROSS_CLASS_MERGE_PRIOR:-1}"
SHOW_DISTANCE_LABEL="${SHOW_DISTANCE_LABEL:-1}"
DISTANCE_LABEL_MODE="${DISTANCE_LABEL_MODE:-depth_lateral}"
DISTANCE_LABEL_PANELS="${DISTANCE_LABEL_PANELS:-3d}"
EXTRA_ARGS="${EXTRA_ARGS:-}"

# Optional rawid L2 package download through mdi.
ENABLE_RAW_L2_DOWNLOAD="${ENABLE_RAW_L2_DOWNLOAD:-1}"
RAW_L2_DOWNLOAD_ONLY="${RAW_L2_DOWNLOAD_ONLY:-0}"
RAW_L2_DOWNLOAD_ROOT="${RAW_L2_DOWNLOAD_ROOT:-/data1/dongying/Mono3d/G1Q3/model_inference/cncap/aeb_clips_20260429_selected/raw_l2}"
RAW_L2_DOWNLOAD_MANIFEST="${RAW_L2_DOWNLOAD_MANIFEST:-${RAW_L2_DOWNLOAD_ROOT}/download_manifest.json}"
RAW_L2_DOWNLOAD_DRY_RUN="${RAW_L2_DOWNLOAD_DRY_RUN:-0}"
RAW_L2_DOWNLOAD_SKIP_DONE="${RAW_L2_DOWNLOAD_SKIP_DONE:-1}"
RAW_L2_DOWNLOAD_STRICT="${RAW_L2_DOWNLOAD_STRICT:-1}"

# Auto-tracking is delegated to the shared event-json launcher.
# Set TRACK_ONLY=1 to skip clip export/inference and run tracking on OUTPUT_DIR.
# Set CONVERT_ONLY=1 to skip clip export/inference and tracking, then convert.
TRACK_ONLY="${TRACK_ONLY:-0}"
CONVERT_ONLY="${CONVERT_ONLY:-0}"
AUTO_TRACK="${AUTO_TRACK:-1}"
TRACK_CLASSES="${TRACK_CLASSES:-0 1 2 3 4 5 6 7 8 9 10 11 12 17 18 19}"
TRACK_IOU_THRESH="${TRACK_IOU_THRESH:-0.3}"
TRACK_MAX_AGE="${TRACK_MAX_AGE:-5}"
TRACK_MIN_HITS="${TRACK_MIN_HITS:-1}"
TRACK_DIST_THRESH="${TRACK_DIST_THRESH:-100}"
TRACK_MAX_3D_DISTANCE="${TRACK_MAX_3D_DISTANCE:-10.0}"
TRACK_MODEL_VERSION="${TRACK_MODEL_VERSION:-20260506}"
TRACK_FILE_PATTERN="${TRACK_FILE_PATTERN:-*.json}"
TRACK_ENABLE_USE_3D="${TRACK_ENABLE_USE_3D:-0}"
TRACK_MERGE_OUTPUT_NAME="${TRACK_MERGE_OUTPUT_NAME:-combined_tracking.json}"
TRACK_MANIFEST_NAME="${TRACK_MANIFEST_NAME:-frame_order_manifest.json}"
TRACK_EVENT_TRACKING_DIRNAME="${TRACK_EVENT_TRACKING_DIRNAME:-}"

# Post-tracking protocol conversion. This scene launcher converts only the
# event-level merge.json by default.
ENABLE_CONVERT="${ENABLE_CONVERT:-1}"
CONVERT_STRICT="${CONVERT_STRICT:-1}"
CONVERT_RESULTS_ROOT="${CONVERT_RESULTS_ROOT:-${OUTPUT_DIR}}"
CONVERT_OUTPUT_ROOT="${CONVERT_OUTPUT_ROOT:-${OUTPUT_DIR%/}_objectlist}"
CONVERT_OUTPUT_LAYOUT="${CONVERT_OUTPUT_LAYOUT:-parallel_root}"
CONVERT_OUTPUT_DIR_NAME="${CONVERT_OUTPUT_DIR_NAME:-objectlist}"
CONVERT_MERGE_JSON_NAME="${CONVERT_MERGE_JSON_NAME:-merge.json}"
CONVERT_PARALLEL_JOBS="${CONVERT_PARALLEL_JOBS:-4}"
CONVERT_CAM_ID="${CONVERT_CAM_ID:-}"

if [[ ! -f "${BASE_SCRIPT}" ]]; then
  echo "Base launcher not found: ${BASE_SCRIPT}" >&2
  exit 1
fi

run_raw_l2_download() {
  local downloader="${MODEL_INFERENCE_DIR}/core/download_rawid_l2_by_event_json.py"
  if [[ ! -f "${downloader}" ]]; then
    echo "Raw L2 downloader not found: ${downloader}" >&2
    exit 1
  fi

  local -a cmd=(
    "${PYTHON_BIN}" "${downloader}"
    --event-json-file "${EVENT_JSON_FILE}"
    --event-id-field "${EVENT_ID_FIELD}"
    --event-clip-ids-field "${EVENT_CLIP_IDS_FIELD}"
    --event-cache-file "${EVENT_CACHE_FILE}"
    --event-resolve-workers "${EVENT_RESOLVE_WORKERS}"
    --event-request-timeout "${EVENT_REQUEST_TIMEOUT}"
    --event-request-retries "${EVENT_REQUEST_RETRIES}"
    --event-request-retry-backoff-sec "${EVENT_REQUEST_RETRY_BACKOFF_SEC}"
    --output-root "${RAW_L2_DOWNLOAD_ROOT}"
    --manifest-path "${RAW_L2_DOWNLOAD_MANIFEST}"
  )

  if [[ -n "${SCENE}" ]]; then
    cmd+=(--scene "${SCENE}")
  fi

  if [[ -n "${CONDITION_FIELDS}" ]]; then
    # shellcheck disable=SC2206
    CONDITION_FIELDS_ARR=(${CONDITION_FIELDS})
    cmd+=(--condition-fields "${CONDITION_FIELDS_ARR[@]}")
  fi

  if [[ "${MAX_RECORDS_PER_CONDITION}" != "0" ]]; then
    cmd+=(--max-records-per-condition "${MAX_RECORDS_PER_CONDITION}")
  fi

  if [[ -n "${CONDITION_SELECT_STRATEGY}" ]]; then
    cmd+=(--condition-select-strategy "${CONDITION_SELECT_STRATEGY}")
  fi

  if [[ "${MAX_EVENTS}" != "0" ]]; then
    cmd+=(--max-events "${MAX_EVENTS}")
  fi

  if [[ "${RAW_L2_DOWNLOAD_DRY_RUN}" == "1" ]]; then
    cmd+=(--dry-run)
  fi

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

  if [[ "${RAW_L2_DOWNLOAD_STRICT}" == "1" ]]; then
    cmd+=(--strict)
  fi

  echo ""
  echo "######################################################################"
  echo "# Rawid L2 package download through mdi"
  echo "######################################################################"
  echo "Download root : ${RAW_L2_DOWNLOAD_ROOT}"
  echo "Manifest      : ${RAW_L2_DOWNLOAD_MANIFEST}"
  "${cmd[@]}"
}

if [[ "${ENABLE_RAW_L2_DOWNLOAD}" == "1" || "${RAW_L2_DOWNLOAD_ONLY}" == "1" ]]; then
  if [[ "${RAW_L2_DOWNLOAD_STRICT}" == "1" ]]; then
    run_raw_l2_download
  else
    if ! run_raw_l2_download; then
      echo "[WARN] Raw L2 download failed, continuing because RAW_L2_DOWNLOAD_STRICT=0" >&2
    fi
  fi
fi

if [[ "${RAW_L2_DOWNLOAD_ONLY}" == "1" ]]; then
  exit 0
fi

env \
  PYTHON_BIN="${PYTHON_BIN}" \
  EVENT_JSON_FILE="${EVENT_JSON_FILE}" \
  SCENE="${SCENE}" \
  EVENT_ID_FIELD="${EVENT_ID_FIELD}" \
  EVENT_CLIP_IDS_FIELD="${EVENT_CLIP_IDS_FIELD}" \
  CONDITION_FIELDS="${CONDITION_FIELDS}" \
  MAX_RECORDS_PER_CONDITION="${MAX_RECORDS_PER_CONDITION}" \
  CONDITION_SELECT_STRATEGY="${CONDITION_SELECT_STRATEGY}" \
  SELECTION_ONLY="${SELECTION_ONLY}" \
  MAX_EVENTS="${MAX_EVENTS}" \
  EVENT_CACHE_FILE="${EVENT_CACHE_FILE}" \
  EVENT_RESOLVE_WORKERS="${EVENT_RESOLVE_WORKERS}" \
  EVENT_REQUEST_TIMEOUT="${EVENT_REQUEST_TIMEOUT}" \
  EVENT_REQUEST_RETRIES="${EVENT_REQUEST_RETRIES}" \
  EVENT_REQUEST_RETRY_BACKOFF_SEC="${EVENT_REQUEST_RETRY_BACKOFF_SEC}" \
  EXPORT_ROOT="${EXPORT_ROOT}" \
  OUTPUT_PREFIX="${OUTPUT_PREFIX}" \
  CAMERA_TOPIC="${CAMERA_TOPIC}" \
  MAX_FRAMES_PER_CLIP="${MAX_FRAMES_PER_CLIP}" \
  LIMIT_CLIPS="${LIMIT_CLIPS}" \
  SKIP_DONE="${SKIP_DONE}" \
  EXPORTED_MODEL="${EXPORTED_MODEL}" \
  OUTPUT_DIR="${OUTPUT_DIR}" \
  ENABLE_ATTR="${ENABLE_ATTR}" \
  ENABLE_CROSS_CLASS_MERGE_PRIOR="${ENABLE_CROSS_CLASS_MERGE_PRIOR}" \
  SHOW_DISTANCE_LABEL="${SHOW_DISTANCE_LABEL}" \
  DISTANCE_LABEL_MODE="${DISTANCE_LABEL_MODE}" \
  DISTANCE_LABEL_PANELS="${DISTANCE_LABEL_PANELS}" \
  EXTRA_ARGS="${EXTRA_ARGS}" \
  TRACK_ONLY="${TRACK_ONLY}" \
  CONVERT_ONLY="${CONVERT_ONLY}" \
  AUTO_TRACK="${AUTO_TRACK}" \
  TRACK_CLASSES="${TRACK_CLASSES}" \
  TRACK_IOU_THRESH="${TRACK_IOU_THRESH}" \
  TRACK_MAX_AGE="${TRACK_MAX_AGE}" \
  TRACK_MIN_HITS="${TRACK_MIN_HITS}" \
  TRACK_DIST_THRESH="${TRACK_DIST_THRESH}" \
  TRACK_MAX_3D_DISTANCE="${TRACK_MAX_3D_DISTANCE}" \
  TRACK_MODEL_VERSION="${TRACK_MODEL_VERSION}" \
  TRACK_FILE_PATTERN="${TRACK_FILE_PATTERN}" \
  TRACK_ENABLE_USE_3D="${TRACK_ENABLE_USE_3D}" \
  TRACK_MERGE_OUTPUT_NAME="${TRACK_MERGE_OUTPUT_NAME}" \
  TRACK_MANIFEST_NAME="${TRACK_MANIFEST_NAME}" \
  TRACK_EVENT_TRACKING_DIRNAME="${TRACK_EVENT_TRACKING_DIRNAME}" \
  ENABLE_CONVERT="${ENABLE_CONVERT}" \
  CONVERT_STRICT="${CONVERT_STRICT}" \
  CONVERT_RESULTS_ROOT="${CONVERT_RESULTS_ROOT}" \
  CONVERT_OUTPUT_ROOT="${CONVERT_OUTPUT_ROOT}" \
  CONVERT_OUTPUT_LAYOUT="${CONVERT_OUTPUT_LAYOUT}" \
  CONVERT_OUTPUT_DIR_NAME="${CONVERT_OUTPUT_DIR_NAME}" \
  CONVERT_MERGE_JSON_NAME="${CONVERT_MERGE_JSON_NAME}" \
  CONVERT_PARALLEL_JOBS="${CONVERT_PARALLEL_JOBS}" \
  CONVERT_CAM_ID="${CONVERT_CAM_ID}" \
  bash "${BASE_SCRIPT}" "$@"
