#!/bin/bash

RUNS=100
PROB_FILE="prob_results.txt"
#PROB_FILE2="prob_results2.txt"
GENETIC_FILE="genetic_results.txt"
GENETIC_FILE2="genetic_results_ensemble.txt"

run_simulation() {
    local script=$1
    local output_file=$2
    local name=$3

    echo "Running $name simulation..."
    for ((i=1; i<=$RUNS; i++))
    do
        if [ "$name" == "Genetic Algorithm" ]; then
            python3 $script sample >> $output_file
        elif [ "$name" == "Genetic Algorithm Ensemble" ]; then
            python3 $script sample_ensemble >> $output_file
        else
            python3 $script >> $output_file
        fi
        echo -ne "Progress: $i/$RUNS\r"
    done
    echo
}

calculate_stats() {
    local file=$1
    local name=$2

    TOTAL=$(awk '{sum+=$1} END {print sum}' $file)
    COUNT=$(wc -l < $file)
    MIN=$(sort -n $file | head -n1)
    MAX=$(sort -n $file | tail -n1)
    AVG=$(echo "scale=2; $TOTAL / $COUNT" | bc)

    echo "$name Results after $RUNS runs:"
    echo "Min turns: $MIN"
    echo "Max turns: $MAX"
    echo "Average turns: $AVG"
    echo
}

# Run probability grid simulation
run_simulation "battleship_prob.py" $PROB_FILE "Probability Grid"

# Run probability grid simulation
#run_simulation "battleship_prob2.py" $PROB_FILE2 "Probability Grid 2"

# Run genetic algorithm simulation
run_simulation "battleship_genetic.py" $GENETIC_FILE "Genetic Algorithm"

# Run genetic algorithm simulation
# temporarily commented out because the single top elite often works better...
#run_simulation "battleship_genetic.py" $GENETIC_FILE2 "Genetic Algorithm Ensemble"

# Calculate and display statistics
calculate_stats $PROB_FILE "Probability Grid"
#calculate_stats $PROB_FILE2 "Probability Grid 2"
calculate_stats $GENETIC_FILE "Genetic Algorithm"
#calculate_stats $GENETIC_FILE2 "Genetic Algorithm Ensemble"

# Clean up
#rm $PROB_FILE $PROB_FILE2 $GENETIC_FILE $GENETIC_FILE2
rm $PROB_FILE $GENETIC_FILE
