#!/bin/bash
# Benchmark script for Aprender
# Generated by bashrs - DO NOT EDIT MANUALLY
# Source: scripts/bench.rs

set -euo pipefail

echo "📊 Aprender Benchmark Suite"
echo "==========================="
echo ""

# Configuration - validated to prevent path traversal
# bashrs:allow DET002 - timestamp intentionally non-deterministic for unique filenames
# bashrs:allow SEC010 - BASELINE_DIR is hardcoded constant, not user input
BASELINE_DIR=".performance-baselines"

# Parse arguments
SAVE_BASELINE=false
COMPARE_BASELINE=false

while [[ $# -gt 0 ]]; do
    case "$1" in
        --save)
            SAVE_BASELINE=true
            shift
            ;;
        --compare)
            COMPARE_BASELINE=true
            shift
            ;;
        *)
            echo "Unknown option: $1"
            echo "Usage: $0 [--save] [--compare]"
            exit 1
            ;;
    esac
done

# Ensure release build
echo "🔨 Building release..."
cargo build --release --quiet

# Run benchmarks
echo "🏃 Running benchmarks..."
echo ""

if [ "$SAVE_BASELINE" = true ]; then
    mkdir -p "$BASELINE_DIR"
    # Note: Timestamp is intentionally non-deterministic for unique baseline filenames
    TIMESTAMP="$(date +%Y%m%d_%H%M%S)"
    BASELINE_FILE="$BASELINE_DIR/bench_$TIMESTAMP.txt"

    cargo bench --quiet 2>&1 | tee "$BASELINE_FILE"

    echo ""
    echo "✅ Baseline saved to: $BASELINE_FILE"
elif [ "$COMPARE_BASELINE" = true ]; then
    # Find latest baseline
    LATEST_BASELINE="$(find "$BASELINE_DIR" -name 'bench_*.txt' -type f -printf '%T@ %p\n' 2>/dev/null | sort -rn | head -1 | cut -d' ' -f2-)"

    if [ -z "$LATEST_BASELINE" ]; then
        echo "❌ No baseline found. Run with --save first."
        exit 1
    fi

    echo "📈 Comparing against: $LATEST_BASELINE"
    echo ""

    # Run benchmarks with comparison
    cargo bench --quiet

    echo ""
    echo "✅ Benchmark comparison complete"
else
    cargo bench --quiet
fi

echo ""
echo "🎉 Benchmarks complete!"

exit 0
