#!/usr/bin/env bash
# Install Helm 3.x
# Supports multiple installation methods

set -euo pipefail

# Colors

log() {
    log_success "[✓] $1"
}

error() {
    log_error "[✗] $1"
    exit 1
}

info() {
    log_info "[i] $1"
}

# Check if Helm is already installed
if command -v helm &> /dev/null; then
    HELM_VERSION=$(helm version --short 2>/dev/null || helm version | head -n 1)
    log "Helm is already installed: $HELM_VERSION"
    exit 0
fi

info "Installing Helm..."

# Detect OS
if [[ "$OSTYPE" == "linux-gnu"* ]]; then
    # Linux
    if command -v snap &> /dev/null; then
        info "Installing via snap..."
        sudo snap install helm --classic
        log "Helm installed via snap"
    else
        info "Installing via script..."
        curl https://raw.githubusercontent.com/helm/helm/main/scripts/get-helm-3 | bash
        log "Helm installed via script"
    fi
elif [[ "$OSTYPE" == "darwin"* ]]; then
    # macOS
    if command -v brew &> /dev/null; then
        info "Installing via Homebrew..."
        brew install helm
        log "Helm installed via Homebrew"
    else
        error "Homebrew not found. Please install Homebrew first: https://brew.sh"
    fi
else
    error "Unsupported OS: $OSTYPE"
fi

# Verify installation
if command -v helm &> /dev/null; then
    HELM_VERSION=$(helm version --short 2>/dev/null || echo "installed")
    log "Helm installed successfully: $HELM_VERSION"
else
    error "Helm installation failed"
fi

