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

claude_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
repo_root="$(cd "${claude_root}/../../.." && pwd)"
launcher="${claude_root}/bin/runplan"
temp_dir="$(mktemp -d)"
trap 'rm -rf "$temp_dir"' EXIT

fail() {
  printf 'FAIL %s\n' "$*" >&2
  exit 1
}

assert_failure() {
  local expected_message="$1"
  shift
  local output rc=0
  output="$("$@" 2>&1)" || rc=$?
  [[ "$rc" -eq 2 ]] || fail "expected rc=2, got rc=${rc}: ${output}"
  grep -Fq "$expected_message" <<<"$output" || fail "missing error '${expected_message}': ${output}"
}

home_dir="${temp_dir}/home"
mkdir -p "$home_dir"
HOME="$home_dir" "$repo_root/bin/deckctl" sync apply claude
[[ -L "$home_dir/.claude/bin" ]] || fail 'deckctl did not install the Claude bin symlink'
[[ "$(readlink -f "$home_dir/.claude/bin/runplan")" == "$(readlink -f "$launcher")" ]] \
  || fail 'installed runplan does not resolve to the workstation launcher'
[[ "$(PATH="$home_dir/.claude/bin:$PATH" command -v runplan)" == "$home_dir/.claude/bin/runplan" ]] \
  || fail 'installed runplan is not selected from PATH'

mkdir -p "$home_dir/.local/bin"
cat >"$home_dir/.local/bin/runplan-tui" <<'EOF'
#!/usr/bin/env bash
printf '%s\0' "$PWD" "$@" >"$TUI_ARGS_FILE"
EOF
chmod +x "$home_dir/.local/bin/runplan-tui"
tui_args_file="$temp_dir/tui-args"
other_repo="$temp_dir/other-repo"
mkdir -p "$other_repo"
for entrypoint in '' 'tui' '-tui' '--tui'; do
  (
    cd "$other_repo"
    if [[ -n "$entrypoint" ]]; then
      TUI_ARGS_FILE="$tui_args_file" HOME="$home_dir" HARNESS_HOME="$temp_dir/no-engine" \
        "$launcher" "$entrypoint"
    else
      TUI_ARGS_FILE="$tui_args_file" HOME="$home_dir" HARNESS_HOME="$temp_dir/no-engine" \
        "$launcher"
    fi
  )
  mapfile -d '' -t tui_args <"$tui_args_file"
  [[ "${tui_args[0]}" == "$other_repo" && "${#tui_args[@]}" -eq 1 ]] \
    || fail "TUI entrypoint '${entrypoint:-<zero args>}' changed cwd or arguments"
done

TUI_ARGS_FILE="$tui_args_file" HOME="$home_dir" HARNESS_HOME="$temp_dir/no-engine" \
  "$launcher" tui alpha 'two words' --flag
mapfile -d '' -t tui_args <"$tui_args_file"
[[ "${tui_args[*]}" == "$PWD alpha two words --flag" && "${#tui_args[@]}" -eq 4 ]] \
  || fail 'TUI arguments changed'

rm "$home_dir/.local/bin/runplan-tui"
for entrypoint in '' 'tui' '-tui' '--tui'; do
  if [[ -n "$entrypoint" ]]; then
    assert_failure 'missing TUI binary' env HOME="$home_dir" HARNESS_HOME="$temp_dir/no-engine" \
      "$launcher" "$entrypoint"
  else
    assert_failure 'missing TUI binary' env HOME="$home_dir" HARNESS_HOME="$temp_dir/no-engine" \
      "$launcher"
  fi
done

harness_home="$temp_dir/harness"
bundle="$harness_home/engine/versions/2.4.6"
mkdir -p "$bundle/v2/bin"
printf '%s\n' '2.4.6' >"$harness_home/engine/CURRENT"
printf '%s\n' 'fixture-sha' >"$bundle/ENGINE_SHA"
cat >"$bundle/v2/bin/runplan.js" <<'EOF'
'use strict';
if (process.argv[2] === '--help' || process.argv[2] === '-h') {
  process.stdout.write('v2 help: --account --preset --concurrency\n');
  process.exit(0);
}
require('node:fs').writeFileSync(process.env.ARGS_FILE, JSON.stringify(process.argv.slice(2)));
EOF
args_file="$temp_dir/args.json"
for help_flag in --help -h; do
  help_output="$(HARNESS_HOME="$harness_home" "$launcher" "$help_flag")"
  [[ "$help_output" == 'v2 help: --account --preset --concurrency' ]] \
    || fail "${help_flag} did not print v2 engine help"
  [[ ! -e "$args_file" ]] || fail "${help_flag} unexpectedly launched TUI or altered argv"
done

ARGS_FILE="$args_file" HARNESS_HOME="$harness_home" \
  "$launcher" 'demo slug' 'two words' --account 'zync team' --preset 'codex hi' \
  --concurrency 4 --foreground
node -e '
  const assert = require("node:assert/strict");
  const fs = require("node:fs");
  assert.deepEqual(JSON.parse(fs.readFileSync(process.argv[1], "utf8")), [
    "demo slug", "two words", "--account", "zync team", "--preset", "codex hi",
    "--concurrency", "4", "--foreground",
  ]);
' "$args_file"

rm "$harness_home/engine/CURRENT"
assert_failure 'released engine pointer missing' env HARNESS_HOME="$harness_home" "$launcher" demo

printf '%s\n' '2.4.6' >"$harness_home/engine/CURRENT"
rm "$bundle/ENGINE_SHA"
rm -f "$args_file"
assert_failure 'invalid engine bundle' env ARGS_FILE="$args_file" HARNESS_HOME="$harness_home" "$launcher" demo
[[ ! -e "$args_file" ]] || fail 'v2 entrypoint launched without ENGINE_SHA'

printf '%s\n' 'fixture-sha' >"$bundle/ENGINE_SHA"
rm "$bundle/v2/bin/runplan.js"
mkdir -p "$bundle/bin" "$bundle/src"
cat >"$bundle/bin/runplan" <<'EOF'
#!/usr/bin/env bash
printf legacy >"$LEGACY_MARKER"
EOF
chmod +x "$bundle/bin/runplan"
cat >"$bundle/src/runner.js" <<'EOF'
require('node:fs').writeFileSync(process.env.LEGACY_MARKER, 'legacy');
EOF
legacy_marker="$temp_dir/legacy-launched"
assert_failure 'missing v2/bin/runplan.js' env LEGACY_MARKER="$legacy_marker" HARNESS_HOME="$harness_home" "$launcher" demo
[[ ! -e "$legacy_marker" ]] || fail 'launcher fell back to a legacy engine path'

printf 'PASS workstation runplan launches only the released v2 engine\n'
