#!/usr/bin/env bash
# factory-dispatch.sh decides where a seat dispatch executes at the placement seam.
# A wrong answer either runs model compute on the laptop or bounces a dispatch between
# hosts, so every branch is asserted consistently.
set -euo pipefail

here="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
shim_src="${here}/../../../harness/tools/factory-dispatch.sh"
[[ -f "$shim_src" ]] || { echo "missing shim: $shim_src" >&2; exit 1; }

work="$(mktemp -d)"
trap 'rm -rf "$work"' EXIT

mkdir -p "$work/modules/harness/tools" "$work/modules/workstation/claude/lib" "$work/path" "$work/ws"
cp "$shim_src" "$work/modules/harness/tools/factory-dispatch.sh"
chmod +x "$work/modules/harness/tools/factory-dispatch.sh"
printf '' > "$work/modules/workstation/claude/lib/buildbox-registry.mjs"

cat > "$work/path/run-remote" <<'EOF'
#!/usr/bin/env bash
echo "SUBMIT $*"
EOF
chmod +x "$work/path/run-remote"

# Stands in for both `node <registry> self` (exit 4 = not a registry host, 0 = is one)
# and `node <registry> hosts --order build`.
cat > "$work/path/node" <<'EOF'
#!/usr/bin/env bash
case "${2:-}" in
  self)  exit "${FAKE_SELF_CODE:-4}" ;;
  hosts) if [[ "${FAKE_HOSTS:-debian1}" == "none" ]]; then exit 3; fi
         echo "${FAKE_HOSTS:-debian1}"; exit 0 ;;
esac
echo "LOCAL $*"
EOF
chmod +x "$work/path/node"

cat > "$work/path/ca.sh" <<'EOF'
#!/usr/bin/env bash
echo "LOCAL $*"
EOF
chmod +x "$work/path/ca.sh"

run_shim() {
  env PATH="$work/path:/usr/bin:/bin" HOME="$work" FD_CA_SH="$work/path/ca.sh" \
    "$@" bash "$work/modules/harness/tools/factory-dispatch.sh" "${SHIM_ARGS[@]}" 2>&1 || true
}

expect() {
  local label="$1" want="$2" got="$3"
  if [[ "$got" != *"$want"* ]]; then
    echo "FAIL: $label — expected to contain '$want', got: $got" >&2
    exit 1
  fi
  echo "ok: $label"
}

SHIM_ARGS=(--task t1 --workspace "$work/ws" --trust p --model m)
expect "laptop places a dispatch on a buildbox" \
  "SUBMIT launch --wait -- modules/harness/tools/factory-dispatch.sh --task t1 --workspace ${work}/ws --trust p --model m" \
  "$(run_shim)"

# Each case that actually reaches ca.sh gets its own workspace: factory-dispatch.sh's
# own per-task budget cap (MAX_PER_TASK=2) would otherwise trip across these placement
# cases, which is a different mechanism than the one under test here.
mkdir -p "$work/ws-placed" "$work/ws-registry" "$work/ws-killswitch"

SHIM_ARGS=(--task t1 --workspace "$work/ws-placed" --trust p --model m)
expect "a placed dispatch never re-places itself" "LOCAL" "$(run_shim RUN_REMOTE_PLACED=1)"

SHIM_ARGS=(--task t1 --workspace "$work/ws-registry" --trust p --model m)
expect "a registry host dispatches locally" "LOCAL" "$(run_shim FAKE_SELF_CODE=0)"

SHIM_ARGS=(--task t1 --workspace "$work/ws-killswitch" --trust p --model m)
expect "documented kill switch runs here" "LOCAL" "$(run_shim FACTORY_PLACEMENT=local)"

SHIM_ARGS=(--task t1 --workspace "$work/ws" --trust p --model m)
out="$(run_shim FAKE_HOSTS=none)"
expect "no reachable box fails closed" "no reachable buildbox" "$out"
if [[ "$out" == *"LOCAL"* ]]; then
  echo "FAIL: fell back to dispatching on the laptop" >&2
  exit 1
fi
echo "ok: no reachable box does not fall back to local"

SHIM_ARGS=(--task t1 --workspace "$work/ws" --trust p --model m)
out="$(run_shim FAKE_SELF_CODE=3)"
expect "unreadable registry fails closed" "unreadable or invalid" "$out"
if [[ "$out" == *"LOCAL"* ]]; then
  echo "FAIL: indeterminate identity fell back to local dispatch" >&2
  exit 1
fi
echo "ok: indeterminate identity does not fall back to local"

# run-remote joins its trailing argv into one shell command line, so the shim must
# quote each argument; proof is a round-trip through the shell, not a literal match.
SHIM_ARGS=(--task t1 --workspace "$work/ws" --trust p "--note=two words" 'weird$(touch pwned)')
submitted="$(run_shim)"
submitted="${submitted#SUBMIT launch --wait -- }"

# On the box the placed run finds the real placement shim at this same relative path;
# stand in for "already executed there" by swapping it for an argv-echoing stub now
# that the submission itself has been captured.
cat > "$work/modules/harness/tools/factory-dispatch.sh" <<'EOF'
#!/usr/bin/env bash
for a in "$@"; do printf 'ARG[%s]\n' "$a"; done
EOF
chmod +x "$work/modules/harness/tools/factory-dispatch.sh"

roundtrip="$(cd "$work" && env PATH="$work/path:/usr/bin:/bin" bash -c "$submitted")"
expect "task slug survives" "ARG[--task]" "$roundtrip"
expect "an argument containing a space is not split" "ARG[--note=two words]" "$roundtrip"
expect "shell metacharacters are inert" 'ARG[weird$(touch pwned)]' "$roundtrip"
[[ -e "$work/pwned" || -e ./pwned ]] && { echo "FAIL: argument was evaluated by the shell" >&2; exit 1; }
echo "ok: submitted command line round-trips to the original argv"

echo "all factory-dispatch placement cases passed"
