#!/bin/bash

# Benchmark Runner Script for Node.js API
# Location: node_api/scratch/run_benchmarks.sh

SCENARIO=$1
if [ -z "$SCENARIO" ]; then
    echo "Usage: $0 <scenario_name>"
    echo "Example: $0 scenario1_single_pm2"
    exit 1
fi

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
BASE_URL="https://app.edistry.com"
HEALTH_URL="${BASE_URL}/health"
ABOUT_URL="${BASE_URL}/api/about"
POST_DATA="${SCRIPT_DIR}/post_data.json"
REQUESTS=5000
CONCURRENCIES=(10 50 100 200 500)

RESULTS_DIR="${SCRIPT_DIR}/results/${SCENARIO}"
mkdir -p "${RESULTS_DIR}"

echo "=========================================================="
echo " Starting Benchmarks for Scenario: ${SCENARIO}"
echo " Total Requests per test: ${REQUESTS}"
echo "=========================================================="

# Header for output tables
printf "%-10s %-15s %-12s %-12s %-12s %-12s\n" "Endpoint" "Concurrency" "RPS" "Avg Lat (ms)" "99% Lat (ms)" "Failed Req"
echo "--------------------------------------------------------------------------------"

run_test() {
    local endpoint=$1
    local url=$2
    local method=$3
    local c=$4
    local log_file="${RESULTS_DIR}/${endpoint}_c${c}.log"

    # Run ab directly based on the method
    if [ "$method" == "POST" ]; then
        ab -n "${REQUESTS}" -c "${c}" -r -H "X-Bypass-RateLimit: true" -p "${POST_DATA}" -T "application/json" "${url}" > "${log_file}" 2>&1
    else
        ab -n "${REQUESTS}" -c "${c}" -r -H "X-Bypass-RateLimit: true" "${url}" > "${log_file}" 2>&1
    fi

    # Extract metrics
    local rps=$(grep -i "Requests per second:" "${log_file}" | awk '{print $4}')
    local avg_lat=$(grep -i "Time per request:" "${log_file}" | head -n 1 | awk '{print $4}')
    local failed=$(grep -i "Failed requests:" "${log_file}" | awk '{print $3}')
    local lat_99=$(grep -A 10 "Percentage of the requests served" "${log_file}" | grep "99%" | awk '{print $2}')

    if [ -z "$rps" ]; then rps="ERR"; fi
    if [ -z "$avg_lat" ]; then avg_lat="ERR"; fi
    if [ -z "$failed" ]; then failed="0"; fi
    if [ -z "$lat_99" ]; then lat_99="ERR"; fi

    printf "%-10s %-15s %-12s %-12s %-12s %-12s\n" "${endpoint}" "${c}" "${rps}" "${avg_lat}" "${lat_99}" "${failed}"
}

# Run /health (GET) benchmarks
for c in "${CONCURRENCIES[@]}"; do
    run_test "health" "${HEALTH_URL}" "GET" "${c}"
done

echo "--------------------------------------------------------------------------------"

# Run /api/about (POST) benchmarks
for c in "${CONCURRENCIES[@]}"; do
    run_test "about" "${ABOUT_URL}" "POST" "${c}"
done

echo "=========================================================="
echo " Done. Logs saved in ${RESULTS_DIR}/"
echo "=========================================================="
