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

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

RESULTS_ROOT=${RESULTS_ROOT:-/data1/dongying/Mono3d/G1Q3/feishu_project/inference_issue_data}
OUTPUT_DIR_NAME=${OUTPUT_DIR_NAME:-objectlist}
PYTHON_BIN=${PYTHON_BIN:-/deeplearning_team/ydong/dongying/miniconda/envs/dev/bin/python}
CONVERT_LAUNCHER=${CONVERT_LAUNCHER:-"${PROJECT_ROOT}/tools/convert_merge_tracking_bundle/convert_merge_tracking_exported_onnx_infer_case.sh"}
MERGE_JSON_NAME=${MERGE_JSON_NAME:-merge.json}
CAM_ID=${CAM_ID:-}

TARGET_PATH=""
ISSUE_IDS=()

while (($# > 0)); do
  case "$1" in
    --issue-id)
      if (($# < 2)); then
        echo "Error: --issue-id requires a value" >&2
        exit 1
      fi
      ISSUE_IDS+=("$2")
      shift 2
      ;;
    --issue-id=*)
      ISSUE_IDS+=("${1#*=}")
      shift
      ;;
    -*)
      echo "Error: unsupported option: $1" >&2
      exit 1
      ;;
    *)
      if [[ -n "${TARGET_PATH}" ]]; then
        echo "Error: multiple target paths provided: ${TARGET_PATH} and $1" >&2
        exit 1
      fi
      TARGET_PATH="$1"
      shift
      ;;
  esac
done

if [[ -z "${TARGET_PATH}" ]]; then
  TARGET_PATH="${RESULTS_ROOT}"
fi

if [[ ! -e "${TARGET_PATH}" ]]; then
  echo "Error: target path does not exist: ${TARGET_PATH}" >&2
  exit 1
fi

is_case_dir() {
  local dir_path="$1"
  [[ -d "${dir_path}" ]] && [[ -f "${dir_path}/${MERGE_JSON_NAME}" ]]
}

is_predictions_dir() {
  local dir_path="$1"
  [[ -d "${dir_path}" ]] || return 1
  is_case_dir "$(dirname "${dir_path}")"
}

resolve_case_dir() {
  local target_path="$1"

  if is_case_dir "${target_path}"; then
    printf '%s\n' "${target_path}"
    return 0
  fi

  if is_predictions_dir "${target_path}"; then
    dirname "${target_path}"
    return 0
  fi

  if [[ -f "${target_path}" ]] && [[ "$(basename "${target_path}")" == "${MERGE_JSON_NAME}" ]]; then
    dirname "${target_path}"
    return 0
  fi

  return 1
}

case_output_dir() {
  local case_dir="$1"
  printf '%s/%s\n' "${case_dir%/}" "${OUTPUT_DIR_NAME}"
}

run_convert_case() {
  local case_dir="$1"
  local output_path

  output_path="$(case_output_dir "${case_dir}")"

  echo ""
  echo "######################################################################"
  echo "# Feishu issue-data protocol conversion"
  echo "######################################################################"
  echo "Case dir     : ${case_dir}"
  echo "Tracking JSON: ${case_dir%/}/${MERGE_JSON_NAME}"
  echo "Output path  : ${output_path}"
  if [[ -n "${CAM_ID}" ]]; then
    echo "Camera ID override: ${CAM_ID}"
  fi

  PYTHON_BIN="${PYTHON_BIN}" \
    MERGE_JSON_NAME="${MERGE_JSON_NAME}" \
    CAM_ID="${CAM_ID}" \
    bash "${CONVERT_LAUNCHER}" "${case_dir}" "${output_path}"
}

run_convert_root() {
  local target_root="$1"
  local total_cases=0
  local success_cases=0
  local failed_cases=0

  echo ""
  echo "Batch-root mode: ${target_root}"

  while IFS= read -r -d '' merge_json_path; do
    local case_dir
    case_dir="$(dirname "${merge_json_path}")"
    ((total_cases += 1))

    if run_convert_case "${case_dir}"; then
      ((success_cases += 1))
    else
      ((failed_cases += 1))
      printf '[FAIL] case=%s\n' "${case_dir}" >&2
    fi
  done < <(
    find "${target_root}" -type f -name "${MERGE_JSON_NAME}" -print0 | sort -z
  )

  if [[ "${total_cases}" -eq 0 ]]; then
    echo "[ERROR] No ${MERGE_JSON_NAME} files were found under: ${target_root}" >&2
    return 1
  fi

  echo ""
  printf '[DONE] cases=%d success=%d failed=%d\n' \
    "${total_cases}" "${success_cases}" "${failed_cases}"

  [[ "${failed_cases}" -eq 0 ]]
}

if [[ "${#ISSUE_IDS[@]}" -eq 0 ]]; then
  if RESOLVED_CASE_DIR="$(resolve_case_dir "${TARGET_PATH}")"; then
    run_convert_case "${RESOLVED_CASE_DIR}"
  else
    run_convert_root "${TARGET_PATH}"
  fi
  exit 0
fi

total_issues=0
success_issues=0
failed_issues=0

for issue_id in "${ISSUE_IDS[@]}"; do
  issue_root="${TARGET_PATH}/issue_${issue_id}"
  ((total_issues += 1))

  if [[ ! -d "${issue_root}" ]]; then
    echo "[FAIL] issue_${issue_id}: not found under ${TARGET_PATH}" >&2
    ((failed_issues += 1))
    continue
  fi

  if run_convert_root "${issue_root}"; then
    ((success_issues += 1))
  else
    ((failed_issues += 1))
    echo "[FAIL] issue_${issue_id}: protocol conversion failed" >&2
  fi
done

echo ""
printf '[DONE] issues=%d success=%d failed=%d\n' \
  "${total_issues}" "${success_issues}" "${failed_issues}"

[[ "${failed_issues}" -eq 0 ]]
