#!/usr/bin/env bash
set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" &>/dev/null && pwd)"
ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"

# shellcheck source-path=SCRIPTDIR
source "$SCRIPT_DIR/style.sh"
# shellcheck source-path=SCRIPTDIR
source "$SCRIPT_DIR/helpers.sh"

mise_wait_for_gh_rate_limit() {
	local mise_bin="$1"
	# Allow explicit opt-out for local/dev runs.
	if [[ ${E2E_WAIT_FOR_GH_RATE_LIMIT:-1} != 1 ]]; then
		return 0
	fi
	if "$mise_bin" which wait-for-gh-rate-limit >/dev/null 2>&1; then
		"$mise_bin" x -- wait-for-gh-rate-limit
	else
		warn "wait-for-gh-rate-limit not available; skipping rate-limit wait"
	fi
}

# Check for .release-skip-e2e and skip all tests if version matches
RELEASE_SKIP_FILE="$ROOT/.release-skip-e2e"
VERSION="$(. "$ROOT/scripts/get-version.sh" | tr -d '\n')"
if [[ -f $RELEASE_SKIP_FILE ]]; then
	if grep -Fxq "$VERSION" "$RELEASE_SKIP_FILE"; then
		echo "[e2e] Skipping all e2e tests: .release-skip-e2e contains $VERSION" >&2
		exit 0
	fi
fi

pushd e2e
# List test files with a portable fallback chain.
list_test_files() {
	local pattern="$1"
	if command -v fd >/dev/null 2>&1; then
		fd -tf -g "$pattern" | sort
	elif command -v rg >/dev/null 2>&1; then
		rg --files -g "$pattern" | sort
	else
		find . -type f -name "$pattern" | sed 's#^\./##' | sort
	fi
}

# Avoid mapfile that is not available on bash 3.2 for compatibility with macOS
SLOW_FILES=()
while IFS= read -r line; do
	SLOW_FILES+=("$line")
done < <(list_test_files "test_*_slow")
FAST_FILES=()
while IFS= read -r line; do
	FAST_FILES+=("$line")
done < <(list_test_files "test_*" | grep -v "_slow$")
popd
FILES=("${FAST_FILES[@]}" "${SLOW_FILES[@]}")
MISE_BIN="$(resolve_mise_bin)"
test_count=0
skipped_count=0
status=0

summary "Test" "Duration" "Result"
summary "---" "---" "---"

for index in "${!FILES[@]}"; do
	TEST_NAME="${FILES[$index]}"

	# split tests into tranches to reduce test time
	if [[ -n ${TEST_TRANCHE_COUNT:-} ]]; then
		if [[ $((index % TEST_TRANCHE_COUNT)) -ne $TEST_TRANCHE ]]; then
			continue
		fi
	fi

	# Skip slow tests unless TEST_ALL == 1
	if [[ ${TEST_ALL:-0} != 1 && $TEST_NAME == *_slow ]]; then
		#    title="E2E test $TEST_NAME skipped" file="e2e/$TEST_NAME" warn "slow tests are disabled"
		skipped_count=$((skipped_count + 1))
		summary "$TEST_NAME" "-" ":zap:"
		continue
	fi

	mise_wait_for_gh_rate_limit "$MISE_BIN"
	# Actually run the test
	"$ROOT/e2e/run_test" "$TEST_NAME" # fail fast for now
	# if ! "$ROOT/e2e/run_test" "$TEST_NAME"; then
	#   status=1
	# fi
	test_count=$((test_count + 1))
done

echo "E2E: ran $test_count tests, skipped $skipped_count tests" >&2

exit "$status"
