#!/usr/bin/env bash

# Test that remote git tasks don't produce spurious "failed to parse task file"
# warnings when invoked with arguments (which triggers usage spec parsing
# before remote files are fetched).
# Reproduces: https://github.com/jdx/mise/discussions/8973

#################################################################################
# Setup - start local git HTTP server
#################################################################################

PORT_FILE="$TMPDIR/mise_git_http_port"
READY_FILE="$TMPDIR/mise_git_http_ready"
INFO_FILE="$TMPDIR/mise_git_http_info"

rm -f "$PORT_FILE" "$READY_FILE" "$INFO_FILE"

MISE_GIT_HTTP_PORT_FILE="$PORT_FILE" \
  MISE_GIT_HTTP_READY_FILE="$READY_FILE" \
  MISE_GIT_HTTP_INFO_FILE="$INFO_FILE" \
  python3 "${TEST_ROOT}/helpers/scripts/git_http_backend_server.py" 0 &
SERVER_PID=$!

wait_for_server() {
  local max_attempts=30
  local attempt=1
  while [ $attempt -le $max_attempts ]; do
    if [ -f "$READY_FILE" ] && [ -f "$PORT_FILE" ]; then
      return 0
    fi
    sleep 1
    attempt=$((attempt + 1))
  done
  echo "ERROR: Git HTTP server failed to start within 30 seconds"
  kill "$SERVER_PID" 2>/dev/null || true
  exit 1
}

wait_for_server
SERVER_PORT=$(cat "$PORT_FILE")
LOCAL_GIT_URL="http://localhost:${SERVER_PORT}/repo.git"

git init

cleanup() {
  kill "$SERVER_PID" 2>/dev/null || true
  rm -f "$PORT_FILE" "$READY_FILE" "$INFO_FILE"
}
trap cleanup EXIT

#################################################################################
# Test: remote task with args should not emit usage parse warnings
#################################################################################

cat <<EOF >mise.toml
[tasks.remote_lint]
file = "git::${LOCAL_GIT_URL}//xtasks/lint/ripgrep?ref=v2025.1.17"
EOF

# Run the remote task with extra arguments (-- triggers parse_usage_values_from_task
# before remote files are fetched) and capture both stdout and stderr
output=$(mise run remote_lint -- extraarg 2>&1)
exit_code=$?

if [[ $exit_code -ne 0 ]]; then
  fail "mise run remote_lint failed with exit code $exit_code: $output"
fi
ok "remote task with args ran successfully"

# There should be no "failed to parse task file" warning
if echo "$output" | grep -q "failed to parse task file"; then
  fail "Unexpected warning about failed to parse task file in output: $output"
fi
ok "No spurious 'failed to parse task file' warning for remote task with args"
