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

cat >mise.toml <<'EOF'
[env]
UNSET_ENV = false
UNSET_TOOLS_ENV = { value = false, tools = true }
UNSET_SECRET = false

[deps.check-env]
auto = true
run = 'printf "%s|%s" "${UNSET_ENV-absent}" "${UNSET_TOOLS_ENV-absent}" > deps-env'
outputs = ["deps-env"]

[tasks.check]
run = 'printf "%s|%s" "${UNSET_ENV-absent}" "${UNSET_TOOLS_ENV-absent}"'
EOF

UNSET_ENV=parent UNSET_TOOLS_ENV=parent mise exec -- true
assert "cat deps-env" "absent|absent"

assert \
  "UNSET_ENV=parent UNSET_TOOLS_ENV=parent mise exec -- sh -c 'printf \"%s|%s\" \"\${UNSET_ENV-absent}\" \"\${UNSET_TOOLS_ENV-absent}\"'" \
  "absent|absent"
assert \
  "UNSET_ENV=parent UNSET_TOOLS_ENV=parent mise run check" \
  "absent|absent"
assert \
  "UNSET_SECRET=super-secret mise exec -- python3 -c 'import base64, os, zlib; raw = os.environ[\"__MISE_DIFF\"]; print(b\"super-secret\" in zlib.decompress(base64.b64decode(raw + \"=\" * (-len(raw) % 4))))'" \
  "False"
assert_contains \
  "UNSET_ENV=parent UNSET_TOOLS_ENV=parent mise env -s bash" \
  "unset UNSET_ENV"
assert_contains \
  "UNSET_ENV=parent UNSET_TOOLS_ENV=parent mise env -s bash" \
  "unset UNSET_TOOLS_ENV"
assert \
  "UNSET_ENV=parent UNSET_TOOLS_ENV=parent mise env --json | jq -r 'has(\"UNSET_ENV\") or has(\"UNSET_TOOLS_ENV\")'" \
  "false"

# A forced refresh should apply the unset to an activated shell.
export UNSET_ENV=parent
export UNSET_TOOLS_ENV=parent
eval "$(mise hook-env -s bash --force)"
# shellcheck disable=SC2016
assert \
  'printf "%s|%s" "${UNSET_ENV-absent}" "${UNSET_TOOLS_ENV-absent}"' \
  "absent|absent"

# Removals must survive the full environment cache, not only initial resolution.
export UNSET_ENV=parent
export UNSET_TOOLS_ENV=parent
MISE_ENV_CACHE=true mise env -s bash >/dev/null
assert_contains "MISE_ENV_CACHE=true mise env -s bash" "unset UNSET_ENV"
assert_contains "MISE_ENV_CACHE=true mise env -s bash" "unset UNSET_TOOLS_ENV"

# Clearing the old managed value and applying an explicit removal should emit
# only one unset, even when a runtime override makes both phases remove it.
cat >mise.toml <<'EOF'
[env]
UNSET_ENV = "managed"
EOF
unset UNSET_ENV
unset_count=$(
  env -u __MISE_DIFF bash --noprofile --norc <<'BASH'
set -euo pipefail
eval "$(mise hook-env -s bash --force)"
export UNSET_ENV=runtime-override
cat >mise.toml <<'EOF'
[env]
UNSET_ENV = false
EOF
mise hook-env -s bash --force | grep -c '^unset UNSET_ENV$'
BASH
)
assert "printf '%s' '$unset_count'" "1"
