#!/usr/bin/env bash
set -euo pipefail

repo_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
target_name="${BENCH_TARGET_NAME:-target}"
scenario_name="${BENCH_SCENARIO_NAME:-scenario}"
run_stamp="$(date +%Y%m%d-%H%M%S)"
result_dir="${BENCH_RESULT_DIR:-${repo_root}/artifacts/performance/${run_stamp}-${target_name}-${scenario_name}}"

if ! command -v k6 >/dev/null 2>&1; then
  echo "k6 is required for the three-run comparison" >&2
  exit 1
fi
if [[ -z "${BENCH_BASE_URL:-}" || -z "${BENCH_PATH:-}" ]]; then
  echo "BENCH_BASE_URL and BENCH_PATH are required" >&2
  exit 1
fi

mkdir -p "${result_dir}"
for run_number in 1 2 3; do
  k6 run --summary-export "${result_dir}/summary-run-${run_number}.json" \
    "${repo_root}/tools/performance/dual-line.js" \
    | tee "${result_dir}/run-${run_number}.txt"
done

printf 'target=%s\nscenario=%s\nbase_url=%s\npath=%s\n' \
  "${target_name}" "${scenario_name}" "${BENCH_BASE_URL}" "${BENCH_PATH}" >"${result_dir}/run.env"
echo "Results: ${result_dir}"
