#!/usr/bin/env bash
# Regression test for https://github.com/jdx/mise/discussions/11282
# Everything after a task name is forwarded to the task, so mise's own flags are not
# usable there (`mise run my:task --silent` fails with "unexpected word: --silent").
# Completion must therefore offer only the task's own flags after the task name, and a
# task flag that shares a name with a mise global (e.g. `--env`) must keep its own
# choices instead of being shadowed by the global.
#
# Requires usage >= 3.5.7, which stops the mounting CLI's flags from being inherited
# into mounted commands (jdx/usage#738). `latest` only reaches it once it clears the
# default 24h minimum_release_age, so opt out of the delay here.
export MISE_MINIMUM_RELEASE_AGE=0s

cat <<'EOF' >mise.toml
[tools]
"usage" = { version = "latest", os = ["linux", "macos"] }

[tasks.deploy]
usage = '''
flag "--env <name>" {
  choices "dev" "stage" "prod"
}
flag "--bump <type>" {
  choices "auto" "major" "minor" "patch"
}
flag "--output-dir <path>" {}
'''
run = 'echo deploy'
EOF

mise usage >./mise.usage.kdl

# only the task's own flags are offered after the task name — not mise globals like
# --cd/--env/--jobs/--quiet/--raw/--silent/--verbose/--yes
assert "mise exec -- usage complete-word --shell bash -f ./mise.usage.kdl -- mise run deploy --" "--bump
--env
--output-dir"

# same over the `tasks run` path, which additionally used to leak the `tasks` flags
# (--all, --extended, --global, --json, --local, --sort, …)
assert "mise exec -- usage complete-word --shell bash -f ./mise.usage.kdl -- mise tasks run deploy --" "--bump
--env
--output-dir"

# and over the naked path (`mise deploy` == `mise run deploy`)
assert "mise exec -- usage complete-word --shell bash -f ./mise.usage.kdl -- mise deploy --" "--bump
--env
--output-dir"

# --env collides with mise's global -E/--env: the task's choices must win (previously
# fell through to file completion, which is why renaming it to --environment "fixed" it)
assert "mise exec -- usage complete-word --shell bash -f ./mise.usage.kdl -- mise run deploy --env ''" "dev
stage
prod"

# a non-colliding task flag is unaffected
assert "mise exec -- usage complete-word --shell bash -f ./mise.usage.kdl -- mise run deploy --bump ''" "auto
major
minor
patch"

# mise's flags still complete *before* the task name
assert_contains "mise exec -- usage complete-word --shell bash -f ./mise.usage.kdl -- mise run --" "--silent"

# and a global before the task still parses, so the task's own flag values still
# complete after it (jdx/mise#10069 behavior is preserved)
assert "mise exec -- usage complete-word --shell bash -f ./mise.usage.kdl -- mise -C . run deploy --bump ''" "auto
major
minor
patch"

# a global whose name the task also uses keeps parsing as the global before the task,
# while the task's flag still owns the name after it
assert "mise exec -- usage complete-word --shell bash -f ./mise.usage.kdl -- mise --env dev run deploy --env ''" "dev
stage
prod"
