#!/bin/bash
# Mervia — Claude Code Installation for macOS
# Installs Claude Code + Node.js (no editor). Skips anything already installed.
# Usage: curl -fsSL https://learn.mervia.academy/guides/claude-code-installation/mervia-claude-code-installation-mac.sh | bash

set -e

# Colors
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
RED='\033[0;31m'
BOLD='\033[1m'
NC='\033[0m'

info()    { echo -e "${BLUE}[INFO]${NC} $1"; }
success() { echo -e "${GREEN}[OK]${NC} $1"; }
warn()    { echo -e "${YELLOW}[!]${NC} $1"; }
fail()    { echo -e "${RED}[ERROR]${NC} $1"; }

INSTALLED=()
SKIPPED=()
FAILED=()

echo ""
echo -e "${BLUE}${BOLD}Mervia — Claude Code Installation (macOS)${NC}"
echo -e "${BLUE}===========================================${NC}"
echo ""

# ─── 1. Claude Code ─────────────────────────────────────
info "Checking Claude Code..."
if command -v claude &> /dev/null; then
  success "Claude Code already installed"
  SKIPPED+=("Claude Code")
else
  info "Installing Claude Code (official installer)..."
  if curl -fsSL https://claude.ai/install.sh | bash; then
    # Refresh PATH to pick up newly installed binary
    export PATH="$HOME/.claude/bin:$HOME/.local/bin:/usr/local/bin:$PATH"

    # The official installer normally configures PATH itself. Only persist a
    # fallback entry if `claude` still isn't resolvable (avoids a duplicate line).
    if ! command -v claude &> /dev/null; then
      CLAUDE_BIN=""
      for dir in "$HOME/.claude/bin" "$HOME/.local/bin" "/usr/local/bin"; do
        if [ -x "$dir/claude" ]; then
          CLAUDE_BIN="$dir"
          break
        fi
      done

      if [ -n "$CLAUDE_BIN" ]; then
        # Detect shell profile
        SHELL_RC=""
        case "${SHELL:-}" in
          */zsh)  SHELL_RC="$HOME/.zshrc" ;;
          */bash) SHELL_RC="$HOME/.bash_profile" ;;
        esac

        if [ -n "$SHELL_RC" ] && ! grep -q "$CLAUDE_BIN" "$SHELL_RC" 2>/dev/null; then
          echo '' >> "$SHELL_RC"
          echo '# Claude Code' >> "$SHELL_RC"
          echo "export PATH=\"$CLAUDE_BIN:\$PATH\"" >> "$SHELL_RC"
          info "Added $CLAUDE_BIN to $SHELL_RC"
        fi
      fi
    fi

    INSTALLED+=("Claude Code")
  else
    FAILED+=("Claude Code")
  fi
fi

# ─── 2. Node.js ─────────────────────────────────────────
info "Checking Node.js..."
if command -v node &> /dev/null; then
  success "Node.js already installed — $(node --version)"
  SKIPPED+=("Node.js")
else
  # Fetch the latest LTS version number from nodejs.org.
  # index.json is newest-first; split objects onto their own lines, keep only
  # LTS releases ("lts":"<name>"), take the newest, and read its version.
  # The `v[0-9]` (digit required) avoids matching the `v` in "version".
  # `|| true` keeps `set -e` from aborting before the fallback below.
  NODE_VERSION=$(curl -fsSL https://nodejs.org/dist/index.json 2>/dev/null \
    | tr '}' '\n' | grep '"lts":"' | head -1 | grep -o 'v[0-9][0-9.]*' | head -1) || true
  if [ -z "$NODE_VERSION" ]; then
    NODE_VERSION="v22.15.0"
    warn "Could not detect latest LTS version, using $NODE_VERSION"
  fi

  # The macOS .pkg installer is a single universal package (Intel + Apple
  # Silicon) named node-<version>.pkg — there is no arch-specific .pkg.
  NODE_PKG="node-${NODE_VERSION}.pkg"

  info "Installing Node.js ${NODE_VERSION}..."
  NODE_PKG_PATH="/tmp/$NODE_PKG"
  if curl -fsSL "https://nodejs.org/dist/${NODE_VERSION}/${NODE_PKG}" -o "$NODE_PKG_PATH"; then
    info "This may ask for your Mac password (characters won't show — that's normal)."
    if sudo installer -pkg "$NODE_PKG_PATH" -target /; then
      rm -f "$NODE_PKG_PATH"
      export PATH="/usr/local/bin:$PATH"
      INSTALLED+=("Node.js ${NODE_VERSION}")
    else
      rm -f "$NODE_PKG_PATH"
      FAILED+=("Node.js")
    fi
  else
    fail "Download failed."
    echo ""
    echo -e "  Please install Node.js manually:"
    echo -e "  1. Go to ${BLUE}https://nodejs.org/${NC}"
    echo -e "  2. Download the LTS version and install like any other app"
    echo ""
    FAILED+=("Node.js (manual install needed)")
  fi
fi

# ─── Summary ─────────────────────────────────────────────
echo ""
echo -e "${BLUE}${BOLD}Setup Summary${NC}"
echo -e "${BLUE}===========================================${NC}"

if [ ${#SKIPPED[@]} -gt 0 ]; then
  echo ""
  echo -e "${GREEN}Already had:${NC}"
  for item in "${SKIPPED[@]}"; do echo -e "  ${GREEN}✅${NC} $item"; done
fi

if [ ${#INSTALLED[@]} -gt 0 ]; then
  echo ""
  echo -e "${GREEN}Successfully installed:${NC}"
  for item in "${INSTALLED[@]}"; do echo -e "  ${GREEN}✅${NC} $item"; done
fi

if [ ${#FAILED[@]} -gt 0 ]; then
  echo ""
  echo -e "${RED}Failed:${NC}"
  for item in "${FAILED[@]}"; do echo "  $item"; done
  echo ""
  warn "Please share the error above in the LINE group for help."
fi
