#!/bin/bash

# Performance comparison script for AsyncIO vs ProcessPool approaches

TEST_FILE="${1:-documents/BHE_991.pdf}"
OUTPUT_BASE="output_test"

echo "================================"
echo "GPU Utilization Performance Test"
echo "Test file: $TEST_FILE"
echo "================================"

# Function to run test with monitoring
run_test() {
    local test_name=$1
    local command=$2
    local workers=$3
    local output_dir="${OUTPUT_BASE}_${test_name}"

    echo ""
    echo "Running: $test_name (workers=$workers)"
    echo "--------------------------------"

    # Clean output directory
    rm -rf "$output_dir"
    mkdir -p "$output_dir"

    # Start GPU monitoring in background
    ./monitor_gpu.sh "gpu_metrics_${test_name}.log" &
    MONITOR_PID=$!

    # Run the conversion and time it
    START_TIME=$(date +%s)
    eval "$command"
    END_TIME=$(date +%s)
    DURATION=$((END_TIME - START_TIME))

    # Stop monitoring
    kill $MONITOR_PID 2>/dev/null

    # Analyze GPU metrics
    echo "Duration: ${DURATION} seconds"
    if [ -f "gpu_metrics_${test_name}.log" ]; then
        echo -n "Avg GPU Utilization: "
        awk -F', ' 'NR>1 {sum+=$4; count++} END {if (count>0) printf "%.1f%%\n", sum/count}' "gpu_metrics_${test_name}.log"
        echo -n "Peak GPU Utilization: "
        awk -F', ' 'NR>1 {if ($4>max) max=$4} END {printf "%.0f%%\n", max}' "gpu_metrics_${test_name}.log"
        echo -n "Avg Memory Usage: "
        awk -F', ' 'NR>1 {sum+=$5; count++} END {if (count>0) printf "%.1f%%\n", sum/count}' "gpu_metrics_${test_name}.log"
        echo -n "Avg Power Draw: "
        awk -F', ' 'NR>1 {sum+=$2; count++} END {if (count>0) printf "%.0fW\n", sum/count}' "gpu_metrics_${test_name}.log"
    fi
}

# Test 1: AsyncIO with 1 worker
run_test "async_1w" "uv run python page_converter_v3.py $TEST_FILE --output-dir ${OUTPUT_BASE}_async_1w --concurrent 1" 1

# Test 2: AsyncIO with 4 workers
run_test "async_4w" "uv run python page_converter_v3.py $TEST_FILE --output-dir ${OUTPUT_BASE}_async_4w --concurrent 4" 4

# Test 3: ProcessPool with 1 worker
run_test "process_1w" "uv run python page_converter_process.py $TEST_FILE --output-dir ${OUTPUT_BASE}_process_1w --workers 1" 1

# Test 4: ProcessPool with 2 workers
run_test "process_2w" "uv run python page_converter_process.py $TEST_FILE --output-dir ${OUTPUT_BASE}_process_2w --workers 2" 2

# Test 5: ProcessPool with 4 workers
run_test "process_4w" "uv run python page_converter_process.py $TEST_FILE --output-dir ${OUTPUT_BASE}_process_4w --workers 4" 4

echo ""
echo "================================"
echo "Test Complete!"
echo "GPU metrics saved to gpu_metrics_*.log files"
echo "================================"
