#!/usr/bin/env bash
# Single-endpoint leaderboard load test using wrk. See README.md § Load Testing.

set -euo pipefail

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

if [[ ! -f "$ENV_FILE" ]]; then
  echo "Error: missing $ENV_FILE — copy .env.example and fill in your values." >&2
  exit 1
fi

# Parse .env
BASE_URL="http://localhost:5000"
COMPETITION_ID="1"
TEST_USERS=""
WRK_ENDPOINT=""
WRK_METHOD="GET"
WRK_CONNECTIONS="50"

while IFS='=' read -r key value; do
  [[ -z "$key" || "$key" == \#* ]] && continue
  case "$key" in
    BASE_URL)       BASE_URL="$value" ;;
    COMPETITION_ID) COMPETITION_ID="$value" ;;
    TEST_USERS)     TEST_USERS="$value" ;;
    WRK_ENDPOINT)    WRK_ENDPOINT="$value" ;;
    WRK_METHOD)      WRK_METHOD="$value" ;;
    WRK_CONNECTIONS) WRK_CONNECTIONS="$value" ;;
  esac
done < "$ENV_FILE"

# Default endpoint if not set
WRK_ENDPOINT="${WRK_ENDPOINT:-/api/leaderboard/$COMPETITION_ID}"

if [[ -z "$TEST_USERS" ]]; then
  echo "Error: TEST_USERS must be set in $ENV_FILE" >&2
  exit 1
fi

# Pick first test user
FIRST_ENTRY="${TEST_USERS%%,*}"
USERNAME="${FIRST_ENTRY%%:*}"
PASSWORD="${FIRST_ENTRY#*:}"

echo "Authenticating as '$USERNAME'..."

LOGIN_RESPONSE=$(curl -si -X POST "$BASE_URL/api/user/login" \
  -H 'Content-Type: application/json' \
  -d "{\"username\":\"$USERNAME\",\"password\":\"$PASSWORD\"}" 2>&1) || true

if ! echo "$LOGIN_RESPONSE" | grep -q '^HTTP'; then
  echo "Error: could not reach $BASE_URL — is the backend running?" >&2
  echo "$LOGIN_RESPONSE" >&2
  exit 1
fi

HTTP_STATUS=$(echo "$LOGIN_RESPONSE" | grep -m1 '^HTTP' | awk '{print $2}')
if [[ "$HTTP_STATUS" != "200" ]]; then
  echo "Error: login failed with HTTP $HTTP_STATUS" >&2
  echo "$LOGIN_RESPONSE" >&2
  exit 1
fi

TOKEN=$(echo "$LOGIN_RESPONSE" | tail -1 | jq -r '.token')
FGP_HEADER=$(echo "$LOGIN_RESPONSE" | grep -i 'set-cookie:' | grep -oP '(?:__Host-Fgp|Fgp)=[^;,\s]+')
FGP_NAME=$(echo "$FGP_HEADER" | grep -oP '^[^=]+')
FGP=$(echo "$FGP_HEADER" | grep -oP '=\K.+' | python3 -c "import sys, urllib.parse; print(urllib.parse.unquote(sys.stdin.read().strip()))")

if [[ -z "$TOKEN" || "$TOKEN" == "null" ]]; then
  echo "Error: no token in login response" >&2
  exit 1
fi
if [[ -z "$FGP_NAME" || -z "$FGP" ]]; then
  echo "Error: no FGP cookie in login response" >&2
  exit 1
fi

# Write temporary Lua script with token embedded
LUA_FILE=$(mktemp /tmp/wrk-leaderboard-XXXXXX.lua)
trap 'rm -f "$LUA_FILE"' EXIT

cat > "$LUA_FILE" <<EOF
wrk.method = "$WRK_METHOD"
wrk.headers["Authorization"] = "Bearer $TOKEN"
wrk.headers["Cookie"] = "$FGP_NAME=$FGP"
wrk.headers["Accept-Encoding"] = "gzip"
EOF

ENDPOINT="$BASE_URL$WRK_ENDPOINT"
echo "Running wrk against $WRK_METHOD $ENDPOINT"

wrk -t16 -c${WRK_CONNECTIONS:-500} -d30s -s "$LUA_FILE" "$ENDPOINT"
