#!/usr/bin/env bash
# Installs Node.js 22 into DailyMeals/.toolchain (no Homebrew required).
set -euo pipefail

ROOT="$(cd "$(dirname "$0")/.." && pwd)"
VERSION="22.22.0"
OS="$(uname -s | tr '[:upper:]' '[:lower:]')"
ARCH="$(uname -m)"
case "$ARCH" in
  arm64|aarch64) ARCH="arm64" ;;
  x86_64|amd64) ARCH="x64" ;;
  *) echo "Unsupported architecture: $ARCH" >&2; exit 1 ;;
esac

DIR_NAME="node-v${VERSION}-${OS}-${ARCH}"
TARGET="$ROOT/.toolchain/$DIR_NAME"

if [[ -x "$TARGET/bin/npm" ]]; then
  echo "Node.js already installed: $TARGET"
  exit 0
fi

# Reuse FA_WEB toolchain when present (same machine, same arch).
FA_WEB_TOOLCHAIN="$ROOT/../FA_WEB/.toolchain/$DIR_NAME"
if [[ -d "$FA_WEB_TOOLCHAIN" ]]; then
  mkdir -p "$ROOT/.toolchain"
  ln -sfn "$FA_WEB_TOOLCHAIN" "$TARGET"
  echo "Linked toolchain from FA_WEB: $TARGET"
  exit 0
fi

mkdir -p "$ROOT/.toolchain"
TARBALL="node-v${VERSION}-${OS}-${ARCH}.tar.gz"
URL="https://nodejs.org/dist/v${VERSION}/${TARBALL}"
echo "Downloading $URL ..."
curl -fsSL "$URL" -o "/tmp/${TARBALL}"
tar -xzf "/tmp/${TARBALL}" -C "$ROOT/.toolchain"
rm -f "/tmp/${TARBALL}"
echo "Installed: $TARGET"
echo "Use: $ROOT/scripts/npm --version"
