#!/usr/bin/env bash

# Test that PATH reordering done after `mise activate` is preserved by hook-env.
# This simulates the scenario where ~/.zlogin (which runs after ~/.zshrc on login
# shells) reorders PATH entries — e.g., moving a tool to the front for priority.
#
# Regression test for https://github.com/jdx/mise/discussions/8188
# and https://github.com/jdx/mise/issues/8168

# Save the mise binary path before we override PATH
MISE_BIN="$(which mise)"

# Simulate the PATH captured during mise activate in ~/.zshrc
# The original order has system-bin first, mytool/bin last
export __MISE_ORIG_PATH="$HOME/system-bin:/usr/local/bin:/usr/bin:/bin:$HOME/mytool/bin"

# Create test directories and executables
mkdir -p "$HOME/mytool/bin"
mkdir -p "$HOME/system-bin"

# Simulate ~/.zlogin moving ~/mytool/bin to the FRONT of PATH
# (this is what users do to override system binaries)
export PATH="$HOME/mytool/bin:$HOME/system-bin:/usr/local/bin:/usr/bin:/bin"

cat >mise.toml <<'EOF'
EOF

# Run hook-env using the saved binary path
eval "$("$MISE_BIN" hook-env -s bash)"

echo "DEBUG: PATH=$PATH"

# ~/mytool/bin should still be BEFORE ~/system-bin because the user
# reordered it to the front after activation
MYTOOL_POS=$(echo "$PATH" | tr ':' '\n' | grep -n "mytool/bin" | head -1 | cut -d: -f1)
SYSTEM_POS=$(echo "$PATH" | tr ':' '\n' | grep -n "system-bin" | head -1 | cut -d: -f1)

echo "DEBUG: mytool/bin at position $MYTOOL_POS, system-bin at position $SYSTEM_POS"

if [[ -z $MYTOOL_POS ]]; then
	echo "FAIL: mytool/bin not found in PATH"
	exit 1
fi

if [[ -z $SYSTEM_POS ]]; then
	echo "FAIL: system-bin not found in PATH"
	exit 1
fi

if [[ $MYTOOL_POS -lt $SYSTEM_POS ]]; then
	echo "SUCCESS: mytool/bin stays before system-bin (reorder preserved)"
else
	echo "FAIL: mytool/bin ($MYTOOL_POS) was moved after system-bin ($SYSTEM_POS)"
	echo "hook-env restored the original __MISE_ORIG_PATH order instead of the current order"
	exit 1
fi
