#!/usr/bin/env bash
set -euo pipefail
shopt -s nullglob

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
REPO_ROOT="$(cd "${SCRIPT_DIR}/../.." && pwd)"
PYTHON_BIN="${PYTHON_BIN:-/deeplearning_team/ydong/dongying/miniconda/envs/yolov5/bin/python}"

CASE_ROOT="${CASE_ROOT:-/data1/dongying/Mono3d/G1M3/pdcl_batch_infer/cases_aeb_v2}"

SCENE_FILTER="${SCENE_FILTER:-}"
TEST_FILTER="${TEST_FILTER:-}"
CASE_FILTER="${CASE_FILTER:-}"
DRY_RUN="${DRY_RUN:-0}"
STOP_ON_ERROR="${STOP_ON_ERROR:-0}"

FORWARD_ARGS=("$@")

run_one_case() {
    local scene_name="$1"
    local test_name="$2"
    local case_dir="$3"
    local case_name
    case_name="$(basename "$case_dir")"

    local cmd=(
        "$PYTHON_BIN"
        "tools/temporal_analysis/analyze_heading_debug.py"
        --input "$case_dir"
        "${FORWARD_ARGS[@]}"
    )

    printf '[RUN] %s / %s / %s\n' "$scene_name" "$test_name" "$case_name"

    if [[ "$DRY_RUN" == "1" ]]; then
        printf '      '
        printf '%q ' "${cmd[@]}"
        printf '\n'
        return 0
    fi

    (
        cd "$REPO_ROOT"
        "${cmd[@]}"
    )
}

if [[ ! -d "$CASE_ROOT" ]]; then
    echo "[ERROR] CASE_ROOT not found: $CASE_ROOT" >&2
    exit 1
fi

total=0
success=0
failed=0

for scene_dir in "$CASE_ROOT"/*; do
    [[ -d "$scene_dir" ]] || continue
    scene_name="$(basename "$scene_dir")"

    if [[ -n "$SCENE_FILTER" ]] && [[ ! "$scene_name" =~ $SCENE_FILTER ]]; then
        continue
    fi

    for test_dir in "$scene_dir"/*; do
        [[ -d "$test_dir" ]] || continue
        test_name="$(basename "$test_dir")"

        if [[ -n "$TEST_FILTER" ]] && [[ ! "$test_name" =~ $TEST_FILTER ]]; then
            continue
        fi

        found_case=0
        for case_dir in "$test_dir"/*; do
            [[ -d "$case_dir" ]] || continue
            case_name="$(basename "$case_dir")"

            if [[ -n "$CASE_FILTER" ]] && [[ ! "$case_name" =~ $CASE_FILTER ]]; then
                continue
            fi

            found_case=1
            ((total+=1))

            if run_one_case "$scene_name" "$test_name" "$case_dir"; then
                ((success+=1))
            else
                ((failed+=1))
                printf '[FAIL] %s / %s / %s\n' \
                    "$scene_name" "$test_name" "$case_name" >&2
                if [[ "$STOP_ON_ERROR" == "1" ]]; then
                    exit 1
                fi
            fi
        done

        if [[ "$found_case" == "0" ]]; then
            printf '[SKIP] empty test dir: %s / %s\n' "$scene_name" "$test_name"
        fi
    done
done

printf '\n[DONE] total=%d success=%d failed=%d\n' "$total" "$success" "$failed"

if [[ "$failed" -gt 0 ]]; then
    exit 1
fi
