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

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

usage() {
  cat >&2 <<'USAGE'
Usage: scripts/ci-web-e2e-lane.sh <lane> [--list]

Runs one existing Web E2E CI lane through the repo-managed lane scheduler.
USAGE
}

if [[ "$#" -lt 1 ]]; then
  usage
  exit 2
fi

lane="$1"
shift

if [[ -z "${lane}" || "${lane}" == --* ]]; then
  usage
  exit 2
fi

runner_args=()
if [[ "$#" -gt 0 ]]; then
  if [[ "$#" -eq 1 && "$1" == "--list" ]]; then
    runner_args+=("--list")
  else
    usage
    exit 2
  fi
fi

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 lane=%s status=%s duration_ms=%s\n' \
    "${key}" \
    "${script_name}" \
    "${lane}" \
    "${status}" \
    "$((finished_at - started_at))" >&2
  return "${status}"
}

validate_lane() {
  node --input-type=module -e '
    import { ciWavePlanSummary } from "./web/e2e/run-web-e2e.mjs"

    const lane = process.argv[1]
    const lanes = ciWavePlanSummary().flatMap((wave) => wave.lanes)
    if (!lanes.includes(lane)) {
      console.error(`Unknown Web E2E CI lane ${JSON.stringify(lane)}. Valid lanes: ${lanes.join(", ")}`)
      process.exit(2)
    }
  ' "${lane}"
}

run_web_e2e_lane() {
  (
    cd web
    if (( ${#runner_args[@]} == 0 )); then
      node e2e/run-web-e2e.mjs ci:default --lane "${lane}"
    else
      node e2e/run-web-e2e.mjs ci:default --lane "${lane}" "${runner_args[@]}"
    fi
  )
}

e2e_time_step lane_validation validate_lane

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
if [[ "${runner_args[*]:-}" != "--list" ]]; then
  e2e_time_step web_dist ./scripts/ensure-web-dist.sh
fi
e2e_time_step runner_execution run_web_e2e_lane
