#!/bin/bash
# Benchmark route resolution performance
#
# Usage: ./benchmark-route.sh <path> [iterations]
# Example: ./benchmark-route.sh /services 1000

set -e

ROUTE_PATH="${1:-/}"
ITERATIONS="${2:-1000}"
BASE_URL="${BASE_URL:-http://localhost:3030}"

echo "🧭 Benchmarking route resolution: $ROUTE_PATH"
echo "🔄 Iterations: $ITERATIONS"
echo "🌐 Base URL: $BASE_URL"

# Check if server is running
if ! curl -f -s "$BASE_URL/health" > /dev/null 2>&1; then
    echo "❌ Server not running at $BASE_URL"
    echo "💡 Start server with: just dev::with-nav-test"
    exit 1
fi

# Run benchmark
echo "⏱️  Running benchmark..."
response=$(curl -s "$BASE_URL/api/nav-test/benchmark?path=$ROUTE_PATH&iterations=$ITERATIONS")

if [ $? -eq 0 ]; then
    echo "✅ Benchmark completed"

    # Parse and display performance information
    if command -v jq &> /dev/null; then
        echo "📊 Performance Metrics:"
        echo "$response" | jq -r '
        "  Path: " + .path +
        "\n  Component: " + (.component // "None") +
        "\n  Language: " + .language +
        "\n  Iterations: " + (.iterations | tostring) +
        "\n  Total Time: " + (.total_time_ms | tostring) + "ms" +
        "\n  Average Time: " + (.avg_time_ms | tostring) + "ms" +
        "\n  Min Time: " + (.min_time_ms | tostring) + "ms" +
        "\n  Max Time: " + (.max_time_ms | tostring) + "ms"
        '

        # Calculate performance rating
        avg_time=$(echo "$response" | jq -r '.avg_time_ms')
        if command -v bc &> /dev/null; then
            # Use bc for floating point comparison
            if (( $(echo "$avg_time < 0.1" | bc -l) )); then
                echo "🚀 Excellent performance (< 0.1ms avg)"
            elif (( $(echo "$avg_time < 1.0" | bc -l) )); then
                echo "✅ Good performance (< 1ms avg)"
            elif (( $(echo "$avg_time < 10.0" | bc -l) )); then
                echo "⚠️  Acceptable performance (< 10ms avg)"
            else
                echo "🐌 Slow performance (> 10ms avg)"
            fi
        else
            echo "📈 Performance data available above"
        fi

        # Show requests per second
        total_time_s=$(echo "$response" | jq -r '.total_time_ms / 1000')
        if command -v bc &> /dev/null; then
            rps=$(echo "scale=0; $ITERATIONS / $total_time_s" | bc -l)
            echo "⚡ Requests per second: ~${rps}"
        fi
    else
        echo "📊 Raw Response:"
        echo "$response"
        echo ""
        echo "💡 Install jq for better output formatting: brew install jq"
        echo "💡 Install bc for performance calculations: brew install bc"
    fi
else
    echo "❌ Benchmark failed"
    exit 1
fi

echo ""
echo "🎉 Benchmark completed successfully"
