#!/bin/bash
#
# Zephex terminal CLI installer — https://zephex.dev/install.sh
#
# Terminal / Mode 2 only (no editor MCP, no AI agent). Same tools as web terminal.
# Bundles Node when needed — users never install Node separately.
#
# Usage:
#   curl -fsSL https://zephex.dev/install.sh | bash
#   ZEPHEX_VERSION=2.5.8 curl -fsSL https://zephex.dev/install.sh | bash
#   curl -fsSL https://zephex.dev/cli/install.sh | bash   (alias)
#
# Windows: irm https://zephex.dev/install.ps1 | iex
# Editor MCP (separate): zephex connect --cursor
#
# Env: ZEPHEX_HOME, NODE_VERSION (default 22.14.0), ZEPHEX_VERSION (default latest),
#      ZEPHEX_INSTALL_DRY_RUN=1 (print plan only)

set -euo pipefail

ZEPHEX_HOME="${ZEPHEX_HOME:-$HOME/.zephex}"
BIN_DIR="$ZEPHEX_HOME/bin"
NODE_ROOT="$ZEPHEX_HOME/node"
NPM_PREFIX="$ZEPHEX_HOME/npm-global"
NODE_VERSION="${NODE_VERSION:-22.14.0}"
ZEPHEX_VERSION="${ZEPHEX_VERSION:-}"
INSTALLER_MARKER="# >>> zephex installer >>>"
DRY_RUN="${ZEPHEX_INSTALL_DRY_RUN:-}"

DOWNLOADER=""
if command -v curl >/dev/null 2>&1; then
  DOWNLOADER="curl"
elif command -v wget >/dev/null 2>&1; then
  DOWNLOADER="wget"
else
  echo "Error: curl or wget is required." >&2
  exit 1
fi

download_file() {
  local url="$1" output="$2"
  if [ "$DOWNLOADER" = "curl" ]; then
    curl -fsSL -o "$output" "$url"
  else
    wget -q -O "$output" "$url"
  fi
}

node_ok() {
  command -v node >/dev/null 2>&1 || return 1
  node -e 'const v=process.versions.node.split(".").map(Number); process.exit(v[0]>22||(v[0]===22&&v[1]>5)||(v[0]===22&&v[1]===5&&v[2]>=0)?0:1)' 2>/dev/null
}

case "$(uname -s)" in
  Darwin) os="darwin" ;;
  Linux) os="linux" ;;
  *) echo "Unsupported OS: $(uname -s) (macOS and Linux only — Windows: install.ps1)" >&2
     exit 1 ;;
esac

case "$(uname -m)" in
  x86_64|amd64) arch="x64" ;;
  arm64|aarch64) arch="arm64" ;;
  *) echo "Unsupported architecture: $(uname -m)" >&2; exit 1 ;;
esac

platform="${os}-${arch}"
mkdir -p "$BIN_DIR" "$NODE_ROOT" "$NPM_PREFIX"

use_node() {
  if [ -n "$1" ]; then
    export PATH="$1:$BIN_DIR:$PATH"
  else
    export PATH="$BIN_DIR:$PATH"
  fi
}

install_bundled_node() {
  local tarball="node-v${NODE_VERSION}-${platform}.tar.gz"
  local url="https://nodejs.org/dist/v${NODE_VERSION}/${tarball}"
  local extract_dir="$NODE_ROOT/node-v${NODE_VERSION}-${platform}"
  local cache="$NODE_ROOT/$tarball"

  if [ -x "$extract_dir/bin/node" ]; then
    use_node "$extract_dir/bin"
    return 0
  fi

  echo "Preparing Zephex runtime (one-time download, ~85MB)..." >&2
  download_file "$url" "$cache"
  rm -rf "$extract_dir"
  tar -xzf "$cache" -C "$NODE_ROOT"
  rm -f "$cache"
  use_node "$extract_dir/bin"
}

echo "" >&2
echo "◆ Zephex installer" >&2
echo "  Terminal tools · no AI agent required" >&2
echo "" >&2

if [ -n "$DRY_RUN" ]; then
  echo "[dry-run] Would install to $ZEPHEX_HOME and run: zephex init --terminal" >&2
  echo "[dry-run] Then: cd your-project && zephex" >&2
  exit 0
fi

if node_ok; then
  use_node ""
else
  install_bundled_node
fi

if [ -z "$ZEPHEX_VERSION" ]; then
  ZEPHEX_VERSION="$(npm view zephex version 2>/dev/null || true)"
  [ -n "$ZEPHEX_VERSION" ] || ZEPHEX_VERSION="latest"
fi

echo "Installing zephex@${ZEPHEX_VERSION}..." >&2
npm install -g "zephex@${ZEPHEX_VERSION}" --prefix "$NPM_PREFIX" --no-fund --no-audit --loglevel=error

for cmd in zephex mcpcli; do
  if [ -x "$NPM_PREFIX/bin/$cmd" ]; then
    ln -sf "$NPM_PREFIX/bin/$cmd" "$BIN_DIR/$cmd"
  fi
done

path_has_dir() {
  case ":$PATH:" in *":$1:"*) return 0 ;; *) return 1 ;; esac
}

user_shell="$(basename "${SHELL:-}")"
config_file=""
case "$user_shell" in
  bash) config_file="$HOME/.bashrc" ;;
  zsh) config_file="$HOME/.zshrc" ;;
  fish) config_file="$HOME/.config/fish/config.fish" ;;
esac

if [ -n "$config_file" ]; then
  mkdir -p "$(dirname "$config_file")"
  if ! grep -qs "zephex installer" "$config_file" 2>/dev/null; then
    if [ "$user_shell" = "fish" ]; then
      block="${INSTALLER_MARKER}
fish_add_path $BIN_DIR
for _zephex_node in \"$NODE_ROOT\"/node-v*/bin
  if test -d \"\$_zephex_node\"
    fish_add_path \"\$_zephex_node\"
    break
  end
end
# <<< zephex installer <<<"
    else
      block="${INSTALLER_MARKER}
export PATH=\"$BIN_DIR:\$PATH\"
for _zephex_node in \"$NODE_ROOT\"/node-v*/bin; do
  [ -d \"\$_zephex_node\" ] && export PATH=\"\$_zephex_node:\$PATH\" && break
done
unset _zephex_node
# <<< zephex installer <<<"
    fi
    printf '\n%s\n' "$block" >> "$config_file"
  fi
fi

export PATH="$BIN_DIR:$PATH"
for _zephex_node in "$NODE_ROOT"/node-v*/bin; do
  [ -d "$_zephex_node" ] && export PATH="$_zephex_node:$PATH" && break
done
unset _zephex_node

# curl | bash: stdin is a pipe; use stdout TTY + /dev/tty so browser sign-in can run
if [ -t 1 ]; then
  if [ -e /dev/tty ]; then
    zephex init --terminal </dev/tty 2>/dev/null || true
  else
    zephex init --terminal 2>/dev/null || true
  fi
  zephex welcome --install 2>/dev/null || true
  if ! path_has_dir "$BIN_DIR"; then
    echo "" >&2
    echo "Restart your terminal, or run: export PATH=\"$BIN_DIR:\$PATH\"" >&2
  fi
  exit 0
fi

zephex welcome --install 2>/dev/null || echo "Run: zephex init --terminal && zephex help" >&2
if ! path_has_dir "$BIN_DIR"; then
  echo "Restart your terminal, or: export PATH=\"$BIN_DIR:\$PATH\"" >&2
fi