#!/bin/bash

# 1. Prevent CPU thread deadlocks
export OMP_NUM_THREADS=1
export MKL_NUM_THREADS=1
export OPENBLAS_NUM_THREADS=1
export cv2_NUM_THREADS=0

# 2. Default settings (Everything off until flags are passed)
USE_VIDEO=false
USE_AUDIO=false
USE_FLOW=false

# 3. Parse command-line arguments to toggle modalities
while [[ "$#" -gt 0 ]]; do
    case $1 in
        --video) USE_VIDEO=true ;;
        --audio) USE_AUDIO=true ;;
        --flow)  USE_FLOW=true ;;
        *) echo "Unknown parameter passed: $1"; exit 1 ;;
    esac
    shift
done

# 4. Build Python arguments and log name suffix dynamically
MODALITY_ARGS=""
MODALITY_SUFFIX=""

if [ "$USE_VIDEO" = true ]; then
    MODALITY_ARGS="$MODALITY_ARGS --use_video"
    MODALITY_SUFFIX="${MODALITY_SUFFIX}_video"
fi

if [ "$USE_AUDIO" = true ]; then
    MODALITY_ARGS="$MODALITY_ARGS --use_audio"
    MODALITY_SUFFIX="${MODALITY_SUFFIX}_audio"
fi

if [ "$USE_FLOW" = true ]; then
    MODALITY_ARGS="$MODALITY_ARGS --use_flow"
    MODALITY_SUFFIX="${MODALITY_SUFFIX}_flow"
fi

# Safety check: Enforce that at least one modality is selected
if [ -z "$MODALITY_ARGS" ]; then
    echo "❌ Error: You must select at least one modality!"
    echo "Usage: $0 [--video] [--audio] [--flow]"
    exit 1
fi

# 5. Base command setup (Notice $MODALITY_ARGS is appended)
BASE_CMD="python train_HAC_fast_CMRF.py --datapath ./data/ --bsz 16 --save_best --seed 42 $MODALITY_ARGS"

# ==========================================
# Launching Experiments 1 & 2 in PARALLEL
# ==========================================
echo "Launching Experiment 1 (Target: Cartoon)..."
$BASE_CMD -s human animal -t cartoon > "log_target_cartoon${MODALITY_SUFFIX}.txt" 2>&1 &

echo "Launching Experiment 2 (Target: Animal)..."
$BASE_CMD -s human cartoon -t animal > "log_target_animal${MODALITY_SUFFIX}.txt" 2>&1 &

# This tells the script to pause and wait for the two background jobs above to finish
echo "Waiting for Cartoon and Animal to finish before starting Human..."
wait 

# ==========================================
# Launching Experiment 3 SEQUENTIALLY
# ==========================================
echo "Launching Experiment 3 (Target: Human)..."
# Notice there is NO '&' at the end of this line, so the script waits for it to finish naturally
$BASE_CMD -s animal cartoon -t human > "log_target_human${MODALITY_SUFFIX}.txt" 2>&1

echo "======================================================"
echo "SUCCESS: All experiments have finished safely!"
echo "Outputs saved to logs with suffix: *${MODALITY_SUFFIX}.txt"
echo "======================================================"