#!/bin/bash
# Batch inference over all cases in a mined eval dataset directory.
#
# Directory layout expected (produced by mine_balanced_eval_subset.py):
#   EVAL_DIR/<date>/<case_uuid>/images/
#   EVAL_DIR/<date>/<case_uuid>/calib/L2_calib/camera4.json
#
# Output mirrors the same structure under OUTPUT_DIR:
#   OUTPUT_DIR/<date>/<case_uuid>/visualizations/
#   OUTPUT_DIR/<date>/<case_uuid>/predictions/
#   OUTPUT_DIR/<date>/<case_uuid>/predictions.json
#
# Usage:
#   bash tools/model_inference/scripts/run_evalset_infer.sh
#
# Override defaults with environment variables:
#   EVAL_DIR=... EXPORTED_MODEL=... OUTPUT_DIR=... bash tools/model_inference/scripts/run_evalset_infer.sh

set -euo pipefail

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

PYTHON_BIN="${PYTHON_BIN:-/deeplearning_team/ydong/dongying/miniconda/envs/dev/bin/python}"
EVAL_DIR="${EVAL_DIR:-/data1/dongying/Mono3d/G1M3/data_for_alignment/mono3d_mining_val300}"
EXPORTED_MODEL="${EXPORTED_MODEL:-${PROJECT_ROOT}/runs/export/train_mono3d_two_roi_202603291430-raw-fuse/merged_model.torchscript}"
OUTPUT_DIR="${OUTPUT_DIR:-${PROJECT_ROOT}/runs/test/evalset_infer_$(basename "${EVAL_DIR}")_new}"
ENABLE_ATTR="${ENABLE_ATTR:-1}"
ENABLE_CROSS_CLASS_MERGE_PRIOR="${ENABLE_CROSS_CLASS_MERGE_PRIOR:-0}"
ENABLE_VRU_MERGE="${ENABLE_VRU_MERGE:-1}"

if [[ ! -d "${EVAL_DIR}" ]]; then
    echo "ERROR: EVAL_DIR does not exist: ${EVAL_DIR}" >&2
    exit 1
fi

if [[ ! -f "${EXPORTED_MODEL}" ]]; then
    echo "ERROR: EXPORTED_MODEL does not exist: ${EXPORTED_MODEL}" >&2
    exit 1
fi

echo "Eval dir: ${EVAL_DIR}"
echo "Model   : ${EXPORTED_MODEL}"
echo "Output  : ${OUTPUT_DIR}"
echo ""

CMD=(
    "${PYTHON_BIN}" "${MODEL_INFERENCE_DIR}/core/run_two_roi_exported_onnx_infer.py"
    --eval-dir "${EVAL_DIR}"
    --exported-model "${EXPORTED_MODEL}"
    --output-dir "${OUTPUT_DIR}"
)

if [[ "${ENABLE_ATTR}" == "1" ]]; then
    CMD+=(--enable-attr)
fi

if [[ "${ENABLE_CROSS_CLASS_MERGE_PRIOR}" == "1" ]]; then
    CMD+=(--enable-cross-class-merge-prior)
fi

if [[ "${ENABLE_VRU_MERGE}" == "1" ]]; then
    CMD+=(--enable-vru-merge)
fi

"${CMD[@]}"
