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

usage() {
  cat <<'EOF'
usage: e2e-smoke-lane

Environment selection:
  TEST=e2e_smoke_mob_live_smoke
  SCENARIO=62
  SUITE=mob-live-smoke

Execution modes:
  MEERKAT_E2E_EXECUTION_MODE=cargo     Run the current nested-cargo harness.
  MEERKAT_E2E_EXECUTION_MODE=prebuilt  Materialize selected artifacts first,
                                       then run the harness from the manifest.
EOF
}

if [[ "${1:-}" == "-h" || "${1:-}" == "--help" ]]; then
  usage
  exit 0
fi

root="$(git rev-parse --show-toplevel)"
cd "${root}"
export WORKSPACE_ROOT="${root}"

source "${root}/scripts/build-backend-env"
meerkat_load_local_secrets_env "${root}"

buildbuddy_enabled() {
  case "${MEERKAT_BUILDBUDDY:-}" in
    1|true|TRUE|yes|YES|on|ON|buildbuddy)
      return 0
      ;;
    *)
      return 1
      ;;
  esac
}

buildbuddy_output_base() {
  if [[ -n "${BUILDBUDDY_OUTPUT_BASE:-}" ]]; then
    printf '%s\n' "${BUILDBUDDY_OUTPUT_BASE}"
    return 0
  fi

  local cache_root workspace_hash config lane_key agent_lane
  cache_root="${MEERKAT_BUILDBUDDY_OUTPUT_ROOT:-${XDG_CACHE_HOME:-${HOME}/.cache}/meerkat/buildbuddy-bazel}"
  workspace_hash="$(printf '%s' "${root}" | shasum -a 256 | awk '{print substr($1, 1, 16)}')"
  config="${BUILDBUDDY_BAZEL_CONFIG:-buildbuddy-macos-rbe}"
  lane_key="${BUILDBUDDY_OUTPUT_LANE:-e2e-smoke-rbe-${config}}"
  agent_lane="${BUILDBUDDY_AGENT_LANE:-${RUST_LANE_ID:-${CODEX_AGENT_ID:-}}}"
  if [[ -n "${agent_lane}" ]]; then
    lane_key="${lane_key}-${agent_lane}"
  fi
  lane_key="$(printf '%s' "${lane_key}" | tr -c 'A-Za-z0-9_.-' '-')"
  printf '%s/%s-%s-%s\n' "${cache_root}" "$(basename "${root}")" "${workspace_hash}" "${lane_key}"
}

buildbuddy_e2e_artifacts_bin() {
  local output_base candidate
  output_base="$(buildbuddy_output_base)"
  candidate="$(
    find "${output_base}/execroot/_main/bazel-out" \
      -type f \
      -name e2e_artifacts_bin \
      -path '*/bin/tests/integration/e2e_artifacts_bin' \
      -perm -111 \
      2>/dev/null |
      head -n 1
  )"
  if [[ -n "${candidate}" ]]; then
    printf '%s\n' "${candidate}"
    return 0
  fi
  return 1
}

buildbuddy_wasm_pack_bin() {
  local output_base candidate
  output_base="$(buildbuddy_output_base)"
  for candidate in \
    "${output_base}/external/+http_archive+wasm_pack_darwin_arm64/wasm-pack" \
    "${output_base}/external/wasm_pack_darwin_arm64/wasm-pack" \
    "${output_base}/execroot/_main/external/+http_archive+wasm_pack_darwin_arm64/wasm-pack" \
    "${output_base}/execroot/_main/external/wasm_pack_darwin_arm64/wasm-pack"; do
    if [[ -x "${candidate}" ]]; then
      printf '%s\n' "${candidate}"
      return 0
    fi
  done
  candidate="$(
    find -L "${output_base}" \
      -type f \
      -name wasm-pack \
      -path '*/wasm_pack_darwin_arm64/*' \
      -perm -111 \
      2>/dev/null |
      head -n 1
  )"
  if [[ -n "${candidate}" ]]; then
    printf '%s\n' "${candidate}"
    return 0
  fi
  return 1
}

e2e_artifacts_cmd=("${root}/scripts/repo-cargo" run -p meerkat-integration-tests --bin e2e_artifacts --)
if buildbuddy_enabled; then
  if artifact_bin="$(buildbuddy_e2e_artifacts_bin)"; then
    e2e_artifacts_cmd=("${artifact_bin}")
    export MEERKAT_E2E_BAZEL_BIN_DIR="$(cd "$(dirname "${artifact_bin}")/../.." && pwd)"
    if [[ -z "${RKAT_WASM_PACK_BIN:-}" && -z "${WASM_PACK:-}" ]] &&
      wasm_pack_bin="$(buildbuddy_wasm_pack_bin)"; then
      export RKAT_WASM_PACK_BIN="${wasm_pack_bin}"
      export WASM_PACK="${wasm_pack_bin}"
    fi
  else
    echo "error: BuildBuddy e2e-smoke foundation did not produce e2e_artifacts_bin" >&2
    echo "Run MEERKAT_BUILDBUDDY=1 make e2e-smoke so scripts/buildbuddy-dev builds //tests/integration:e2e_artifacts_bin first." >&2
    exit 1
  fi
fi

selection_count=0
selection_args=()

if [[ -n "${TEST:-}" ]]; then
  selection_count=$((selection_count + 1))
  selection_args=(--test "${TEST}")
fi
if [[ -n "${SCENARIO:-}" ]]; then
  selection_count=$((selection_count + 1))
  selection_args=(--scenario "${SCENARIO}")
fi
if [[ -n "${SUITE:-}" ]]; then
  selection_count=$((selection_count + 1))
  selection_args=(--suite "${SUITE}")
fi

if [[ "${selection_count}" -gt 1 ]]; then
  echo "error: provide only one of TEST, SCENARIO, or SUITE" >&2
  exit 2
fi

if [[ "${selection_count}" -eq 0 ]]; then
  selection_args=(--lane smoke)
fi

filter=""
if [[ "${selection_count}" -eq 1 ]]; then
  filter="$("${root}/scripts/e2e-smoke-filter" "${selection_args[@]}")"
fi

mode="${MEERKAT_E2E_EXECUTION_MODE:-cargo}"
case "${mode}" in
  prebuilt|PREBUILT|Prebuilt|1|true|TRUE)
    mode="prebuilt"
    ;;
  cargo|CARGO|Cargo|0|false|FALSE|"")
    mode="cargo"
    ;;
  *)
    echo "error: unknown MEERKAT_E2E_EXECUTION_MODE='${mode}'" >&2
    exit 2
    ;;
esac

test_args=(
  test
  -p
  meerkat-integration-tests
  --test
  e2e_smoke_lane
)
if [[ -n "${filter}" ]]; then
  test_args+=("${filter}")
fi
test_args+=(
  --
  --ignored
  --nocapture
)

if [[ "${mode}" == "cargo" ]]; then
  if [[ "${selection_count}" -eq 0 ]]; then
    exec "${root}/scripts/repo-cargo" e2e-smoke
  fi
  exec "${root}/scripts/repo-cargo" "${test_args[@]}"
fi

if [[ -z "${MEERKAT_E2E_ARTIFACT_MANIFEST:-}" ]]; then
  target_dir="$("${root}/scripts/repo-cargo" --print-env | awk -F= '$1 == "CARGO_TARGET_DIR" { print $2 }')"
  selection_key="$(printf '%s-' "${selection_args[@]}" | tr -c 'A-Za-z0-9_.-' '-' | sed 's/-$//')"
  export MEERKAT_E2E_ARTIFACT_MANIFEST="${target_dir}/e2e-lanes/prebuilt/${selection_key}/artifact-manifest.json"
fi

"${e2e_artifacts_cmd[@]}" \
  materialize \
  --manifest "${MEERKAT_E2E_ARTIFACT_MANIFEST}" \
  "${selection_args[@]}"

export MEERKAT_E2E_EXECUTION_MODE=prebuilt
exec "${e2e_artifacts_cmd[@]}" \
  run-smoke \
  --manifest "${MEERKAT_E2E_ARTIFACT_MANIFEST}" \
  "${selection_args[@]}"
