#!/bin/bash
# Resolve the canonical pinned Node binary for CTM + Wall-E and print its
# ABSOLUTE, immutable path on stdout. Exits non-zero (diagnostic on stderr) when
# the pinned version cannot be located.
#
# The pin lives in <repo-root>/.node-version (single source of truth). This
# resolver deliberately IGNORES ambient PATH so a Homebrew upgrade that repoints
# /opt/homebrew/bin/node, or a v26-first shell, can never select the wrong ABI
# for the shared native modules (better-sqlite3, sqlite-vec, tree-sitter).
#
# In a non-owner / shipped create-walle install the pin file is absent, so this
# degrades to the PATH `node` and never constrains other users.
set -euo pipefail

find_repo_root() {
  local dir="$1"
  while [[ "$dir" != "/" ]]; do
    if [[ -f "$dir/.node-version" && -d "$dir/wall-e" && -d "$dir/claude-task-manager" ]]; then
      printf '%s\n' "$dir"
      return 0
    fi
    dir="$(dirname "$dir")"
  done
  return 1
}

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
ROOT="$(find_repo_root "$SCRIPT_DIR" || true)"

if [[ -z "${ROOT:-}" ]]; then
  # No pin (non-owner / shipped context): fall back to PATH node.
  if command -v node >/dev/null 2>&1; then
    command -v node
    exit 0
  fi
  echo "[node-bin] no .node-version pin found and no node on PATH" >&2
  exit 1
fi

PIN="$(tr -d 'v[:space:]' < "$ROOT/.node-version")"
if [[ -z "$PIN" ]]; then
  echo "[node-bin] empty .node-version pin at $ROOT" >&2
  exit 1
fi

candidates=(
  "/opt/homebrew/Cellar/node/$PIN/bin/node"
  "/usr/local/Cellar/node/$PIN/bin/node"
  "$HOME/.fnm/node-versions/v$PIN/installation/bin/node"
  "$HOME/.local/share/fnm/node-versions/v$PIN/installation/bin/node"
  "$HOME/.nvm/versions/node/v$PIN/bin/node"
)

for c in "${candidates[@]}"; do
  if [[ -x "$c" ]]; then
    got="$("$c" --version 2>/dev/null | tr -d 'v[:space:]')"
    if [[ "$got" == "$PIN" ]]; then
      printf '%s\n' "$c"
      exit 0
    fi
  fi
done

# Last resort: the ambient `node` IF it already equals the pin. Covers system
# installs (nodejs.org pkg, distro packages) where node lives outside Cellar/
# fnm/nvm. We still gate on an exact version match, so this never selects a
# mismatched ABI — it just avoids a false "not found" for non-manager installs.
if command -v node >/dev/null 2>&1; then
  got="$(node --version 2>/dev/null | tr -d 'v[:space:]')"
  if [[ "$got" == "$PIN" ]]; then
    command -v node
    exit 0
  fi
fi

{
  echo "[node-bin] Pinned Node v$PIN not found. CTM + Wall-E require it so the"
  echo "  shared native modules (better-sqlite3, sqlite-vec, tree-sitter) keep a"
  echo "  stable ABI. Install it, e.g.:"
  echo "    brew install node@${PIN%%.*}     # or: fnm install $PIN / nvm install $PIN"
  echo "  Looked in:"
  printf '    %s\n' "${candidates[@]}"
} >&2
exit 1
