#!/usr/bin/env bash

# Test that a `[tasks.<name>]` TOML block merges metadata (env, description,
# dir, aliases, depends, etc.) into an auto-discovered file task of the same
# name. Previously the file task silently won and the TOML block was discarded.
# See jdx/mise#8673 (comment by calebhearth).

mkdir -p .mise/tasks

cat <<'SCRIPT' >.mise/tasks/echo-env
#!/usr/bin/env bash
echo "TASK_VAR=${TASK_VAR:-<unset>}"
echo "FROM_DOTENV=${FROM_DOTENV:-<unset>}"
SCRIPT
chmod +x .mise/tasks/echo-env

cat <<'EOF' >.env
FROM_DOTENV=hello-from-dotenv
EOF

cat <<'EOF' >mise.toml
[tasks.echo-env]
description = "Echo the configured TASK_VAR"
env = { TASK_VAR = "from-toml", _.file = ".env" }
EOF

# TOML env merges into the file task.
assert_contains "mise run echo-env" "TASK_VAR=from-toml"

# Path-based directives (like `_.file`) from the overlay must resolve
# relative to the TOML file, not the file task's script path.
assert_contains "mise run echo-env" "FROM_DOTENV=hello-from-dotenv"

# TOML description merges in and is surfaced through `tasks ls`.
assert_contains "mise tasks ls" "Echo the configured TASK_VAR"

# And through `tasks ls --json` with the expected env directive.
assert_contains "mise tasks ls --json" '"description": "Echo the configured TASK_VAR"'
assert_contains "mise tasks ls --json" '"TASK_VAR=from-toml"'

# Overlay deps (including usage-arg refs) survive re-rendering. The overlay
# adds a `depends` with a `{{usage.app}}` template that must resolve when
# the parent task receives `--app=demo` from the CLI.
cat <<'SCRIPT' >.mise/tasks/parent
#!/usr/bin/env bash
#USAGE flag "--app <app>"
echo "parent app=$usage_app"
SCRIPT
chmod +x .mise/tasks/parent

cat <<'SCRIPT' >.mise/tasks/child
#!/usr/bin/env bash
echo "child got: $*"
SCRIPT
chmod +x .mise/tasks/child

cat <<'EOF' >>mise.toml

[tasks.parent]
depends = ["child {{usage.app}}"]
EOF

assert_contains "mise run parent --app demo" "child got: demo"
assert_contains "mise run parent --app demo" "parent app=demo"
