#!/usr/bin/env bash
# ─────────────────────────────────────────────────────────────────────────────
# Calibration Parameter Profiling Launch Script
#
# Usage:
#   bash run_calib_profiling.sh [train|val|both]
#
#   Positional arg (optional): split — defaults to "train"
#
# To also profile test-case directories and compare with training data, set
# CASES_DIRS below (space-separated "name:path" pairs) or export the variable
# before running this script:
#
#   CASES_DIRS="cases_coding:/data1/dongying/Mono3d/G1M3/cases_coding cases_feishu:/data1/dongying/Mono3d/G1M3/cases_feishu" \
#     bash run_calib_profiling.sh train
#
# Outputs all plots and reports to $OUTPUT_DIR.
# ─────────────────────────────────────────────────────────────────────────────

set -euo pipefail

# ── User-configurable parameters ─────────────────────────────────────────────

# Path to dataset YAML config
DATA="data/mono3d.yaml"

# Which split(s) to profile: train | val | both
SPLIT="${1:-train}"

# Max image files to scan (0 = all — calib is deduplicated per sequence dir)
MAX_FILES=0

# Output directory for plots and reports
OUTPUT_DIR="calib_profiling_results"

# Number of parallel workers (0 = auto-detect CPU count, 1 = sequential)
WORKERS=0

# Test-case directories to profile alongside the training/val split.
# All directories are merged into a single combined profile named $CASES_NAME.
# Format: space-separated "name:path" pairs.  Set to "" to skip.
# Example:
#   CASES_DIRS="cases_coding:/data1/dongying/Mono3d/G1M3/cases_coding cases_feishu:/data1/dongying/Mono3d/G1M3/cases_feishu"
CASES_DIRS="${CASES_DIRS:-cases_coding:/data1/dongying/Mono3d/G1M3/cases_coding cases_feishu:/data1/dongying/Mono3d/G1M3/cases_feishu}"

# Label used for the merged test-cases profile in plots and output filenames
CASES_NAME="${CASES_NAME:-cases}"

# ── Derived paths ─────────────────────────────────────────────────────────────
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
REPO_ROOT="$(cd "$SCRIPT_DIR/../../.." && pwd)"

cd "$REPO_ROOT"

echo "=========================================="
echo "  Calibration Profiling"
echo "  data      : $DATA"
echo "  split     : $SPLIT"
echo "  cases_dirs: $CASES_DIRS"
echo "  cases_name: $CASES_NAME"
echo "  output    : $OUTPUT_DIR"
echo "=========================================="

# Build optional --cases-dirs / --cases-name arguments
CASES_ARGS=()
if [[ -n "${CASES_DIRS}" ]]; then
    # shellcheck disable=SC2206
    CASES_ARGS=(--cases-dirs ${CASES_DIRS} --cases-name "${CASES_NAME}")
fi

python tools/scripts_for_gt/profiling/calib_profiling.py \
    --data       "$DATA"       \
    --split      "$SPLIT"      \
    --max-files  "$MAX_FILES"  \
    --output-dir "$OUTPUT_DIR" \
    --workers    "$WORKERS"    \
    "${CASES_ARGS[@]}"
