#!/usr/bin/env bash

cat <<EOF >mise.toml
[tasks.child]
tools = { tiny = "1" }
run = "rtx-tiny"

[tasks.parent]
run = [{ task = "child" }]

[tasks.templated-child]
tools = { tiny = "2" }
run = "rtx-tiny"

[tasks.templated-parent]
env = { CHILD = "templated-child" }
run = [{ task = "{{ env.CHILD }}" }]
EOF

# A task referenced from a run entry is resolved at execution time, but its
# task-only tools must still be installed before the injected task starts.
assert "mise run parent" "rtx-tiny: v1.1.0 args:"

# Runtime-rendered task references take the same late installation path.
assert "mise run templated-parent" "rtx-tiny: v2.1.0 args:"

cat <<EOF >mise.toml
[tasks.install-failure]
tools = { dummy = "other-dummy" }
run = "echo should-not-run"

[tasks.install-failure-parent]
run = [{ task = "install-failure" }]

[tasks.install-sibling]
run = "sleep 0.2; echo sibling-completed"
EOF

# A failed late install is reported as a task failure and does not bypass
# completion of already-running siblings in continue-on-error mode.
assert_fail_contains \
  "mise run --continue-on-error install-failure-parent ::: install-sibling 2>&1" \
  "sibling-completed"

cat <<EOF >mise.toml
[tasks.install-one]
tools = { dummy = "1.0.0" }
run = "dummy"

[tasks.install-two]
tools = { dummy = "2.0.0" }
run = "dummy"

[tasks.install-one-parent]
run = [{ task = "install-one" }]

[tasks.install-two-parent]
run = [{ task = "install-two" }]
EOF

# Concurrent parents inject both children at once, so the overlap marker proves
# deferred installs share the task scheduler's jobs limit.
install_gate="$HOME/deferred-install-gate"
assert_contains \
  "DUMMY_INSTALL_GATE_DIR='$install_gate' mise run --jobs 1 install-one-parent ::: install-two-parent" \
  "This is Dummy"
assert_fail "test -e '$install_gate.overlap'"

cat <<EOF >mise.toml
[tasks.a]
tools = { tiny = "1" }
run = "rtx-tiny"
[tasks.b]
depends = ["a"]
tools = { tiny = "2" }
run = "rtx-tiny"
EOF

assert "mise run b" "rtx-tiny: v1.1.0 args:
rtx-tiny: v2.1.0 args:"

# Task tool maps must preserve structured options. The needs-dummy installer
# fails unless its `depends` entry causes dummy to be installed first.
cat <<EOF >mise.toml
[tasks.structured-options]
tools = { needs-dummy = { version = "1.0.0", depends = ["dummy"] }, dummy = "2.0.0" }
run = "needs-dummy"
EOF

rm -rf "$MISE_DATA_DIR/installs/dummy"
rm -rf "$MISE_DATA_DIR/installs/needs-dummy"

assert "MISE_JOBS=1 mise run structured-options" "needs-dummy v1.0.0"

cat <<EOF >mise.toml
[tasks.selector]
tools = { tiny = { prefix = "1" } }
run = "rtx-tiny"
EOF

assert "mise run selector" "rtx-tiny: v1.1.0 args:"
