#!/usr/bin/env bash

export MISE_TRUSTED_CONFIG_PATHS=""
unset CI GITHUB_ACTIONS GITHUB_ACTION 2>/dev/null || true

mise_bin_dir="$(dirname "$(type -P mise)")"
base_path="$mise_bin_dir:/usr/bin:/bin"
fish_bin="$(type -P fish || true)"

cat >mise.toml <<'EOF'
[env]
FROM_PROJECT = "{{ exec(command='touch project-config-ran') }}"
EOF

# An ambient usage binary is preferred without consulting project configuration.
cat >"$HOME/bin/usage" <<'EOF'
#!/usr/bin/env bash
echo '# path-usage-completion'
EOF
chmod +x "$HOME/bin/usage"
path_output="$(PATH="$HOME/bin:$base_path" MISE_YES=0 mise completion fish 2>&1)"
assert_contains_text "$path_output" "path-usage-completion"
assert_not_contains_text "$path_output" "trust"
assert_fail "test -e project-config-ran"

# A globally configured usage tool is the only mise-managed fallback considered. Build a local
# asdf fixture before making the project config unsafe, then expose its binary under the expected
# name so completion can identify which lookup path ran.
rm "$HOME/bin/usage"
cp -RL "$MISE_DATA_DIR/plugins/dummy" "$HOME/usage-plugin"

cat >"$MISE_CONFIG_DIR/config.toml" <<'EOF'
[tools]
"asdf:usage" = "1.0.0"
EOF
mv mise.toml mise.toml.untrusted
PATH="$base_path" mise plugin link -f usage "$HOME/usage-plugin"
mkdir -p "$MISE_DATA_DIR/installs/asdf-usage/1.0.0/bin"
cat >"$MISE_DATA_DIR/installs/asdf-usage/1.0.0/bin/usage" <<'EOF'
#!/usr/bin/env bash
echo '# global-usage-completion'
EOF
chmod +x "$MISE_DATA_DIR/installs/asdf-usage/1.0.0/bin/usage"
mv mise.toml.untrusted mise.toml

global_output="$(PATH="$base_path" MISE_YES=0 mise completion fish 2>&1)"
assert_contains_text "$global_output" "global-usage-completion"
assert_not_contains_text "$global_output" "trust"
assert_fail "test -e project-config-ran"

# Without either usage source, the prerendered completion remains available. On macOS, exercise
# the same command in a real PTY under fish, matching fish's lazy completion bootstrap.
mv "$MISE_CONFIG_DIR/config.toml" "$MISE_CONFIG_DIR/config.toml.disabled"
fallback="$(PATH="$base_path" MISE_YES=0 mise completion fish)"
assert_contains_text "$fallback" "# @generated by usage-cli from usage spec"
assert_fail "test -e project-config-ran"

trust_markers="$(find "$MISE_STATE_DIR/trusted-configs" -mindepth 1 \( -type f -o -type l \) 2>/dev/null || true)"
[[ -z $trust_markers ]] || fail "completion unexpectedly trusted or ignored the project config"

if [[ $(uname -s) == Darwin && -n $fish_bin ]]; then
  pty_output="$(PATH="$base_path" MISE_YES=0 script -q /dev/null "$fish_bin" --no-config -c \
    'mise completion fish | source; complete -C "mise "')"
  assert_not_contains_text "$pty_output" "trust"
  assert_fail "test -e project-config-ran"
fi
