#!/usr/bin/env bash
#
#   BrainBoxx installer
#   ───────────────────
#   curl -fsSL https://get.brainboxx.app | bash
#   curl -fsSL https://get.brainboxx.app | bash -s -- --pair A2E5-XFV4-Y7U9
#
#   Installs the `bb` agent on this machine (macOS or Linux), sets it to start
#   on boot, and — if given a pairing code — connects it to your phone.
#
#   Env overrides (advanced):
#     BB_DIST_URL   where to fetch bb from        (default https://get.brainboxx.app)
#     BB_RELAY      relay websocket url            (default wss://relay.brainboxx.app/ws)
#     BB_BOX        folder this machine exposes    (default $HOME/BrainBoxx)
#     BB_HOME       install location               (default $HOME/.brainboxx)
#     BB_PREFIX     where the `bb` command goes     (default /usr/local, else ~/.local)
#
set -euo pipefail

# ── config ───────────────────────────────────────────────────────────────────
BB_DIST_URL="${BB_DIST_URL:-https://get.brainboxx.app}"
BB_RELAY="${BB_RELAY:-wss://relay.brainboxx.app/ws}"
BB_BOX="${BB_BOX:-$HOME/BrainBoxx}"
BB_HOME="${BB_HOME:-$HOME/.brainboxx}"
PAIR_CODE=""

while [ $# -gt 0 ]; do
  case "$1" in
    --pair)  PAIR_CODE="${2:-}"; shift 2 ;;
    --relay) BB_RELAY="${2:-}";  shift 2 ;;
    --box)   BB_BOX="${2:-}";    shift 2 ;;
    -h|--help)
      grep '^#' "$0" | sed 's/^# \{0,1\}//' | sed '/!\/usr\/bin/d'; exit 0 ;;
    *) echo "bb-install: unknown option: $1" >&2; exit 1 ;;
  esac
done

# ── pretty output ────────────────────────────────────────────────────────────
if [ -t 1 ] && [ -z "${NO_COLOR:-}" ]; then
  BOLD=$(printf '\033[1m'); DIM=$(printf '\033[2m'); RESET=$(printf '\033[0m')
  CYAN=$(printf '\033[36m'); GREEN=$(printf '\033[32m'); RED=$(printf '\033[31m')
else
  BOLD=; DIM=; RESET=; CYAN=; GREEN=; RED=
fi
step() { printf '%s→%s %s\n' "$CYAN" "$RESET" "$1"; }
ok()   { printf '%s✓%s %s\n' "$GREEN" "$RESET" "$1"; }
die()  { printf '%s✗ %s%s\n' "$RED" "$1" "$RESET" >&2; exit 1; }

banner() {
  printf '\n%s' "$BOLD"
  printf '  ┌───────────────────────┐\n'
  printf '  │   B R A I N B O X X   │\n'
  printf '  └───────────────────────┘%s\n' "$RESET"
  printf '  %sthe box that holds your brains%s\n\n' "$DIM" "$RESET"
}

trap 'die "install failed — see the last line above. Nothing was left running."' ERR

# ── detect platform ──────────────────────────────────────────────────────────
UNAME_S="$(uname -s)"
case "$UNAME_S" in
  Darwin) PLATFORM=macos ;;
  Linux)  PLATFORM=linux ;;
  *) die "unsupported OS: $UNAME_S (BrainBoxx runs on macOS and Linux)" ;;
esac

# sudo only if we're not root and it's available
if [ "$(id -u)" -eq 0 ]; then SUDO=""; elif command -v sudo >/dev/null 2>&1; then SUDO="sudo"; else SUDO=""; fi

# ── prerequisites: Node ≥ 18 and a C++ toolchain (node-pty compiles) ─────────
node_major() { node -p 'process.versions.node.split(".")[0]' 2>/dev/null || echo 0; }
have_node()  { command -v node >/dev/null 2>&1 && [ "$(node_major)" -ge 18 ]; }

ensure_node() {
  have_node && { ok "Node $(node -v) present"; return; }
  step "installing Node.js…"
  if [ "$PLATFORM" = macos ]; then
    if command -v brew >/dev/null 2>&1; then brew install node >/dev/null
    else die "Node ≥18 is required. Install it (e.g. 'brew install node') and re-run."; fi
  else
    if command -v apt-get >/dev/null 2>&1; then
      curl -fsSL https://deb.nodesource.com/setup_20.x | $SUDO -E bash - >/dev/null
      $SUDO apt-get install -y nodejs >/dev/null
    elif command -v dnf >/dev/null 2>&1; then $SUDO dnf install -y nodejs >/dev/null
    else die "Node ≥18 is required and no supported package manager was found. Install Node and re-run."; fi
  fi
  have_node || die "Node install did not produce Node ≥18."
  ok "Node $(node -v) installed"
}

ensure_build_tools() {
  if [ "$PLATFORM" = macos ]; then
    xcode-select -p >/dev/null 2>&1 || die "Xcode Command Line Tools are required (run 'xcode-select --install', then re-run)."
  else
    if command -v apt-get >/dev/null 2>&1 && ! command -v g++ >/dev/null 2>&1; then
      step "installing build tools…"
      $SUDO apt-get update -y >/dev/null
      $SUDO apt-get install -y python3 make g++ ca-certificates >/dev/null
    fi
  fi
  ok "build toolchain ready"
}

# ── fetch + install bb ───────────────────────────────────────────────────────
install_bb() {
  step "downloading bb…"
  TMP="$(mktemp -d)"; trap 'rm -rf "$TMP"' EXIT
  curl -fsSL "$BB_DIST_URL/bb-latest.tar.gz" -o "$TMP/bb.tar.gz" \
    || die "could not download bb from $BB_DIST_URL"
  rm -rf "$BB_HOME/app"; mkdir -p "$BB_HOME/app"
  tar -xzf "$TMP/bb.tar.gz" -C "$BB_HOME/app"
  ok "unpacked to $BB_HOME/app"

  step "building (this compiles the terminal engine)…"
  ( cd "$BB_HOME/app" && npm install --omit=dev --no-audit --no-fund >/dev/null )
  ok "dependencies built"

  # put `bb` on PATH — prefer a writable system bin, fall back to ~/.local/bin
  local entry="$BB_HOME/app/index.js"; chmod +x "$entry"
  local prefix="${BB_PREFIX:-/usr/local}"
  if [ -w "$prefix/bin" ] || { [ -n "$SUDO" ] && [ -d "$prefix/bin" ]; }; then
    ${SUDO} ln -sf "$entry" "$prefix/bin/bb"; BB_BIN="$prefix/bin/bb"
  else
    mkdir -p "$HOME/.local/bin"; ln -sf "$entry" "$HOME/.local/bin/bb"; BB_BIN="$HOME/.local/bin/bb"
    case ":$PATH:" in *":$HOME/.local/bin:"*) : ;; *) NEEDS_PATH="$HOME/.local/bin" ;; esac
  fi
  ok "installed the ${BOLD}bb${RESET} command → $BB_BIN"
}

# ── pair + autostart ─────────────────────────────────────────────────────────
configure_bb() {
  mkdir -p "$BB_BOX"
  step "pairing this machine…"
  if [ -n "$PAIR_CODE" ]; then
    "$BB_BIN" pair --code "$PAIR_CODE" --relay "$BB_RELAY" --box "$BB_BOX"
    ok "paired with code $PAIR_CODE"
  else
    "$BB_BIN" pair --relay "$BB_RELAY" --box "$BB_BOX"
  fi
  step "enabling start-on-boot…"
  "$BB_BIN" install
  ok "bb is running and will survive reboot"
}

# ── run ──────────────────────────────────────────────────────────────────────
banner
step "installing on ${BOLD}${PLATFORM}${RESET} (box → $BB_BOX)"
ensure_node
ensure_build_tools
install_bb
configure_bb
trap - ERR

printf '\n%s✓ BrainBoxx is live on this machine.%s\n' "$GREEN$BOLD" "$RESET"
if [ -z "$PAIR_CODE" ]; then
  printf '  Open the app and pair using the code shown by:  %sbb pair%s\n' "$BOLD" "$RESET"
fi
if [ -n "${NEEDS_PATH:-}" ]; then
  # shellcheck disable=SC2016  # literal $PATH is intentional — user pastes this into their shell
  printf '  %sAdd to your shell so `bb` is found:%s  export PATH="%s:$PATH"\n' "$DIM" "$RESET" "$NEEDS_PATH"
fi
printf '\n'
