#!/usr/bin/env sh
# DBAOps Sovereign™ — Install OS prerequisites (macOS Homebrew / Linux apt + NodeSource)
# Usage: ./scripts/install-requirements.sh [--yes] [--with-docker]
# See: docs/INSTALL-REQUIREMENTS.md

set -e
YES=0
WITH_DOCKER=0
for arg in "$@"; do
  case "$arg" in
    --yes|-y) YES=1 ;;
    --with-docker) WITH_DOCKER=1 ;;
  esac
done

die() { echo "ERROR: $*" >&2; exit 1; }

need_sudo() {
  if [ "$(id -u)" -eq 0 ]; then return 1; fi
  if [ "$YES" = 1 ]; then sudo -n true 2>/dev/null || die "sudo required non-interactively; run without --yes or configure sudo"
  else sudo true; fi
}

install_macos_brew() {
  command -v brew >/dev/null 2>&1 || die "Install Homebrew first: https://brew.sh"
  echo "DBAOps Sovereign™ — macOS: installing Node via Homebrew…"
  brew install node
}

install_linux_apt() {
  need_sudo
  echo "DBAOps Sovereign™ — Linux (apt): Node.js 20.x via NodeSource…"
  if [ "$YES" != 1 ]; then
    echo "This will use sudo. Continue? [y/N]"
    read -r r
    case "$r" in y|Y|yes|YES) ;; *) die "Aborted" ;; esac
  fi
  sudo apt-get update -qq
  sudo apt-get install -y ca-certificates curl gnupg
  curl -fsSL https://deb.nodesource.com/setup_20.x | sudo -E bash -
  sudo apt-get install -y nodejs
}

node_ok() {
  command -v node >/dev/null 2>&1 || return 1
  maj=$(node -p "process.versions.node.split('.')[0]" 2>/dev/null || echo 0)
  [ "${maj:-0}" -ge 18 ]
}

if node_ok; then
  echo "Node.js OK ($(node -v))."
else
  case "$(uname -s)" in
    Darwin) install_macos_brew ;;
    Linux)
      if command -v apt-get >/dev/null 2>&1; then
        install_linux_apt
      else
        die "Unsupported Linux package manager. Install Node 18+ manually: https://nodejs.org/ — see docs/INSTALL-REQUIREMENTS.md"
      fi
      ;;
    *) die "Unsupported OS. Install Node 18+ manually: https://nodejs.org/" ;;
  esac
fi

if ! node_ok; then
  die "Node 18+ still not available. Open a new terminal or check PATH."
fi

# Docker only (when Node was already satisfied)
if [ "$WITH_DOCKER" = 1 ]; then
  case "$(uname -s)" in
    Darwin)
      command -v brew >/dev/null 2>&1 || die "Install Homebrew first: https://brew.sh"
      if command -v docker >/dev/null 2>&1; then
        echo "Docker already on PATH."
      else
        echo "Installing Docker Desktop (cask)…"
        brew install --cask docker || echo "Install manually: https://www.docker.com/products/docker-desktop/"
      fi
      ;;
    Linux)
      if command -v apt-get >/dev/null 2>&1; then
        need_sudo
        sudo apt-get install -y docker.io
        echo "Optional: sudo usermod -aG docker \"\$USER\" then re-login."
      else
        echo "Install Docker using your distro packages or https://docs.docker.com/engine/install/"
      fi
      ;;
  esac
fi

echo "Done. Next from repo root:"
echo "  npm run setup"
echo "  npm start"
echo "Docs: docs/INSTALL-CROSS-PLATFORM.md"
