#!/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 flags ─────────────────────────────────────────────────────────
USE_VIDEO=false
USE_AUDIO=false
USE_FLOW=false
USE_PID=true         # PID is ON by default; pass --no-pid to turn it off

# ── 3. Parse arguments ────────────────────────────────────────────────────────
while [[ "$#" -gt 0 ]]; do
    case $1 in
        --video)  USE_VIDEO=true ;;
        --audio)  USE_AUDIO=true ;;
        --flow)   USE_FLOW=true  ;;
        --no-pid) USE_PID=false  ;;
        *) echo "❌ Unknown parameter: $1"; exit 1 ;;
    esac
    shift
done

# ── 4. Safety check ───────────────────────────────────────────────────────────
if [ "$USE_VIDEO" = false ] && [ "$USE_AUDIO" = false ] && [ "$USE_FLOW" = false ]; then
    echo "❌ Error: select at least one modality (--video / --audio / --flow)"
    echo "   Usage: $0 [--video] [--audio] [--flow] [--no-pid]"
    exit 1
fi

# ── 5. Build Python flag strings ──────────────────────────────────────────────
MODALITY_ARGS=""
MODALITY_SUFFIX=""

[ "$USE_VIDEO" = true ] && { MODALITY_ARGS="$MODALITY_ARGS --use_video"; MODALITY_SUFFIX="${MODALITY_SUFFIX}_video"; }
[ "$USE_AUDIO" = true ] && { MODALITY_ARGS="$MODALITY_ARGS --use_audio"; MODALITY_SUFFIX="${MODALITY_SUFFIX}_audio"; }
[ "$USE_FLOW"  = true ] && { MODALITY_ARGS="$MODALITY_ARGS --use_flow";  MODALITY_SUFFIX="${MODALITY_SUFFIX}_flow";  }

PID_ARGS=""
PID_SUFFIX=""
if [ "$USE_PID" = true ]; then
    PID_ARGS="--use_pid \
              --alpha_pid 0.7 \
              --alpha_pid_shared 1.0 \
              --alpha_pid_unique 1.0 \
              --pid_gamma 0.5 \
              --pid_proj_dim 6 \
              --pid_warmup_epochs 3"
    PID_SUFFIX="_pid"
fi

FULL_SUFFIX="${MODALITY_SUFFIX}${PID_SUFFIX}"

# ── 6. Base command ───────────────────────────────────────────────────────────
BASE_CMD="python train_HAC_fast_test.py \
    --datapath ./data/ \
    --bsz 16 \
    --nepochs 15 \
    --lr 1e-4 \
    --alpha_contrast 3.0 \
    --alpha_trans 0.1 \
    --explore_loss_coeff 0.7 \
    --temp 0.1 \
    --save_best \
    --seed 42 \
    $MODALITY_ARGS \
    $PID_ARGS"

# ── 7. Helper: run one experiment (Background or Sequential) ──────────────────
run_experiment() {
    local SOURCES="$1"   # e.g. "human animal"
    local TARGET="$2"    # e.g. "cartoon"
    local LOGFILE="log_target_${TARGET}${FULL_SUFFIX}.txt"

    echo ""
    echo "======================================================"
    echo " Starting: sources=[${SOURCES}]  target=[${TARGET}]"
    echo " Log: ${LOGFILE}"
    echo " PID: ${USE_PID}"
    echo "======================================================"

    # Build -s / -t arguments from the strings
    SOURCE_ARGS=""
    for s in $SOURCES; do SOURCE_ARGS="$SOURCE_ARGS $s"; done

    $BASE_CMD -s $SOURCES -t $TARGET > "$LOGFILE" 2>&1
    local EXIT_CODE=$?

    if [ $EXIT_CODE -ne 0 ]; then
        echo "❌ FAILED (exit $EXIT_CODE): target=${TARGET} — check ${LOGFILE}"
        return $EXIT_CODE
    fi

    echo "✅ Done: target=${TARGET}  (see ${LOGFILE})"
    return 0
}

# ── 8. Run all three targets (2 Parallel, Last Sequential) ────────────────────
echo ""
echo "██████████████████████████████████████████████████████"
echo "  HAC Multi-Modal DG — Parallel + Sequential Mode"
echo "  Modalities: ${MODALITY_SUFFIX}"
echo "  PID loss:   ${USE_PID}"
echo "██████████████████████████████████████████████████████"

# --- PART 1: Run the first two domains in parallel ---
echo "🚀 launching first 2 domains in parallel..."
run_experiment "human animal" "cartoon" &
PID1=$!

run_experiment "human cartoon" "animal" &
PID2=$!

# Wait for both background experiments to finish before continuing
echo "⏳ Waiting for parallel runs to finish..."
wait $PID1
EXIT_1=$?
wait $PID2
EXIT_2=$?

# Verify both background tasks succeeded before processing the final sequential domain
if [ $EXIT_1 -ne 0 ] || [ $EXIT_2 -ne 0 ]; then
    echo "❌ Execution halted: One or both parallel tasks failed."
    exit 1
fi

# --- PART 2: Run the final domain sequentially ---
echo "🏃 Proceeding to the final sequential run..."
run_experiment "animal cartoon" "human"
EXIT_3=$?

if [ $EXIT_3 -ne 0 ]; then
    exit $EXIT_3
fi

# ── 9. Aggregate results ──────────────────────────────────────────────────────
echo ""
echo "======================================================"
echo " ALL EXPERIMENTS COMPLETE"
echo " Modalities: ${MODALITY_SUFFIX}  |  PID: ${USE_PID}"
echo "======================================================"
echo ""
echo "Best test accuracies (grep from logs):"
for TARGET in cartoon animal human; do
    LOGFILE="log_target_${TARGET}${FULL_SUFFIX}.txt"
    if [ -f "$LOGFILE" ]; then
        # Pull the last BestTestAcc line written by the training script
        BEST=$(grep "BestTestAcc" "$LOGFILE" | tail -1)
        echo "  target=${TARGET}: ${BEST}"
    fi
done
echo ""
echo "CSV logs saved in checkpoints/  |  Models saved in models/"
echo "Log files: log_target_*${FULL_SUFFIX}.txt"