#!/bin/sh
# EMP CLI — Linux / macOS installer (pure Node, no AVX, no Bun, no native build)
# v1.3.0
# One-liner:
#   curl -fsSL https://raw.githubusercontent.com/saintdevzz/emp-cli/main/install.sh | sh
# Local:
#   sh install.sh
#   ./install.sh
set -eu

REPO_URL="https://github.com/saintdevzz/emp-cli.git"
INSTALL_DIR="$HOME/.emp/cli"
BIN_DIR="$HOME/.local/bin"

echo "EMP CLI installer (Linux/macOS, plain Node)"

# 1. check node (need Node 14+)
if ! command -v node >/dev/null 2>&1; then
  echo "Node.js not found. Install Node.js 14+ from https://nodejs.org/"
  echo "No AVX/Bun/native build needed - plain Node only."
  exit 1
fi
NODE_VER="$(node --version 2>/dev/null || echo unknown)"
echo "Found Node $NODE_VER"

# 2. resolve script dir (handles curl | sh where $0 is 'sh')
SCRIPT_DIR=""
if [ -n "${0:-}" ] && [ -f "$0" ]; then
  # $0 is a file (./install.sh or sh install.sh) - try dirname
  case "$0" in
    */*) SCRIPT_DIR="$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)" ;;
    *) SCRIPT_DIR="$(pwd)" ;;
  esac
fi
# also try BASH_SOURCE if bash
if [ -z "$SCRIPT_DIR" ] && [ -n "${BASH_SOURCE:-}" ]; then
  SCRIPT_DIR="$(CDPATH= cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)"
fi

IS_LOCAL=0
if [ -n "$SCRIPT_DIR" ] && [ -f "$SCRIPT_DIR/bin/emp.js" ]; then
  IS_LOCAL=1
  SRC="$SCRIPT_DIR"
  echo "Installing from local folder: $SRC"
else
  SRC=""
fi

if [ "$IS_LOCAL" -eq 0 ]; then
  if command -v git >/dev/null 2>&1; then
    echo "Cloning $REPO_URL -> $INSTALL_DIR"
    rm -rf "$INSTALL_DIR"
    git clone "$REPO_URL" "$INSTALL_DIR"
    SRC="$INSTALL_DIR"
  else
    echo "git not found, downloading zip..."
    TMP_ZIP="${TMPDIR:-/tmp}/emp-cli.zip"
    TMP_EXTRACT="${TMPDIR:-/tmp}/emp-cli-extract"
    rm -rf "$TMP_EXTRACT" "$TMP_ZIP"
    mkdir -p "$TMP_EXTRACT"
    DL_URL="https://github.com/saintdevzz/emp-cli/archive/main.zip"
    if command -v curl >/dev/null 2>&1; then
      curl -fsSL "$DL_URL" -o "$TMP_ZIP"
    elif command -v wget >/dev/null 2>&1; then
      wget -qO "$TMP_ZIP" "$DL_URL"
    else
      echo "Need curl or wget to download, or install git." >&2
      exit 1
    fi
    if command -v unzip >/dev/null 2>&1; then
      unzip -q "$TMP_ZIP" -d "$TMP_EXTRACT"
    else
      # fallback: python unzip
      python3 -m zipfile -e "$TMP_ZIP" "$TMP_EXTRACT" 2>/dev/null || { echo "Need unzip or python3." >&2; exit 1; }
    fi
    EXTRACTED="$(find "$TMP_EXTRACT" -maxdepth 1 -type d -name 'emp-cli*' | head -n 1)"
    if [ -z "$EXTRACTED" ] || [ ! -d "$EXTRACTED" ]; then
      echo "Failed to extract emp-cli.zip" >&2
      exit 1
    fi
    rm -rf "$INSTALL_DIR"
    mkdir -p "$(dirname "$INSTALL_DIR")"
    mv "$EXTRACTED" "$INSTALL_DIR"
    rm -rf "$TMP_EXTRACT" "$TMP_ZIP"
    SRC="$INSTALL_DIR"
  fi
fi

# 3. copy if local and different from INSTALL_DIR
if [ "$SRC" != "$INSTALL_DIR" ]; then
  rm -rf "$INSTALL_DIR"
  mkdir -p "$INSTALL_DIR"
  # copy bin/lib + meta (cp -a if available, else cp -R)
  if cp -a --help >/dev/null 2>&1; then
    cp -a "$SRC/bin" "$SRC/lib" "$INSTALL_DIR/" 2>/dev/null || cp -R "$SRC/bin" "$SRC/lib" "$INSTALL_DIR/"
    cp -a "$SRC/package.json" "$SRC/emp.sh" "$SRC/emp.cmd" "$INSTALL_DIR/" 2>/dev/null || true
    [ -f "$SRC/install.sh" ] && cp -a "$SRC/install.sh" "$INSTALL_DIR/" 2>/dev/null || true
  else
    cp -R "$SRC/bin" "$SRC/lib" "$INSTALL_DIR/"
    cp "$SRC/package.json" "$SRC/emp.sh" "$INSTALL_DIR/" 2>/dev/null || true
  fi
  SRC="$INSTALL_DIR"
fi

# ensure executables
chmod +x "$INSTALL_DIR/bin/emp.js" 2>/dev/null || true
chmod +x "$INSTALL_DIR/emp.sh" 2>/dev/null || true

# 4. create shim in ~/.local/bin/emp
mkdir -p "$BIN_DIR"
SHIM="$BIN_DIR/emp"
cat > "$SHIM" <<EOS
#!/bin/sh
exec node "$INSTALL_DIR/bin/emp.js" "\$@"
EOS
chmod +x "$SHIM"
echo "Created shim $SHIM -> $INSTALL_DIR/bin/emp.js"

# 5. add BIN_DIR to PATH if missing
add_to_path() {
  _file="$1"
  # create file if it doesn't exist (e.g. .bashrc on minimal systems)
  if [ ! -f "$_file" ]; then return 0; fi
  if grep -qF "$BIN_DIR" "$_file" 2>/dev/null; then
    return 0
  fi
  # check if PATH already contains BIN_DIR in current shell
  case ":$PATH:" in
    *":$BIN_DIR:"*) return 0 ;;
  esac
  echo "" >> "$_file"
  echo "# added by EMP CLI installer" >> "$_file"
  echo "export PATH=\"\$HOME/.local/bin:\$PATH\"" >> "$_file"
  echo "Added $BIN_DIR to PATH in $_file"
}

# only add if not already on PATH
case ":$PATH:" in
  *":$BIN_DIR:"*)
    echo "$BIN_DIR already on PATH"
    ;;
  *)
    # try common shell rc files (only ones that exist)
    for rc in "$HOME/.bashrc" "$HOME/.zshrc" "$HOME/.profile" "$HOME/.bash_profile"; do
      if [ -f "$rc" ]; then add_to_path "$rc"; fi
    done
    # if none existed, create .profile entry
    if [ ! -f "$HOME/.bashrc" ] && [ ! -f "$HOME/.zshrc" ]; then
      echo "export PATH=\"\$HOME/.local/bin:\$PATH\"" >> "$HOME/.profile"
      echo "Added $BIN_DIR to PATH in $HOME/.profile"
    fi
    echo "Added $BIN_DIR to PATH - restart your shell or run: export PATH=\"\$HOME/.local/bin:\$PATH\""
    ;;
esac

echo ""
echo "Done! Try:"
echo "  emp --help"
echo "  emp setup"
echo "  emp --zen ask \"hi\""
echo ""
echo "If 'emp' not found, run: export PATH=\"\$HOME/.local/bin:\$PATH\""
echo "Config at ~/.emp/config.json"
