#!/usr/bin/env bash
# The npx shim must run an already-installed context-mode bundle directly, and must fall
# through to real npx for everything else (and when nothing is installed).
set -uo pipefail

ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
SHIM_BODY="$ROOT/bin/_cpu-guard-shim.sh"
SANDBOX="$(mktemp -d)"
trap 'rm -rf "$SANDBOX"' EXIT

pass=0; fail=0
ok(){ echo "PASS $1"; pass=$((pass+1)); }
bad(){ echo "FAIL $1: $2"; fail=$((fail+1)); }

mkdir -p "$SANDBOX/bin" "$SANDBOX/lib" "$SANDBOX/real"
cp "$SHIM_BODY" "$SANDBOX/bin/_cpu-guard-shim.sh"
cp "$ROOT/lib/shim-guard.sh" "$SANDBOX/lib/shim-guard.sh"
ln -s _cpu-guard-shim.sh "$SANDBOX/bin/npx"

# A stub "real npx" that only reports it was reached, so a fall-through is unmistakable.
cat >"$SANDBOX/real/npx" <<'EOF'
#!/usr/bin/env bash
echo "REAL-NPX $*"
EOF
chmod +x "$SANDBOX/real/npx"

# A stub bun that reports its argv instead of executing the bundle.
cat >"$SANDBOX/real/bun" <<'EOF'
#!/usr/bin/env bash
echo "BUN $*"
EOF
chmod +x "$SANDBOX/real/bun"

BUNDLE_DIR="$SANDBOX/home/.npm/_npx/deadbeef/node_modules/context-mode"
mkdir -p "$BUNDLE_DIR"
echo "// bundle" >"$BUNDLE_DIR/cli.bundle.mjs"

run(){ # run <home> <args...>
  local home="$1"; shift
  HOME="$home" OD_BUN="$SANDBOX/real/bun" PATH="$SANDBOX/bin:$SANDBOX/real:/usr/bin:/bin" \
    SHIM_REENTRY=0 "$SANDBOX/bin/npx" "$@" 2>&1
}

out=$(run "$SANDBOX/home" -y context-mode hook cursor posttooluse)
if [[ "$out" == "BUN $BUNDLE_DIR/cli.bundle.mjs hook cursor posttooluse" ]]; then
  ok "npx -y context-mode runs the installed bundle under bun"
else
  bad "npx -y context-mode runs the installed bundle under bun" "$out"
fi

out=$(run "$SANDBOX/home" context-mode hook cursor pretooluse)
if [[ "$out" == "BUN $BUNDLE_DIR/cli.bundle.mjs hook cursor pretooluse" ]]; then
  ok "the fast path does not require -y"
else
  bad "the fast path does not require -y" "$out"
fi

out=$(run "$SANDBOX/home" -y some-other-package --flag)
if [[ "$out" == "REAL-NPX -y some-other-package --flag" ]]; then
  ok "another package falls through to real npx"
else
  bad "another package falls through to real npx" "$out"
fi

out=$(run "$SANDBOX/empty-home" -y context-mode hook cursor posttooluse)
if [[ "$out" == "REAL-NPX -y context-mode hook cursor posttooluse" ]]; then
  ok "no installed bundle falls through to real npx"
else
  bad "no installed bundle falls through to real npx" "$out"
fi

# The newest install wins, so a package upgrade is picked up without touching the shim.
NEWER="$SANDBOX/home/.npm/_npx/cafebabe/node_modules/context-mode"
mkdir -p "$NEWER"
echo "// newer" >"$NEWER/cli.bundle.mjs"
touch -d "+1 hour" "$NEWER/cli.bundle.mjs"
out=$(run "$SANDBOX/home" -y context-mode hook cursor stop)
if [[ "$out" == "BUN $NEWER/cli.bundle.mjs hook cursor stop" ]]; then
  ok "the newest installed bundle wins"
else
  bad "the newest installed bundle wins" "$out"
fi

echo "npx-context-mode-fastpath: pass=$pass fail=$fail"
[ "$fail" -eq 0 ]
