#!/bin/bash
# Batch run joint formula CFD on all illusion generalization scenes
# Usage: bash batch_illusion_generalization.sh

cd /home/frank14f/DynamisLab
RESULT_DIR="src/SR_analysis/validate/results"
FRONT_JSON="src/SR_analysis/validate/results/pysr_illusion_joint_front.json"
TOP_JSON="src/SR_analysis/validate/results/pysr_illusion_joint_top.json"
LOGFILE="src/SR_analysis/validate/results/generalization_results.json"

# scenes: name, steps
SCENES=(
    "illusion_0.5L 320"
    "illusion_0.6L 320"
    "illusion_0.8L 214"
    "illusion_1.2L 214"
    "illusion_2L 160"
)

RESULTS=()
TOTAL=${#SCENES[@]}
i=0

for scene_line in "${SCENES[@]}"; do
    read -r name steps <<< "$scene_line"
    i=$((i+1))
    echo "[$i/$TOTAL] Running $name (steps=$steps)..."

    OUTPUT=$(conda run -n pycuda_3_10 python -u src/SR_analysis/validate/run_closed_loop_illusion.py \
        --scene "$name" --device 2 --steps "$steps" --mode pysr \
        --pysr-front "$FRONT_JSON" \
        --pysr-top "$TOP_JSON" \
        --out "$RESULT_DIR" 2>&1)
    
    # Extract similarity from output
    SIM=$(echo "$OUTPUT" | grep "similarity" | tail -1 | grep -oP '[\d.]+' | head -1)
    ACT_RANGE=$(echo "$OUTPUT" | grep "action_range" | tail -1 | grep -oP '[\d.]+' | head -1)
    
    echo "  Result: similarity=$SIM, action_range=$ACT_RANGE"
    
    RESULTS+=("{\"scene\":\"$name\",\"similarity\":$SIM,\"action_range\":$ACT_RANGE}")
done

# Save summary
echo "[" > "$LOGFILE"
for j in "${!RESULTS[@]}"; do
    if [ $j -eq $((${#RESULTS[@]} - 1)) ]; then
        echo "${RESULTS[$j]}" >> "$LOGFILE"
    else
        echo "${RESULTS[$j]}," >> "$LOGFILE"
    fi
done
echo "]" >> "$LOGFILE"
echo "Summary saved to $LOGFILE"
echo "Done."
