#!/usr/bin/env bash
# Install kubectl
# 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 kubectl is already installed
if command -v kubectl &> /dev/null; then
    KUBECTL_VERSION=$(kubectl version --client --short 2>/dev/null || kubectl version --client | head -n 1)
    log "kubectl is already installed: $KUBECTL_VERSION"
    exit 0
fi

info "Installing kubectl..."

# Detect OS
if [[ "$OSTYPE" == "linux-gnu"* ]]; then
    # Linux
    if command -v snap &> /dev/null; then
        info "Installing via snap..."
        sudo snap install kubectl --classic
        log "kubectl installed via snap"
    elif command -v apt-get &> /dev/null; then
        info "Installing via apt..."
        curl -LO "https://dl.k8s.io/release/$(curl -L -s https://dl.k8s.io/release/stable.txt)/bin/linux/amd64/kubectl"
        sudo install -o root -g root -m 0755 kubectl /usr/local/bin/kubectl
        rm kubectl
        log "kubectl installed"
    else
        error "Package manager not found"
    fi
elif [[ "$OSTYPE" == "darwin"* ]]; then
    # macOS
    if command -v brew &> /dev/null; then
        info "Installing via Homebrew..."
        brew install kubectl
        log "kubectl 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 kubectl &> /dev/null; then
    KUBECTL_VERSION=$(kubectl version --client --short 2>/dev/null || echo "installed")
    log "kubectl installed successfully: $KUBECTL_VERSION"
else
    error "kubectl installation failed"
fi

