#!/bin/bash
# 用法说明：
#   分析原始逐帧检测结果与跟踪结果之间是否存在检测框丢失。
#
#   默认对每个 case 的三路输入分别分析：
#     ROI0:       {case_dir}/roi0/        ↔  {case_dir}/roi0.json
#     ROI1:       {case_dir}/roi1/        ↔  {case_dir}/roi1.json
#     Merge:      {case_dir}/merge_json/  ↔  {case_dir}/merge.json
#
#   输出报告：
#     {case_dir}/roi0_loss_report.json
#     {case_dir}/roi1_loss_report.json
#     {case_dir}/merge_loss_report.json
#
# 支持两种模式：
#   1) 批量模式（默认）：处理 RESULTS_ROOT/MODEL_NAME 下所有 case
#        bash analyze_tracking_loss.sh
#   2) 单 case 模式：指定 case 目录路径作为第一个参数
#        bash analyze_tracking_loss.sh /path/to/case

set -u

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

# -----------------------------------------------------------------------
# 配置区：与 track_objects.sh 保持一致
# -----------------------------------------------------------------------
RESULTS_ROOT="/data1/dongying/Mono3d/G1M3/cases_regular"
MODEL_NAME="model_20260228"

TOP_K_FRAMES=20
TOP_K_SAMPLES=200
RAW_FILE_PATTERN="*.json"

analyze_one_source() {
    local case_dir="$1"
    local raw_subdir="$2"
    local tracking_name="$3"
    local report_name="$4"
    local source_label="$5"

    local raw_dir="${case_dir}/${raw_subdir}"
    local tracking_json="${case_dir}/${tracking_name}"
    local report_json="${case_dir}/${report_name}"

    if [[ ! -d "${raw_dir}" ]]; then
        echo "Warning: raw directory not found, skipping ${source_label}: ${raw_dir}"
        return 0
    fi
    if [[ ! -f "${tracking_json}" ]]; then
        echo "Warning: tracking json not found, skipping ${source_label}: ${tracking_json}"
        return 0
    fi

    echo ""
    echo "--- Analyze ${source_label} ---"
    python3 "${PROJECT_ROOT}/tools/temporal_analysis/analyze_tracking_loss.py" \
        --raw-dir "${raw_dir}" \
        --tracking "${tracking_json}" \
        --output "${report_json}" \
        --file-pattern "${RAW_FILE_PATTERN}" \
        --top-k-frames "${TOP_K_FRAMES}" \
        --top-k-samples "${TOP_K_SAMPLES}"
}

analyze_one_case() {
    local case_dir="$1"

    if [[ ! -d "${case_dir}" ]]; then
        echo "Error: case directory does not exist: ${case_dir}"
        return 1
    fi

    echo ""
    echo "======================================================================"
    echo "Analyze tracking loss: ${case_dir}"
    echo "======================================================================"

    analyze_one_source "${case_dir}" "roi0" "roi0.json" "roi0_loss_report.json" "roi0"
    analyze_one_source "${case_dir}" "roi1" "roi1.json" "roi1_loss_report.json" "roi1"
    analyze_one_source "${case_dir}" "merge_json" "merge.json" "merge_loss_report.json" "merge"
}

echo ""
echo "######################################################################"
echo "# Analyze detection loss between raw per-frame JSON and tracking JSON"
echo "######################################################################"

if [[ -n "${1:-}" ]]; then
    CASE_DIR="$1"
    echo "Single-case mode: ${CASE_DIR}"
    analyze_one_case "${CASE_DIR}"
    exit $?
fi

MODEL_DIR="${RESULTS_ROOT}/${MODEL_NAME}"
if [[ ! -d "${MODEL_DIR}" ]]; then
    echo "Error: model directory not found: ${MODEL_DIR}"
    exit 1
fi

mapfile -t CASE_DIRS < <(find "${MODEL_DIR}" -mindepth 1 -maxdepth 1 -type d | sort)

if [[ ${#CASE_DIRS[@]} -eq 0 ]]; then
    echo "Warning: no case directories found under ${MODEL_DIR}"
    exit 0
fi

echo "Batch mode: found ${#CASE_DIRS[@]} case(s) under ${MODEL_DIR}"

for case_dir in "${CASE_DIRS[@]}"; do
    analyze_one_case "${case_dir}" || exit 1
done

echo ""
echo "Tracking loss analysis complete."
