#!/usr/bin/env bash
# Starts the Academeet WhatsApp bridge on a Node version the openclaw CLI
# accepts. The bridge spawns `openclaw` as a child, so the child inherits this
# PATH — pinning here fixes both.
#
# openclaw self-updates, and a newer release can raise its Node floor (this
# happened: 2026.6.11 -> 2026.7.1-2 required >=22.22.3 and the bridge was on
# 22.21.1, so every turn failed with "something went wrong on my side").
set -euo pipefail

cd "$(dirname "$0")"

NVM_DIR="${NVM_DIR:-$HOME/Library/Application Support/Herd/config/nvm}"

# Highest installed version that satisfies openclaw's requirement.
pick_node() {
  local best=""
  for dir in "$NVM_DIR"/versions/node/*/bin; do
    [ -x "$dir/node" ] || continue
    local v
    v="$("$dir/node" --version 2>/dev/null | tr -d 'v')"
    # Need >= 22.22.3; prefer the newest available.
    if [ "$(printf '%s\n22.22.3\n' "$v" | sort -V | head -1)" = "22.22.3" ]; then
      best="$dir"
    fi
  done
  echo "$best"
}

NODE_BIN="$(pick_node)"

if [ -z "$NODE_BIN" ]; then
  echo "No installed Node satisfies openclaw (needs >=22.22.3). Try: nvm install 24" >&2
  exit 1
fi

export PATH="$NODE_BIN:$PATH"
echo "starting bridge on node $("$NODE_BIN/node" --version)"

# Refuse to start if openclaw itself can't run — otherwise every WhatsApp turn
# fails with a generic apology and the cause is only visible in the log.
if ! openclaw --version >/dev/null 2>&1; then
  echo "openclaw CLI is not runnable under this Node — check 'openclaw --version'" >&2
  exit 1
fi

exec node index.mjs
