#!/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 >>>"
INSTALLER_END="# <<< 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"
}

write_env_sh() {
  cat >"$ZEPHEX_HOME/env.sh" <<EOF
# Zephex CLI — loaded by ~/.zshrc / ~/.bashrc after install
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
EOF
}

shell_path_block() {
  if [ "$1" = "fish" ]; then
    printf '%s\n' "${INSTALLER_MARKER}"
    printf 'fish_add_path %s\n' "$BIN_DIR"
    printf 'for _zephex_node in "%s"/node-v*/bin\n' "$NODE_ROOT"
    printf '  if test -d "$_zephex_node"\n'
    printf '    fish_add_path "$_zephex_node"\n'
    printf '    break\n'
    printf '  end\n'
    printf 'end\n'
    printf '%s\n' "${INSTALLER_END}"
    return
  fi
  printf '%s\n' "${INSTALLER_MARKER}"
  printf '[ -f "$HOME/.zephex/env.sh" ] && . "$HOME/.zephex/env.sh"\n'
  printf '%s\n' "${INSTALLER_END}"
}

append_shell_path() {
  local file="$1"
  local shell_name="$2"
  mkdir -p "$(dirname "$file")"
  if [ ! -f "$file" ]; then
    touch "$file"
  fi
  if grep -qs "zephex installer" "$file" 2>/dev/null; then
    return 0
  fi
  printf '\n' >>"$file"
  shell_path_block "$shell_name" >>"$file"
}

print_path_activation() {
  echo "" >&2
  echo "┌─ Use zephex in THIS terminal ─────────────────────────────" >&2
  echo "│  Installed to: $BIN_DIR" >&2
  echo "│" >&2
  echo "│  Run now (copy/paste — includes Node if we bundled it):" >&2
  echo "│    source ~/.zephex/env.sh" >&2
  echo "│" >&2
  echo "│  Then:  zephex   or   mcpcli get-context" >&2
  echo "│  New Terminal windows: quit & reopen (PATH added to shell rc)" >&2
  echo "└────────────────────────────────────────────────────────────" >&2
  echo "" >&2
}

echo "" >&2
echo "◆ Zephex installer" >&2
echo "  Terminal tools · no AI agent required" >&2
echo "  curl|bash runs in a subshell — we will print how to enable zephex/mcpcli when done." >&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] Parent shell PATH: source ~/.zephex/env.sh" >&2
  exit 0
fi

print_path_preflight() {
  echo "│  Tip: after install, run: source ~/.zephex/env.sh" >&2
}
print_path_preflight

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

write_env_sh

user_shell="$(basename "${SHELL:-}")"
case "$user_shell" in
  bash)
    append_shell_path "$HOME/.bashrc" bash
    append_shell_path "$HOME/.profile" bash
    ;;
  zsh)
    append_shell_path "$HOME/.zshrc" zsh
    # Login shells (macOS Terminal, Linux gdm/konsole) read .zprofile first
    append_shell_path "$HOME/.zprofile" zsh
    ;;
  fish) append_shell_path "$HOME/.config/fish/config.fish" fish ;;
esac
# Non-bash login shells on Linux (dash/sh) often read only ~/.profile
if [ "$os" = "linux" ] && [ "$user_shell" != "bash" ] && [ "$user_shell" != "zsh" ] && [ "$user_shell" != "fish" ]; then
  append_shell_path "$HOME/.profile" bash
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
  print_path_activation
  exit 0
fi

zephex welcome --install 2>/dev/null || echo "Run: zephex init --terminal && zephex help" >&2
print_path_activation