#!/bin/bash

# Throughput test for Wasot random generation
# This script establishes a baseline and tests current performance

set -e

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"

# Configuration
TEST_EVENTS=1000000  # 1M events for quick but meaningful test
OUTPUT_FILE="/tmp/wasot_throughput_test.wasot"
BASELINE_FILE="$PROJECT_ROOT/.throughput_baseline"

# Colors
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m'

echo "🚀 Wasot Throughput Test"
echo "======================="

# Build in release mode
echo "Building in release mode..."
cargo build --release --bin wasot --quiet

# Function to measure throughput
measure_throughput() {
    local events=$1
    local output=$2
    
    # Clean up any existing file
    rm -f "$output"
    
    # Run with time measurement
    local start_time=$(date +%s.%N)
    "$PROJECT_ROOT/target/release/wasot" random -n "$events" -o "$output" >/dev/null 2>&1
    local end_time=$(date +%s.%N)
    
    # Calculate metrics
    local duration=$(echo "$end_time - $start_time" | bc)
    local file_size_bytes=$(stat -c%s "$output" 2>/dev/null || stat -f%z "$output" 2>/dev/null)
    local throughput_mb_s=$(echo "scale=2; ($file_size_bytes / 1024 / 1024) / $duration" | bc)
    local events_per_sec=$(echo "scale=0; $events / $duration" | bc)
    
    # Clean up
    rm -f "$output"
    
    echo "$throughput_mb_s $events_per_sec $duration"
}

# Check if we need to establish baseline
if [ ! -f "$BASELINE_FILE" ] || [ "$1" == "--reset-baseline" ]; then
    echo -e "${YELLOW}Establishing baseline performance...${NC}"
    
    # Run 3 times and take the median
    declare -a throughputs
    declare -a event_rates
    
    for i in {1..3}; do
        echo -n "  Run $i/3... "
        metrics=$(measure_throughput $TEST_EVENTS $OUTPUT_FILE)
        throughput=$(echo "$metrics" | cut -d' ' -f1)
        event_rate=$(echo "$metrics" | cut -d' ' -f2)
        throughputs+=($throughput)
        event_rates+=($event_rate)
        echo "✓ ${throughput} MB/s"
    done
    
    # Calculate median (sort and take middle value)
    IFS=$'\n' sorted_throughputs=($(sort -n <<<"${throughputs[*]}"))
    IFS=$'\n' sorted_event_rates=($(sort -n <<<"${event_rates[*]}"))
    baseline_throughput=${sorted_throughputs[1]}
    baseline_event_rate=${sorted_event_rates[1]}
    
    # Save baseline
    echo "$baseline_throughput $baseline_event_rate" > "$BASELINE_FILE"
    echo -e "${GREEN}Baseline established: ${baseline_throughput} MB/s (${baseline_event_rate} events/s)${NC}"
    echo ""
fi

# Read baseline
read baseline_throughput baseline_event_rate < "$BASELINE_FILE"
echo "Baseline performance: ${baseline_throughput} MB/s (${baseline_event_rate} events/s)"
echo ""

# Run current test
echo "Running throughput test..."
metrics=$(measure_throughput $TEST_EVENTS $OUTPUT_FILE)
current_throughput=$(echo "$metrics" | cut -d' ' -f1)
current_event_rate=$(echo "$metrics" | cut -d' ' -f2)
duration=$(echo "$metrics" | cut -d' ' -f3)

echo "Current performance: ${current_throughput} MB/s (${current_event_rate} events/s)"
echo "Test duration: ${duration}s"

# Calculate percentage of baseline
throughput_percent=$(echo "scale=1; ($current_throughput / $baseline_throughput) * 100" | bc)
event_rate_percent=$(echo "scale=1; ($current_event_rate / $baseline_event_rate) * 100" | bc)

# Determine if performance is acceptable
# We expect at least 80% of baseline performance
MIN_ACCEPTABLE_PERCENT=80

echo ""
echo "Performance Analysis:"
echo "  Throughput: ${throughput_percent}% of baseline"
echo "  Event rate: ${event_rate_percent}% of baseline"

# Check if performance is acceptable
if (( $(echo "$throughput_percent < $MIN_ACCEPTABLE_PERCENT" | bc -l) )); then
    echo -e "${RED}❌ FAIL: Throughput is below acceptable threshold (${MIN_ACCEPTABLE_PERCENT}%)${NC}"
    echo ""
    echo "Possible causes:"
    echo "  - Recent code changes introduced performance regression"
    echo "  - System under heavy load"
    echo "  - Disk I/O issues"
    echo ""
    echo "To reset baseline after fixing issues: $0 --reset-baseline"
    exit 1
else
    echo -e "${GREEN}✅ PASS: Throughput is within acceptable range${NC}"
fi

# Additional performance insights
echo ""
echo "Performance Insights:"
if (( $(echo "$current_throughput < 100" | bc -l) )); then
    echo -e "${YELLOW}⚠️  Warning: Throughput below 100 MB/s suggests potential I/O bottleneck${NC}"
    echo "   Check for excessive flushing or small write operations"
elif (( $(echo "$current_throughput > 1000" | bc -l) )); then
    echo -e "${GREEN}🚀 Excellent: Throughput exceeds 1 GB/s${NC}"
else
    echo -e "${GREEN}✓ Good: Throughput is in expected range${NC}"
fi

# Estimate time for large files
echo ""
echo "Estimated generation times:"
echo "  10GB file: $(echo "scale=1; 10240 / $current_throughput" | bc)s"
echo "  100GB file: $(echo "scale=1; 102400 / $current_throughput / 60" | bc) minutes"
echo "  1TB file: $(echo "scale=1; 1048576 / $current_throughput / 3600" | bc) hours"