#!/bin/bash
# =============================================================================
# EasyCC — Claude Code Mac Auto-Installer
#
# Usage:
#   bash ~/Downloads/install-mac.sh
#
# Or run remotely:
#   curl -fsSL https://managerkim.com/downloads/install-mac.sh | bash
#
# Test mode (detect only, no installation):
#   bash install-mac.sh --test
#
# =============================================================================

# Do not use set -e — error handling is done per step. set -e causes unexpected script termination on non-zero exit.

# ---------------------------------------------------------------------------
# Run mode (--test or --dry-run for detection only)
# ---------------------------------------------------------------------------
TEST_MODE=false
for arg in "$@"; do
    case "$arg" in
        --test|--dry-run|-t) TEST_MODE=true ;;
    esac
done

# ---------------------------------------------------------------------------
# Log file
# ---------------------------------------------------------------------------
LOG_FILE="$HOME/Desktop/easy-clco-install-log.txt"
[ -d "$HOME/Desktop" ] || LOG_FILE="$HOME/easy-clco-install-log.txt"

write_log() {
    local ts
    ts=$(date '+%Y-%m-%d %H:%M:%S')
    echo "[$ts] $1" >> "$LOG_FILE"
}

write_system_info() {
    echo "============================================" > "$LOG_FILE"
    write_log "EasyCC — Installation Log"
    write_log "============================================"
    write_log "Run time: $(date '+%Y-%m-%d %H:%M:%S')"
    write_log "Test mode: $TEST_MODE"
    write_log "OS: $(sw_vers -productName 2>/dev/null || uname -s) $(sw_vers -productVersion 2>/dev/null || uname -r)"
    write_log "Architecture: $(uname -m)"
    write_log "User: $(whoami)"
    write_log "Home path: $HOME"
    write_log "Shell: $SHELL ($BASH_VERSION)"
    write_log "--- PATH ---"
    echo "$PATH" | tr ':' '\n' | while read -r p; do write_log "  $p"; done
    write_log "--- END PATH ---"
    write_log ""
}

# ---------------------------------------------------------------------------
# Colors and utilities
# ---------------------------------------------------------------------------
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
CYAN='\033[0;36m'
MAGENTA='\033[0;35m'
BOLD='\033[1m'
NC='\033[0m'

ERRORS=()

step_ok()   { echo -e "  ${GREEN}✅ $1${NC}"; write_log "[OK] $1"; }
step_fail() { echo -e "  ${RED}❌ $1${NC}"; ERRORS+=("$1"); write_log "[FAIL] $1"; }
step_wait() { echo -e "  ${YELLOW}⏳ $1${NC}"; write_log "[WAIT] $1"; }
step_info() { echo -e "  ${CYAN}ℹ️  $1${NC}"; write_log "[INFO] $1"; }
step_test() { echo -e "  ${MAGENTA}🧪 $1${NC}"; write_log "[TEST] $1"; }

# ---------------------------------------------------------------------------
# System info logging + header
# ---------------------------------------------------------------------------
write_system_info

echo ""
echo -e "${BOLD}${BLUE}╔══════════════════════════════════════════════════════════╗${NC}"
echo -e "${BOLD}${BLUE}║                                                          ║${NC}"
echo -e "${BOLD}${BLUE}║        EasyCC — Claude Code Auto-Installer                ║${NC}"
echo -e "${BOLD}${BLUE}║                                                          ║${NC}"
echo -e "${BOLD}${BLUE}║   Xcode CLT · Git · Claude Code · Homebrew · Node.js · gh ║${NC}"
echo -e "${BOLD}${BLUE}║                                                          ║${NC}"
echo -e "${BOLD}${BLUE}╚══════════════════════════════════════════════════════════╝${NC}"
echo ""
echo -e "  Log file: ${CYAN}$LOG_FILE${NC}"
if [ "$TEST_MODE" = true ]; then
    echo -e "  ${MAGENTA}Test mode — detection only, no installation${NC}"
fi
echo ""
echo ""

# ---------------------------------------------------------------------------
# Source shell profile — so already-installed tools are found in PATH
# ---------------------------------------------------------------------------
reload_shell() {
    if [ -f /opt/homebrew/bin/brew ]; then
        eval "$(/opt/homebrew/bin/brew shellenv)"
    elif [ -f /usr/local/bin/brew ]; then
        eval "$(/usr/local/bin/brew shellenv)"
    fi

    for f in "$HOME/.zprofile" "$HOME/.zshrc" "$HOME/.bash_profile" "$HOME/.bashrc" "$HOME/.profile"; do
        [ -f "$f" ] && source "$f" 2>/dev/null || true
    done

    export NVM_DIR="${NVM_DIR:-$HOME/.nvm}"
    [ -s "$NVM_DIR/nvm.sh" ] && source "$NVM_DIR/nvm.sh" 2>/dev/null || true

    # Claude Code native path
    [ -d "$HOME/.local/bin" ] && export PATH="$HOME/.local/bin:$PATH"

    if command -v npm &>/dev/null; then
        export PATH="$(npm prefix -g 2>/dev/null)/bin:$PATH"
    fi
}

reload_shell

# ===========================================================================
# Pre-install environment scan — show current state before installation
# ===========================================================================
echo -e "${BOLD}  Scanning your system...${NC}"
echo ""
echo -e "  --- Environment Scan ------------------------------------"
echo ""

TO_INSTALL=()
WORKSPACE_DIR="$HOME/claude-workspace"

# Xcode CLT
printf "    %-18s" "Xcode CLT"
sleep 0.3
if xcode-select -p &>/dev/null; then
    echo -e "${GREEN}OK  $(xcode-select -p)${NC}"
else
    echo -e "${RED}X   Not installed -> will install${NC}"
    TO_INSTALL+=("Xcode CLT")
fi

# Git
printf "    %-18s" "Git"
sleep 0.3
if command -v git &>/dev/null; then
    echo -e "${GREEN}OK  $(git --version)${NC}"
else
    echo -e "${RED}X   Not installed -> will install${NC}"
    TO_INSTALL+=("Git")
fi

# Claude Code
printf "    %-18s" "Claude Code"
sleep 0.3
if command -v claude &>/dev/null || [ -f "$HOME/.local/bin/claude" ]; then
    VER=$(claude --version 2>/dev/null || echo "installed")
    echo -e "${GREEN}OK  ${VER}${NC}"
else
    echo -e "${RED}X   Not installed -> will install${NC}"
    TO_INSTALL+=("Claude Code")
fi

# Homebrew
printf "    %-18s" "Homebrew"
sleep 0.3
if command -v brew &>/dev/null; then
    echo -e "${GREEN}OK  $(brew --version 2>/dev/null | head -1)${NC}"
else
    echo -e "${RED}X   Not installed -> will install${NC}"
    TO_INSTALL+=("Homebrew")
fi

# Node.js
printf "    %-18s" "Node.js"
sleep 0.3
if command -v node &>/dev/null; then
    echo -e "${GREEN}OK  $(node --version)${NC}"
else
    echo -e "${RED}X   Not installed -> will install${NC}"
    TO_INSTALL+=("Node.js")
fi

# GitHub CLI
printf "    %-18s" "GitHub CLI (gh)"
sleep 0.3
if command -v gh &>/dev/null; then
    echo -e "${GREEN}OK  $(gh --version | head -1)${NC}"
else
    echo -e "${RED}X   Not installed -> will install${NC}"
    TO_INSTALL+=("GitHub CLI")
fi

# Workspace folder
printf "    %-18s" "Workspace"
sleep 0.3
if [ -d "$WORKSPACE_DIR" ]; then
    echo -e "${GREEN}OK  $WORKSPACE_DIR${NC}"
else
    echo -e "${RED}X   Not found -> will create${NC}"
    TO_INSTALL+=("Workspace")
fi

echo ""
echo -e "  ---------------------------------------------------------"

SCAN_FOUND=$((7 - ${#TO_INSTALL[@]}))
SCAN_MISSING=${#TO_INSTALL[@]}

if [ "$SCAN_MISSING" -eq 0 ]; then
    echo ""
    echo -e "  ${GREEN}${BOLD}All tools are already installed! Running verification only.${NC}"
    echo ""
else
    echo ""
    echo -e "    ${SCAN_FOUND} detected  /  ${SCAN_MISSING} to install"
    echo -e "    ${YELLOW}Will install: $(IFS=', '; echo "${TO_INSTALL[*]}")${NC}"
    echo ""

    if [ "$TEST_MODE" = false ]; then
        printf "    Proceed with installation? (Y/n): "
        # When running via curl | bash, stdin is a pipe — read directly from /dev/tty, auto-proceed on failure
        read -r CONFIRM_REPLY < /dev/tty 2>/dev/null || CONFIRM_REPLY="y"
        if [[ "$CONFIRM_REPLY" =~ ^[Nn] ]]; then
            echo ""
            echo -e "  ${YELLOW}Installation cancelled.${NC}"
            echo ""
            exit 0
        fi
        echo ""
        echo -e "    ${GREEN}Starting installation!${NC}"
        echo ""
    fi
fi

echo ""

# ===========================================================================
# Step 1: Xcode Command Line Tools (essential macOS dev tools)
# ===========================================================================
echo -e "${BOLD}[1/9] Xcode Command Line Tools (Git, compilers, etc.)${NC}"

if xcode-select -p &>/dev/null; then
    step_ok "Xcode CLT already installed ($(xcode-select -p))"
elif [ "$TEST_MODE" = true ]; then
    step_test "[Test mode] Xcode CLT not installed — skipping"
    step_test "[Test mode] xcode-select status: $(xcode-select -p 2>/dev/null || echo 'not installed')"
else
    step_wait "Attempting to install Xcode Command Line Tools..."
    step_info "If a system popup appears, click 'Install'."
    if xcode-select --install 2>/dev/null; then
        echo ""
        step_info "Xcode CLT installation in progress. (Includes Git, make, and other dev tools)"
        step_info "Please re-run this script after installation completes."
        echo ""
        exit 0
    else
        if xcode-select -p &>/dev/null; then
            step_ok "Xcode CLT installation complete"
        else
            step_fail "Xcode CLT installation failed — manual install: xcode-select --install"
        fi
    fi
fi
echo ""

# ===========================================================================
# Step 2: Git (Claude Code dependency)
# ===========================================================================
echo -e "${BOLD}[2/9] Git (required for Claude Code)${NC}"

if command -v git &>/dev/null; then
    step_ok "Git already installed ($(git --version))"
elif [ "$TEST_MODE" = true ]; then
    step_test "[Test mode] Git not installed — will be included when Xcode CLT is installed"
else
    step_fail "Git not found — please install Xcode CLT first, then re-run this script"
fi
echo ""

# ===========================================================================
# Step 3: Claude Code (native installer preferred)
# ===========================================================================
echo -e "${BOLD}[3/9] Claude Code (native installer)${NC}"

CLAUDE_INSTALLED=false

if command -v claude &>/dev/null; then
    CLAUDE_VER=$(claude --version 2>/dev/null || echo 'version unknown')
    step_ok "Claude Code already installed ($CLAUDE_VER)"
    CLAUDE_INSTALLED=true

    # Detect installation method
    CLAUDE_PATH=$(command -v claude)
    if [[ "$CLAUDE_PATH" == *".local/bin"* ]]; then
        step_info "Install method: native (auto-updates)"
    elif [[ "$CLAUDE_PATH" == *"npm"* ]] || [[ "$CLAUDE_PATH" == *"node_modules"* ]]; then
        step_info "Install method: npm (deprecated — switch to native recommended)"
        step_info "To switch: claude install or curl -fsSL https://claude.ai/install.sh | bash"
    fi
elif [ -f "$HOME/.local/bin/claude" ]; then
    # Installed but not in PATH
    export PATH="$HOME/.local/bin:$PATH"
    CLAUDE_VER=$(claude --version 2>/dev/null || echo 'version unknown')
    step_ok "Claude Code found (not in PATH): $HOME/.local/bin/claude"
    step_info "Adding to PATH."
    CLAUDE_INSTALLED=true
elif [ "$TEST_MODE" = true ]; then
    step_test "[Test mode] Claude Code not installed — skipping"
    step_test "[Test mode] Native path ($HOME/.local/bin/claude): not found"
    step_test "[Test mode] brew available: $(command -v brew &>/dev/null && echo 'Yes' || echo 'No')"
    step_test "[Test mode] npm available: $(command -v npm &>/dev/null && echo "Yes ($(npm --version))" || echo 'No')"
else
    # --- Method 1: Official native installer (recommended) ---
    step_wait "Installing via official native installer... (Node.js not required)"
    if curl -fsSL https://claude.ai/install.sh | bash 2>/dev/null; then
        reload_shell
        [ -d "$HOME/.local/bin" ] && export PATH="$HOME/.local/bin:$PATH"
        if command -v claude &>/dev/null; then
            step_ok "Claude Code installed (native — auto-updates)"
            CLAUDE_INSTALLED=true
        fi
    else
        step_info "Native installer failed"
    fi

    # --- Method 2: Homebrew Cask ---
    if [ "$CLAUDE_INSTALLED" = false ] && command -v brew &>/dev/null; then
        step_wait "Trying Homebrew Cask install..."
        if brew install --cask claude-code 2>/dev/null; then
            reload_shell
            if command -v claude &>/dev/null; then
                step_ok "Claude Code installed (Homebrew — manual update: brew upgrade claude-code)"
                CLAUDE_INSTALLED=true
            fi
        else
            step_info "Homebrew install failed"
        fi
    fi

    # --- Method 3: npm (legacy — requires Node.js) ---
    if [ "$CLAUDE_INSTALLED" = false ] && command -v npm &>/dev/null; then
        step_wait "Trying npm install (legacy)..."
        if npm install -g @anthropic-ai/claude-code 2>/dev/null; then
            reload_shell
            if command -v claude &>/dev/null; then
                step_ok "Claude Code installed (npm — switch to native recommended)"
                CLAUDE_INSTALLED=true
            fi
        else
            step_info "npm install failed"
        fi
    fi

    if [ "$CLAUDE_INSTALLED" = false ]; then
        step_fail "Claude Code installation failed — manual install: curl -fsSL https://claude.ai/install.sh | bash"
    fi
fi
echo ""

# ===========================================================================
# Step 4: Homebrew (package manager)
# ===========================================================================
echo -e "${BOLD}[4/9] Homebrew (package manager)${NC}"

if command -v brew &>/dev/null; then
    step_ok "Homebrew already installed ($(brew --version | head -1))"
elif [ "$TEST_MODE" = true ]; then
    step_test "[Test mode] Homebrew not installed — skipping"
else
    step_wait "Installing Homebrew..."
    if /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"; then
        reload_shell
        if command -v brew &>/dev/null; then
            step_ok "Homebrew installation complete"
        else
            step_fail "Homebrew installed but not found in PATH"
        fi
    else
        step_fail "Homebrew installation failed — install manually at https://brew.sh"
    fi
fi
echo ""

# ===========================================================================
# Step 5: Node.js (optional)
# ===========================================================================
echo -e "${BOLD}[5/9] Node.js (optional)${NC}"

if command -v node &>/dev/null; then
    NODE_VER=$(node --version)
    NODE_MAJOR=$(echo "$NODE_VER" | sed 's/v\([0-9]*\).*/\1/')
    if [ "$NODE_MAJOR" -ge 18 ] 2>/dev/null; then
        step_ok "Node.js already installed ($NODE_VER)"
    else
        step_ok "Node.js $NODE_VER installed — 18+ recommended (current: $NODE_MAJOR)"
    fi
elif [ "$TEST_MODE" = true ]; then
    step_test "[Test mode] Node.js not installed — skipping"
    step_test "[Test mode] brew available: $(command -v brew &>/dev/null && echo 'Yes' || echo 'No')"
else
    step_info "Node.js not found. (Not required for Claude Code, needed for some projects)"
    step_wait "Installing Node.js... (brew install node)"
    if command -v brew &>/dev/null; then
        if brew install node; then
            reload_shell
            if command -v node &>/dev/null; then
                step_ok "Node.js installation complete ($(node --version))"
            else
                step_fail "Node.js installed but verification failed"
            fi
        else
            step_fail "Node.js installation failed — run 'brew install node' manually"
        fi
    else
        step_fail "Cannot install Node.js without Homebrew"
    fi
fi

if command -v npm &>/dev/null; then
    step_ok "npm available ($(npm --version))"
fi
echo ""

# ===========================================================================
# Step 6: GitHub CLI (gh) — GitHub integration
# ===========================================================================
echo -e "${BOLD}[6/9] GitHub CLI (gh) — GitHub integration${NC}"

if command -v gh &>/dev/null; then
    step_ok "GitHub CLI already installed ($(gh --version | head -1))"
elif [ "$TEST_MODE" = true ]; then
    step_test "[Test mode] GitHub CLI not installed — skipping"
else
    if command -v brew &>/dev/null; then
        step_wait "Installing GitHub CLI... (brew install gh)"
        if brew install gh; then
            reload_shell
            if command -v gh &>/dev/null; then
                step_ok "GitHub CLI installation complete ($(gh --version | head -1))"
            else
                step_fail "GitHub CLI installed but verification failed"
            fi
        else
            step_fail "GitHub CLI installation failed — run 'brew install gh' manually"
        fi
    else
        step_fail "Cannot install GitHub CLI without Homebrew"
    fi
fi
echo ""

# ===========================================================================
# Step 7: Terminal info
# ===========================================================================
echo -e "${BOLD}[7/9] Terminal${NC}"
step_ok "You can use the built-in Mac Terminal (Terminal.app)."
step_info "For a better experience, try iTerm2: https://iterm2.com"
echo ""

# ===========================================================================
# Step 8: Create workspace folder
# ===========================================================================
echo -e "${BOLD}[8/9] Workspace folder${NC}"

WORKSPACE_DIR="$HOME/claude-workspace"

if [ -d "$WORKSPACE_DIR" ]; then
    step_ok "Workspace folder already exists ($WORKSPACE_DIR)"
else
    if mkdir -p "$WORKSPACE_DIR"; then
        step_ok "Workspace folder created ($WORKSPACE_DIR)"
    else
        step_fail "Failed to create workspace folder"
    fi
fi

# git init (Claude Code expects a git repo)
if [ -d "$WORKSPACE_DIR" ] && [ ! -d "$WORKSPACE_DIR/.git" ]; then
    if command -v git &>/dev/null; then
        git -C "$WORKSPACE_DIR" init -q 2>/dev/null && step_ok "Git repository initialized" || true
    fi
fi
echo ""

# ===========================================================================
# Step 9: Permanent PATH configuration
# ===========================================================================
echo -e "${BOLD}[9/9] PATH environment variable setup${NC}"
write_log ""
write_log "========== [9/9] PATH environment variable setup =========="

# Determine user shell config file
SHELL_RC=""
if [ -n "$ZSH_VERSION" ] || [ "$SHELL" = "/bin/zsh" ]; then
    SHELL_RC="$HOME/.zshrc"
elif [ -n "$BASH_VERSION" ] || [ "$SHELL" = "/bin/bash" ]; then
    SHELL_RC="$HOME/.bash_profile"
fi
[ -z "$SHELL_RC" ] && SHELL_RC="$HOME/.zshrc"

step_info "Shell config file: $SHELL_RC"

MARKER="# [EASY-CLCO-PATH-SETUP]"
PATHS_ADDED=0

# Also check old marker (backward compatibility)
OLD_MARKER="# [WORKSHOP-PATH-SETUP]"

if grep -q "$MARKER" "$SHELL_RC" 2>/dev/null || grep -q "$OLD_MARKER" "$SHELL_RC" 2>/dev/null; then
    step_ok "PATH configuration already present ($SHELL_RC)"
else
    PATH_BLOCK=""

    # Claude Code native path (~/.local/bin)
    if [ -d "$HOME/.local/bin" ]; then
        if ! grep -q '\.local/bin' "$SHELL_RC" 2>/dev/null; then
            PATH_BLOCK="${PATH_BLOCK}export PATH=\"\$HOME/.local/bin:\$PATH\"\n"
            step_info "Adding Claude Code native path: ~/.local/bin"
            PATHS_ADDED=$((PATHS_ADDED + 1))
        else
            step_ok "Claude Code native path OK: ~/.local/bin"
        fi
    fi

    # Homebrew (Apple Silicon / Intel)
    if [ -f /opt/homebrew/bin/brew ]; then
        if ! grep -q '/opt/homebrew/bin/brew shellenv' "$SHELL_RC" 2>/dev/null; then
            PATH_BLOCK="${PATH_BLOCK}eval \"\$(/opt/homebrew/bin/brew shellenv)\"\n"
            step_info "Adding Homebrew path (Apple Silicon)"
            PATHS_ADDED=$((PATHS_ADDED + 1))
        else
            step_ok "Homebrew path OK"
        fi
    elif [ -f /usr/local/bin/brew ]; then
        if ! grep -q '/usr/local/bin/brew shellenv' "$SHELL_RC" 2>/dev/null; then
            PATH_BLOCK="${PATH_BLOCK}eval \"\$(/usr/local/bin/brew shellenv)\"\n"
            step_info "Adding Homebrew path (Intel)"
            PATHS_ADDED=$((PATHS_ADDED + 1))
        else
            step_ok "Homebrew path OK"
        fi
    fi

    # npm global bin
    if command -v npm &>/dev/null; then
        NPM_PREFIX="$(npm prefix -g 2>/dev/null)/bin"
        if [ -d "$NPM_PREFIX" ]; then
            if ! grep -q "$NPM_PREFIX" "$SHELL_RC" 2>/dev/null; then
                PATH_BLOCK="${PATH_BLOCK}export PATH=\"${NPM_PREFIX}:\$PATH\"\n"
                step_info "Adding npm global path: $NPM_PREFIX"
                PATHS_ADDED=$((PATHS_ADDED + 1))
            else
                step_ok "npm global path OK: $NPM_PREFIX"
            fi
        fi
    fi

    if [ "$PATHS_ADDED" -eq 0 ]; then
        step_ok "All PATHs are correct. Nothing to add."
    elif [ "$TEST_MODE" = true ]; then
        step_test "[Test mode] ${PATHS_ADDED} path(s) need to be added to $SHELL_RC"
        echo -e "$PATH_BLOCK" | while read -r line; do
            [ -n "$line" ] && step_test "  → $line"
        done
    else
        {
            echo ""
            echo "$MARKER"
            echo "# EasyCC — auto-added PATH configuration"
            echo -e "$PATH_BLOCK"
        } >> "$SHELL_RC"

        step_ok "${PATHS_ADDED} path(s) added to $SHELL_RC"
        step_info "Takes effect in a new terminal. (or run: source $SHELL_RC)"
        write_log "Added PATHs:"
        echo -e "$PATH_BLOCK" | while read -r line; do
            [ -n "$line" ] && write_log "  $line"
        done
    fi
fi
echo ""

# ===========================================================================
# claude doctor verification
# ===========================================================================
if command -v claude &>/dev/null; then
    echo -e "${BOLD}Installation verification (claude doctor — up to 30 seconds)${NC}"
    write_log ""
    write_log "========== claude doctor =========="

    DOCTOR_TMP=$(mktemp /tmp/easy-clco-doctor.XXXXXX)
    claude doctor > "$DOCTOR_TMP" 2>&1 &
    DOCTOR_PID=$!
    DOCTOR_WAITED=0
    while kill -0 $DOCTOR_PID 2>/dev/null && [ $DOCTOR_WAITED -lt 30 ]; do
        sleep 1
        DOCTOR_WAITED=$((DOCTOR_WAITED + 1))
    done
    if kill -0 $DOCTOR_PID 2>/dev/null; then
        kill $DOCTOR_PID 2>/dev/null
        wait $DOCTOR_PID 2>/dev/null || true
        step_info "claude doctor timeout (30s) — does not affect normal usage"
    fi
    DOCTOR_OUTPUT=$(cat "$DOCTOR_TMP" 2>/dev/null || true)
    rm -f "$DOCTOR_TMP"

    echo "$DOCTOR_OUTPUT" | head -20
    write_log "$DOCTOR_OUTPUT"
    echo ""
fi

# ===========================================================================
# Final summary
# ===========================================================================
echo -e "${BOLD}${BLUE}══════════════════════════════════════════════════════════${NC}"
echo -e "${BOLD}  Installation Summary${NC}"
echo -e "${BOLD}${BLUE}══════════════════════════════════════════════════════════${NC}"
echo ""

check_tool() {
    local name="$1"
    local cmd="$2"
    if command -v "$cmd" &>/dev/null; then
        echo -e "  ${GREEN}✅ ${name}${NC} — $(command -v "$cmd")"
    else
        echo -e "  ${RED}❌ ${name}${NC} — not installed"
    fi
}

check_tool "Git"         "git"
check_tool "Claude Code" "claude"
check_tool "Homebrew"    "brew"
check_tool "Node.js"     "node"
check_tool "npm"         "npm"
check_tool "GitHub CLI"  "gh"

echo ""

# Write results to log
write_log ""
write_log "========== Final Results =========="
for tool_name in "git" "claude" "brew" "node" "npm" "gh"; do
    if command -v "$tool_name" &>/dev/null; then
        write_log "  $tool_name: OK ($(command -v "$tool_name"))"
    else
        write_log "  $tool_name: not installed"
    fi
done
write_log "Error count: ${#ERRORS[@]}"
write_log "Log ended: $(date '+%Y-%m-%d %H:%M:%S')"

# Error summary
if [ ${#ERRORS[@]} -gt 0 ]; then
    echo -e "${RED}${BOLD}Some items encountered issues:${NC}"
    for err in "${ERRORS[@]}"; do
        echo -e "  ${RED}• $err${NC}"
    done
    echo ""
    echo -e "${YELLOW}Please resolve the issues above and re-run this script.${NC}"
    echo ""
    echo -e "  Full log: ${CYAN}$LOG_FILE${NC}"
    echo ""
else
    echo -e "${GREEN}${BOLD}All installations complete!${NC}"
    echo ""
    echo -e "${BOLD}  Start Claude Code with:${NC}"
    echo ""
    echo -e "    ${CYAN}cd ~/claude-workspace && claude${NC}"
    echo ""
    echo -e "  Full log: ${CYAN}$LOG_FILE${NC}"
    echo ""

    # Auto-launch Claude Code — open in a new terminal window
    if [ "$CLAUDE_INSTALLED" = true ]; then
        echo -e "${BOLD}Launch Claude Code now? (Y/n)${NC}"
        read -r -t 10 REPLY < /dev/tty 2>/dev/null || REPLY="n"
        echo ""
        if [[ "$REPLY" =~ ^[Yy]?$ ]]; then
            # Open in new Terminal window (no stdin issues)
            if osascript -e "tell application \"Terminal\" to do script \"cd ~/claude-workspace && claude\"" 2>/dev/null; then
                step_ok "Claude Code launched in a new terminal window."
            else
                # If osascript fails (permissions, etc.), run directly
                cd "$WORKSPACE_DIR"
                exec claude
            fi
        else
            echo -e "${CYAN}To run later:  cd ~/claude-workspace && claude${NC}"
            echo ""
        fi
    fi
fi
