#!/usr/bin/env bash
# Run k6 load tests for Voiceprint endpoints
# Usage: ./run.sh [scenario]
#   scenario: mixed (default), enrollment, verification, model-retrieval

set -euo pipefail

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

# Load environment variables from .env if present
if [[ -f .env ]]; then
  set -a
  source .env
  set +a
fi

SCENARIO="${1:-mixed}"
OUTPUT_DIR="${SCRIPT_DIR}/results"
TIMESTAMP="$(date +%Y%m%d-%H%M%S)"

mkdir -p "$OUTPUT_DIR"

echo "=== Voiceprint Load Test ==="
echo "Scenario: $SCENARIO"
echo "Target RPS: ${TARGET_RPS:-500}"
echo "Duration: ${DURATION:-300s}"
echo "Base URL: ${VOICEPRINT_BASE_URL:-http://localhost:3000}"
echo ""

case "$SCENARIO" in
  mixed)
    k6 run voiceprint.js \
      --out json="$OUTPUT_DIR/results-${TIMESTAMP}.json" \
      <<EOF
EOF
    ;;
  enrollment)
    k6 run --scenario enrollment_only voiceprint.js \
      --out json="$OUTPUT_DIR/results-${TIMESTAMP}.json"
    ;;
  verification)
    k6 run --scenario verification_only voiceprint.js \
      --out json="$OUTPUT_DIR/results-${TIMESTAMP}.json"
    ;;
  model-retrieval)
    k6 run --scenario model_retrieval_only voiceprint.js \
      --out json="$OUTPUT_DIR/results-${TIMESTAMP}.json"
    ;;
  *)
    echo "Unknown scenario: $SCENARIO"
    echo "Available: mixed, enrollment, verification, model-retrieval"
    exit 1
    ;;
esac

EXIT_CODE=$?

if [[ $EXIT_CODE -eq 0 ]]; then
  echo ""
  echo "✅ All thresholds passed!"
  echo "Results saved to: $OUTPUT_DIR/results-${TIMESTAMP}.json"
else
  echo ""
  echo "❌ Thresholds failed. Check output above."
  echo "Results saved to: $OUTPUT_DIR/results-${TIMESTAMP}.json"
fi

exit $EXIT_CODE
