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

repo_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd -P)"
cd "${repo_root}"
script_name="ci-web-e2e-full"

e2e_now_ms() {
  local value
  value="$(date +%s%3N 2>/dev/null || true)"
  if [[ "${value}" =~ ^[0-9]+$ ]]; then
    printf '%s\n' "${value}"
    return
  fi
  printf '%s000\n' "$(date +%s)"
}

e2e_time_step() {
  local key="$1"
  shift
  local started_at finished_at status
  started_at="$(e2e_now_ms)"
  set +e
  (
    set -e
    "$@"
  )
  status="$?"
  set -e
  finished_at="$(e2e_now_ms)"
  printf '[e2e:timing] key=%s script=%s status=%s duration_ms=%s\n' \
    "${key}" \
    "${script_name}" \
    "${status}" \
    "$((finished_at - started_at))" >&2
  return "${status}"
}

run_web_e2e() {
  (
    cd web
    node e2e/run-web-e2e.mjs ci "$@"
  )
}

if [[ ! -f .env ]]; then
  cp .env.example .env
fi

explicit_tidb_playground_version="${AGENTTEAM_TIDB_PLAYGROUND_VERSION-__agentteam_unset__}"
set -a
source .env
set +a
if [[ "${explicit_tidb_playground_version}" != "__agentteam_unset__" ]]; then
  export AGENTTEAM_TIDB_PLAYGROUND_VERSION="${explicit_tidb_playground_version}"
elif [[ "${AGENTTEAM_TIDB_PLAYGROUND_VERSION:-}" == "v8.5.5" ]]; then
  unset AGENTTEAM_TIDB_PLAYGROUND_VERSION
fi

e2e_time_step ensure_web_node_modules ./scripts/ensure-web-node-modules.sh
e2e_time_step web_dist ./scripts/ensure-web-dist.sh
e2e_time_step runner_execution run_web_e2e "$@"
