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

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

LIST_DIR=${LIST_DIR:-/mnt/mono3d/ydong_data/D01_group_list}
LIST_PATTERN=${LIST_PATTERN:-*.txt}
OUTPUT_ROOT=${OUTPUT_ROOT:-/mnt/mono3d/ydong_data/Mono3d_camera2_gt_by_group_id}
NUM_WORKERS=${NUM_WORKERS:-32}
PRODUCT_TYPE=${PRODUCT_TYPE:-2d-3d-association}
CAMERA_ID=${CAMERA_ID:-camera2}
IMAGE_SUFFIX=${IMAGE_SUFFIX:-jpg}
ANNOTATION_STRIDE=${ANNOTATION_STRIDE:-2}
SKIP_IMAGES=${SKIP_IMAGES:-0}
PYTHON_BIN=${PYTHON_BIN:-python}
LOG_DIR=${LOG_DIR:-${OUTPUT_ROOT}/_logs/extract_gt_by_group_id}

if [[ ! -d "${LIST_DIR}" ]]; then
    echo "[ERROR] LIST_DIR 不存在: ${LIST_DIR}" >&2
    exit 1
fi

mkdir -p "${OUTPUT_ROOT}" "${LOG_DIR}"

mapfile -t LIST_FILES < <(find "${LIST_DIR}" -maxdepth 1 -type f -name "${LIST_PATTERN}" | sort)

if [[ ${#LIST_FILES[@]} -eq 0 ]]; then
    echo "[ERROR] 在 ${LIST_DIR} 下未找到匹配 ${LIST_PATTERN} 的列表文件" >&2
    exit 1
fi

RUN_TAG=$(date +%Y%m%d_%H%M%S)
MERGED_UUID_FILE="${LOG_DIR}/merged_group_list_${RUN_TAG}.txt"
RUN_LOG="${LOG_DIR}/extract_gt_by_group_id_${RUN_TAG}.log"

awk 'NF && $1 !~ /^#/ && !seen[$1]++ { print }' "${LIST_FILES[@]}" > "${MERGED_UUID_FILE}"

TOTAL_LISTS=${#LIST_FILES[@]}
TOTAL_GROUPS=$(wc -l < "${MERGED_UUID_FILE}")

echo "[INFO] list 文件数: ${TOTAL_LISTS}"
echo "[INFO] 合并后 group 数: ${TOTAL_GROUPS}"
echo "[INFO] workers: ${NUM_WORKERS}"
echo "[INFO] image suffix: ${IMAGE_SUFFIX}"
echo "[INFO] annotation stride: ${ANNOTATION_STRIDE}"
echo "[INFO] skip images: ${SKIP_IMAGES}"
echo "[INFO] merged uuid file: ${MERGED_UUID_FILE}"
echo "[INFO] run log: ${RUN_LOG}"

PY_ARGS=()
if [[ "${SKIP_IMAGES}" == "1" ]]; then
    PY_ARGS+=(--skip_images)
fi

"${PYTHON_BIN}" "${PROJECT_ROOT}/tools/pdcl_inference/extract_gt_by_group_id.py" \
    --uuid_file "${MERGED_UUID_FILE}" \
    --output "${OUTPUT_ROOT}" \
    --product_type "${PRODUCT_TYPE}" \
    --camera_id "${CAMERA_ID}" \
    --image_suffix "${IMAGE_SUFFIX}" \
    --annotation_stride "${ANNOTATION_STRIDE}" \
    --workers "${NUM_WORKERS}" \
    "${PY_ARGS[@]}" | tee "${RUN_LOG}"
