#!/bin/bash
# Clewso Installer
# Usage: curl -fsSL https://clewso.dev/install.sh | bash
#
# Environment variables:
#   CLEW_VERSION  - Specific version to install (default: latest)
#   CLEW_INSTALL_DIR - Installation directory (default: /usr/local/bin)

set -euo pipefail

VERSION="${CLEW_VERSION:-latest}"
INSTALL_DIR="${CLEW_INSTALL_DIR:-/usr/local/bin}"
REPO="matchdav/clew-engine"

# Colors
RED='\033[0;31m'
GREEN='\033[0;32m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

info() { echo -e "${BLUE}[INFO]${NC} $1"; }
success() { echo -e "${GREEN}[OK]${NC} $1"; }
error() { echo -e "${RED}[ERROR]${NC} $1" >&2; exit 1; }

# Detect OS and Architecture
detect_platform() {
    OS=$(uname -s | tr '[:upper:]' '[:lower:]')
    ARCH=$(uname -m)

    case "$OS" in
        linux) OS="linux" ;;
        darwin) OS="darwin" ;;
        *) error "Unsupported OS: $OS" ;;
    esac

    case "$ARCH" in
        x86_64|amd64) ARCH="amd64" ;;
        aarch64|arm64) ARCH="arm64" ;;
        *) error "Unsupported architecture: $ARCH" ;;
    esac

    info "Detected platform: ${OS}-${ARCH}"
}

# Get latest version if not specified
get_version() {
    if [ "$VERSION" = "latest" ]; then
        info "Fetching latest version..."
        VERSION=$(curl -fsSL "https://api.github.com/repos/${REPO}/releases/latest" | grep '"tag_name"' | sed -E 's/.*"([^"]+)".*/\1/')
        if [ -z "$VERSION" ]; then
            error "Could not determine latest version"
        fi
    fi
    info "Installing version: $VERSION"
}

# Download and install binary
install_binary() {
    local DOWNLOAD_URL="https://github.com/${REPO}/releases/download/${VERSION}/clewso-${OS}-${ARCH}"
    local TMP_FILE=$(mktemp)

    info "Downloading from: $DOWNLOAD_URL"
    
    if ! curl -fsSL "$DOWNLOAD_URL" -o "$TMP_FILE"; then
        # Fallback to pip install if binary not available
        info "Binary not available, falling back to pip install..."
        install_via_pip
        return
    fi

    chmod +x "$TMP_FILE"
    
    # Check if we need sudo
    if [ -w "$INSTALL_DIR" ]; then
        mv "$TMP_FILE" "${INSTALL_DIR}/clewso"
    else
        info "Requesting sudo to install to $INSTALL_DIR"
        sudo mv "$TMP_FILE" "${INSTALL_DIR}/clewso"
    fi

    success "Installed clewso to ${INSTALL_DIR}/clewso"
}

# Fallback: Install via pip
install_via_pip() {
    info "Installing via pip..."
    
    if command -v pipx &> /dev/null; then
        pipx install clewso
        success "Installed via pipx"
    elif command -v uv &> /dev/null; then
        uv tool install clewso
        success "Installed via uv"
    elif command -v pip &> /dev/null; then
        pip install --user clewso
        success "Installed via pip"
    else
        error "No package manager found (pipx, uv, or pip required)"
    fi
}

# Verify installation
verify_install() {
    if command -v clewso &> /dev/null; then
        echo ""
        success "Installation complete!"
        echo ""
        clewso --help
    else
        info "Add ${INSTALL_DIR} to your PATH to use 'clewso'"
    fi
}

# Main
main() {
    echo ""
    echo "🧶 Clewso Installer"
    echo "==================="
    echo ""
    
    detect_platform
    get_version
    install_binary
    verify_install
    
    echo ""
    echo "Get started:"
    echo "  cd your-repo"
    echo "  clewso review --staged"
    echo ""
}

main
