#!/usr/bin/env bash
# ──────────────────────────────────────────────────────────────────────────────
#  NEXUS AI CLI — macOS Installer
#  Usage:  curl -fsSL https://nexusai.run/install-mac.sh | bash
#      or: bash install-mac.sh
#      or: bash install-mac.sh --api-url https://your-self-hosted.example.com
# ──────────────────────────────────────────────────────────────────────────────
set -euo pipefail
IFS=$'\n\t'

# ── Constants ─────────────────────────────────────────────────────────────────
CLI_NAME="nexusapp-cli"
CLI_CMD="nexus"
CLI_VERSION="2.0.0"
MIN_NODE_MAJOR=18
NODE_INSTALL_VERSION=20
DEFAULT_API_URL="https://nexusai.run"
RELEASE_URL="${DEFAULT_API_URL}/releases/cli/${CLI_NAME}-${CLI_VERSION}.tgz"
CONFIG_DIR="${HOME}/.nexusai"

# ── Colors ────────────────────────────────────────────────────────────────────
if [ -t 1 ] && command -v tput &>/dev/null && tput colors &>/dev/null; then
  RED=$(tput setaf 1); GREEN=$(tput setaf 2); YELLOW=$(tput setaf 3)
  BLUE=$(tput setaf 4); CYAN=$(tput setaf 6); BOLD=$(tput bold); RESET=$(tput sgr0)
else
  RED=''; GREEN=''; YELLOW=''; BLUE=''; CYAN=''; BOLD=''; RESET=''
fi

# ── Logging ───────────────────────────────────────────────────────────────────
step()    { echo "${BLUE}${BOLD}==> $*${RESET}"; }
info()    { echo "    $*"; }
success() { echo "${GREEN}${BOLD} ✓  $*${RESET}"; }
warn()    { echo "${YELLOW} ⚠  $*${RESET}"; }
error()   { echo "${RED}${BOLD} ✗  $*${RESET}" >&2; }
die()     { error "$*"; exit 1; }

# ── Banner ────────────────────────────────────────────────────────────────────
print_banner() {
  echo ""
  echo "${CYAN}${BOLD}  ███╗   ██╗███████╗██╗  ██╗██╗   ██╗███████╗     █████╗ ██╗${RESET}"
  echo "${CYAN}${BOLD}  ████╗  ██║██╔════╝╚██╗██╔╝██║   ██║██╔════╝    ██╔══██╗██║${RESET}"
  echo "${CYAN}${BOLD}  ██╔██╗ ██║█████╗   ╚███╔╝ ██║   ██║███████╗    ███████║██║${RESET}"
  echo "${CYAN}${BOLD}  ██║╚██╗██║██╔══╝   ██╔██╗ ██║   ██║╚════██║    ██╔══██║██║${RESET}"
  echo "${CYAN}${BOLD}  ██║ ╚████║███████╗██╔╝ ██╗╚██████╔╝███████║    ██║  ██║██║${RESET}"
  echo "${CYAN}${BOLD}  ╚═╝  ╚═══╝╚══════╝╚═╝  ╚═╝ ╚═════╝ ╚══════╝    ╚═╝  ╚═╝╚═╝${RESET}"
  echo ""
  echo "  ${BOLD}CLI Installer for macOS${RESET} — version ${CLI_VERSION}"
  echo "  ${BLUE}https://nexusai.run${RESET}"
  echo ""
}

# ── Parse arguments ───────────────────────────────────────────────────────────
API_URL="${NEXUSAI_API_URL:-${DEFAULT_API_URL}}"
SKIP_NODE_INSTALL=false
UNINSTALL=false
USE_BREW=false      # set to true if Homebrew tap is available

while [[ $# -gt 0 ]]; do
  case "$1" in
    --api-url)    API_URL="$2"; shift 2 ;;
    --skip-node)  SKIP_NODE_INSTALL=true; shift ;;
    --uninstall)  UNINSTALL=true; shift ;;
    --brew)       USE_BREW=true; shift ;;
    --version|-v) echo "${CLI_NAME} installer v${CLI_VERSION}"; exit 0 ;;
    --help|-h)
      echo "Usage: bash install-mac.sh [OPTIONS]"
      echo ""
      echo "Options:"
      echo "  --api-url <url>   Set the NEXUS AI API URL (default: ${DEFAULT_API_URL})"
      echo "  --skip-node       Skip automatic Node.js installation"
      echo "  --brew            Install via Homebrew tap instead of npm"
      echo "  --uninstall       Remove NEXUS AI CLI from this machine"
      echo "  --version         Print installer version"
      echo "  --help            Show this help"
      exit 0 ;;
    *) die "Unknown option: $1. Run with --help for usage." ;;
  esac
done

# ── System checks ─────────────────────────────────────────────────────────────
check_os() {
  step "Checking system"

  if [[ "$(uname -s)" != "Darwin" ]]; then
    die "This script is for macOS only. For Linux, use:\n  curl -fsSL ${DEFAULT_API_URL}/install.sh | bash"
  fi

  ARCH=$(uname -m)
  MACOS_VERSION=$(sw_vers -productVersion)
  MACOS_MAJOR=$(echo "${MACOS_VERSION}" | cut -d. -f1)

  if [[ "${MACOS_MAJOR}" -lt 12 ]]; then
    warn "macOS ${MACOS_VERSION} is older than Monterey (12). Some features may not work."
  fi

  case "${ARCH}" in
    arm64)  CHIP="Apple Silicon (M-series)"; BREW_PREFIX="/opt/homebrew" ;;
    x86_64) CHIP="Intel x86_64";             BREW_PREFIX="/usr/local" ;;
    *)      die "Unsupported architecture: ${ARCH}" ;;
  esac

  info "macOS: ${MACOS_VERSION}"
  info "Chip:  ${CHIP}"

  # Check for Rosetta 2 on Apple Silicon (needed for some x86 tools)
  if [[ "${ARCH}" == "arm64" ]] && ! /usr/bin/pgrep -q oahd 2>/dev/null; then
    info "Note: Rosetta 2 not detected — if any step fails, install it with:"
    info "  softwareupdate --install-rosetta --agree-to-license"
  fi
}

# ── Xcode CLT check ───────────────────────────────────────────────────────────
check_xcode_clt() {
  if ! xcode-select -p &>/dev/null; then
    step "Installing Xcode Command Line Tools"
    info "A dialog may appear asking you to install the developer tools."
    info "Please click 'Install' and wait for it to complete, then re-run this script."
    xcode-select --install 2>/dev/null || true
    die "Xcode Command Line Tools required. Re-run this script after installation completes."
  fi
  success "Xcode CLT OK"
}

# ── Homebrew ──────────────────────────────────────────────────────────────────
ensure_homebrew() {
  step "Checking Homebrew"

  if command -v brew &>/dev/null; then
    BREW_VERSION=$(brew --version | head -1 | awk '{print $2}')
    success "Homebrew ${BREW_VERSION} found"

    # Make sure brew is on PATH (Apple Silicon shells sometimes miss it)
    if [[ "${ARCH}" == "arm64" ]] && ! echo "${PATH}" | grep -q "/opt/homebrew"; then
      eval "$(/opt/homebrew/bin/brew shellenv)"
    fi
    return 0
  fi

  info "Homebrew not found — installing"
  info "This will also install Xcode Command Line Tools if not already present."
  echo ""

  NONINTERACTIVE=1 /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"

  # Add brew to PATH for Apple Silicon
  if [[ "${ARCH}" == "arm64" ]]; then
    eval "$(/opt/homebrew/bin/brew shellenv)"
    # Persist in shell rc files
    for RC in "${HOME}/.zprofile" "${HOME}/.bash_profile" "${HOME}/.profile"; do
      if [ -f "${RC}" ] && ! grep -q "homebrew" "${RC}"; then
        echo '' >> "${RC}"
        echo '# Homebrew — added by NEXUS AI CLI installer' >> "${RC}"
        echo 'eval "$(/opt/homebrew/bin/brew shellenv)"' >> "${RC}"
      fi
    done
  fi

  success "Homebrew installed"
}

# ── Node.js ───────────────────────────────────────────────────────────────────
check_node() {
  step "Checking Node.js"

  if command -v node &>/dev/null; then
    NODE_VERSION=$(node --version | sed 's/v//')
    NODE_MAJOR=$(echo "${NODE_VERSION}" | cut -d. -f1)
    if [[ "${NODE_MAJOR}" -ge "${MIN_NODE_MAJOR}" ]]; then
      success "Node.js ${NODE_VERSION} — OK (>= ${MIN_NODE_MAJOR} required)"
      return 0
    else
      warn "Node.js ${NODE_VERSION} is too old (need v${MIN_NODE_MAJOR}+)"
    fi
  else
    warn "Node.js not found"
  fi

  if [[ "${SKIP_NODE_INSTALL}" == "true" ]]; then
    die "Node.js v${MIN_NODE_MAJOR}+ is required. Install it and re-run."
  fi

  install_node
}

install_node() {
  step "Installing Node.js ${NODE_INSTALL_VERSION} LTS"

  if command -v brew &>/dev/null; then
    info "Installing via Homebrew"
    brew install "node@${NODE_INSTALL_VERSION}"

    # node@N is keg-only on Homebrew — link it
    brew link --overwrite "node@${NODE_INSTALL_VERSION}" 2>/dev/null || true

    # Ensure brew-installed node is on PATH
    NODE_BIN="${BREW_PREFIX}/opt/node@${NODE_INSTALL_VERSION}/bin"
    if [ -d "${NODE_BIN}" ] && ! echo "${PATH}" | grep -q "${NODE_BIN}"; then
      export PATH="${NODE_BIN}:${PATH}"
      for RC in "${HOME}/.zshrc" "${HOME}/.bash_profile" "${HOME}/.zprofile"; do
        if [ -f "${RC}" ] && ! grep -q "node@${NODE_INSTALL_VERSION}" "${RC}"; then
          echo '' >> "${RC}"
          echo "# Node.js — added by NEXUS AI CLI installer" >> "${RC}"
          echo "export PATH=\"${NODE_BIN}:\$PATH\"" >> "${RC}"
        fi
      done
    fi
  else
    info "Homebrew not available — installing Node.js via nvm"
    export NVM_DIR="${HOME}/.nvm"
    curl -fsSL https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.7/install.sh | bash
    # shellcheck source=/dev/null
    [ -s "${NVM_DIR}/nvm.sh" ] && \. "${NVM_DIR}/nvm.sh"
    nvm install "${NODE_INSTALL_VERSION}"
    nvm use "${NODE_INSTALL_VERSION}"
    nvm alias default "${NODE_INSTALL_VERSION}"
  fi

  NODE_VERSION=$(node --version 2>/dev/null | sed 's/v//') || die "Node.js installation failed."
  success "Node.js ${NODE_VERSION} installed"
  success "npm $(npm --version) ready"
}

# ── CLI via Homebrew tap ──────────────────────────────────────────────────────
install_via_brew() {
  step "Installing ${CLI_CMD} via Homebrew"
  brew tap nexusai/tap 2>/dev/null || warn "Could not tap nexusai/tap — falling back to npm install"
  if brew install nexusai/tap/nexus 2>/dev/null; then
    success "${CLI_CMD} installed via Homebrew"
    return 0
  fi
  warn "Homebrew tap install failed — falling back to npm"
  return 1
}

# ── CLI via npm ───────────────────────────────────────────────────────────────
install_cli() {
  step "Installing ${CLI_NAME} v${CLI_VERSION}"

  # Try Homebrew tap first if --brew flag passed
  if [[ "${USE_BREW}" == "true" ]]; then
    install_via_brew && return 0 || true
  fi

  # Determine npm global prefix and whether we need sudo
  NPM_PREFIX=$(npm config get prefix 2>/dev/null || echo "${BREW_PREFIX}")
  if [ -w "${NPM_PREFIX}" ] || [[ $EUID -eq 0 ]]; then
    NPM_CMD="npm"
  else
    NPM_CMD="sudo npm"
  fi

  # Try release tarball first, then npm registry
  info "Downloading from ${RELEASE_URL}"
  if ${NPM_CMD} install -g "${RELEASE_URL}" 2>/dev/null; then
    success "${CLI_CMD} installed from release"
  else
    warn "Release download failed, trying npm registry…"
    if ${NPM_CMD} install -g "${CLI_NAME}@${CLI_VERSION}" 2>/dev/null; then
      success "${CLI_CMD} installed from npm registry"
    else
      die "Installation failed. Try manually:\n  npm install -g ${RELEASE_URL}"
    fi
  fi

  # Verify binary is accessible
  if ! command -v "${CLI_CMD}" &>/dev/null; then
    CANDIDATE=""
    for DIR in "${NPM_PREFIX}/bin" "${BREW_PREFIX}/bin" "${HOME}/.local/bin"; do
      if [ -x "${DIR}/${CLI_CMD}" ]; then
        CANDIDATE="${DIR}"
        break
      fi
    done

    if [ -n "${CANDIDATE}" ]; then
      warn "'${CLI_CMD}' found at ${CANDIDATE} but not in PATH"
      add_to_path "${CANDIDATE}"
    else
      die "'${CLI_CMD}' binary not found. npm global bin: $(npm bin -g 2>/dev/null || echo 'unknown')"
    fi
  fi

  INSTALLED_VERSION=$("${CLI_CMD}" --version 2>/dev/null || echo "unknown")
  success "${CLI_CMD} ${INSTALLED_VERSION} is ready"
}

add_to_path() {
  local DIR="$1"
  warn "Adding ${DIR} to PATH"

  for RC in "${HOME}/.zshrc" "${HOME}/.bash_profile" "${HOME}/.zprofile" "${HOME}/.profile"; do
    if [ -f "${RC}" ] && ! grep -q "${DIR}" "${RC}"; then
      echo '' >> "${RC}"
      echo '# Added by NEXUS AI CLI installer' >> "${RC}"
      echo "export PATH=\"${DIR}:\$PATH\"" >> "${RC}"
    fi
  done

  export PATH="${DIR}:${PATH}"
  warn "Run 'source ~/.zshrc' (or open a new terminal) to apply PATH changes."
}

# ── Configure API URL ─────────────────────────────────────────────────────────
configure() {
  step "Configuring CLI"

  mkdir -p "${CONFIG_DIR}"
  chmod 700 "${CONFIG_DIR}"

  if [[ "${API_URL}" != "${DEFAULT_API_URL}" ]]; then
    local CONFIG_FILE="${CONFIG_DIR}/config.json"
    info "Setting API URL to ${API_URL}"

    if [ -f "${CONFIG_FILE}" ] && command -v python3 &>/dev/null; then
      local TMP
      TMP=$(mktemp)
      python3 -c "
import json
with open('${CONFIG_FILE}') as f:
    cfg = json.load(f)
cfg['apiUrl'] = '${API_URL}'
print(json.dumps(cfg, indent=2))
" > "${TMP}" && mv "${TMP}" "${CONFIG_FILE}" || echo "{\"apiUrl\":\"${API_URL}\"}" > "${CONFIG_FILE}"
    else
      echo "{\"apiUrl\":\"${API_URL}\"}" > "${CONFIG_FILE}"
    fi

    chmod 600 "${CONFIG_FILE}"
    success "API URL configured: ${API_URL}"
  else
    info "Using default API URL: ${DEFAULT_API_URL}"
  fi
}

# ── Uninstall ─────────────────────────────────────────────────────────────────
uninstall() {
  step "Uninstalling NEXUS AI CLI"

  # Check if installed via Homebrew first
  if command -v brew &>/dev/null && brew list nexusai/tap/nexus &>/dev/null 2>&1; then
    brew uninstall nexusai/tap/nexus
    success "Homebrew formula removed"
  elif command -v "${CLI_CMD}" &>/dev/null; then
    NPM_PREFIX=$(npm config get prefix 2>/dev/null || echo "${BREW_PREFIX}")
    if [ -w "${NPM_PREFIX}" ]; then
      npm uninstall -g "${CLI_NAME}"
    else
      sudo npm uninstall -g "${CLI_NAME}"
    fi
    success "${CLI_CMD} binary removed"
  else
    warn "${CLI_CMD} not found — skipping binary removal"
  fi

  if [ -d "${CONFIG_DIR}" ]; then
    read -r -p "  Remove configuration at ${CONFIG_DIR}? [y/N] " CONFIRM
    if [[ "${CONFIRM}" =~ ^[Yy]$ ]]; then
      rm -rf "${CONFIG_DIR}"
      success "Configuration removed"
    else
      info "Configuration kept at ${CONFIG_DIR}"
    fi
  fi

  success "NEXUS AI CLI uninstalled"
  exit 0
}

# ── Post-install message ──────────────────────────────────────────────────────
print_success() {
  echo ""
  echo "────────────────────────────────────────────────────────────────"
  echo "${GREEN}${BOLD}  NEXUS AI CLI installed successfully!${RESET}"
  echo "────────────────────────────────────────────────────────────────"
  echo ""
  echo "  ${BOLD}Get started:${RESET}"
  echo ""
  echo "  ${CYAN}1. Log in to your account:${RESET}"
  echo "     ${BOLD}${CLI_CMD} auth login${RESET}"
  echo ""
  echo "  ${CYAN}2. List your deployments:${RESET}"
  echo "     ${BOLD}${CLI_CMD} deploy list${RESET}"
  echo ""
  echo "  ${CYAN}3. Create a new deployment:${RESET}"
  echo "     ${BOLD}${CLI_CMD} deploy create --name my-app --image my-org/my-app:latest${RESET}"
  echo ""
  echo "  ${CYAN}4. Stream live logs:${RESET}"
  echo "     ${BOLD}${CLI_CMD} deploy logs <deployment-id> --follow${RESET}"
  echo ""
  echo "  ${CYAN}5. View all commands:${RESET}"
  echo "     ${BOLD}${CLI_CMD} --help${RESET}"
  echo ""
  echo "  API endpoint: ${BLUE}${API_URL}${RESET}"
  echo "  Config dir:   ${CONFIG_DIR}"
  echo ""
  echo "  ${BOLD}Docs:${RESET}  ${BLUE}https://nexusai.run/docs${RESET}"
  echo "  ${BOLD}Issues:${RESET} ${BLUE}https://github.com/nexusrun/nexusai${RESET}"
  echo ""
}

# ── Main ──────────────────────────────────────────────────────────────────────
main() {
  print_banner

  if [[ "${UNINSTALL}" == "true" ]]; then
    uninstall
  fi

  check_os
  check_xcode_clt
  ensure_homebrew
  check_node
  install_cli
  configure
  print_success
}

main "$@"
