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

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

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}"
}

load_jenkins_go_proxy_env() {
  if [[ -z "${JENKINS_URL:-}" ]]; then
    return 0
  fi

  local env_file="${AGENTTEAM_JENKINS_GO_PROXY_ENV_FILE:-/tmp/agentteam-nexus-go.env}"
  if [[ ! -f "${env_file}" || -L "${env_file}" || ! -O "${env_file}" ]]; then
    echo "trusted Jenkins Go proxy environment is unavailable: ${env_file}" >&2
    return 1
  fi

  # shellcheck source=/dev/null
  source "${env_file}"
}


cleanup_ci_leftovers() {
  if [[ "${AGENTTEAM_CI_CLEANUP_LEFTOVERS:-}" != "1" ]]; then
    return 0
  fi
  if ! command -v node >/dev/null 2>&1; then
    echo "node is not available; skipping CI leftovers cleanup" >&2
    return 0
  fi
  node scripts/cleanup-leftovers.mjs || true
}

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

ensure_playwright_chromium() {
  (
    cd web
    local browsers_root="${PLAYWRIGHT_BROWSERS_PATH:-${HOME}/.cache/ms-playwright}"
    if [[ -f node_modules/playwright-core/browsers.json ]]; then
      local missing
      # `playwright install chromium` provisions the full chromium and the
      # chromium-headless-shell executables (both installByDefault in
      # browsers.json). A cache hit is only valid when every one of them is
      # fully installed, which Playwright itself signals with an
      # INSTALLATION_COMPLETE marker in each browser directory. The required
      # directories are derived from browsers.json (dashes -> underscores),
      # not hardcoded, so the check tracks Playwright's own registry layout.
      if missing="$(PLAYWRIGHT_BROWSERS_PATH="${browsers_root}" node -e '
        const fs = require("fs")
        const path = require("path")
        const b = JSON.parse(fs.readFileSync("./node_modules/playwright-core/browsers.json", "utf8"))
        const root = process.env.PLAYWRIGHT_BROWSERS_PATH
        const missing = b.browsers
          .filter((x) => x.installByDefault !== false && (x.name === "chromium" || x.name === "chromium-headless-shell"))
          .filter((x) => !fs.existsSync(path.join(root, x.name.replace(/-/g, "_") + "-" + x.revision, "INSTALLATION_COMPLETE")))
          .map((x) => x.name)
        if (missing.length) process.stdout.write(missing.join(" "))
      ' 2>/dev/null)"; then
        if [[ -z "${missing}" ]]; then
          echo "Playwright Chromium (chromium + chromium-headless-shell) already fully installed at ${browsers_root}; skipping install"
          return 0
        fi
        echo "Playwright Chromium install incomplete (missing: ${missing}); installing" >&2
      else
        echo "could not resolve Playwright browsers.json; installing" >&2
      fi
    fi
    npx playwright install --with-deps chromium
  )
}

cleanup_ci_leftovers

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

# Jenkins writes this file after configuring the authenticated Nexus Go module
# proxy. Its global process environment otherwise overrides `go env -w`, so the
# backend build can silently fall back to the much slower public proxy. The
# loader is a no-op outside Jenkins and fails closed on an untrusted/missing
# file inside Jenkins.
load_jenkins_go_proxy_env

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