#!/bin/bash

# OpenHands CLI Installation Script
# Usage: curl -fsSL https://install.openhands.dev/install.sh | sh

set -e

# Colors for output (only if output is to a terminal)
if [ -t 1 ]; then
    RED='\033[0;31m'
    GREEN='\033[0;32m'
    YELLOW='\033[1;33m'
    BLUE='\033[0;34m'
    NC='\033[0m' # No Color
else
    RED=''
    GREEN=''
    YELLOW=''
    BLUE=''
    NC=''
fi

# Configuration
GITHUB_REPO="OpenHands/OpenHands-CLI"
VERSION="1.14.0"
BINARY_NAME="openhands"

# Print colored output
print_info() {
    printf "${BLUE}[INFO]${NC} %s\n" "$1"
}

print_success() {
    printf "${GREEN}[SUCCESS]${NC} %s\n" "$1"
}

print_warning() {
    printf "${YELLOW}[WARNING]${NC} %s\n" "$1"
}

print_error() {
    printf "${RED}[ERROR]${NC} %s\n" "$1"
}

# Detect OS
detect_os() {
    case "$(uname -s)" in
        Darwin*)
            echo "macos"
            ;;
        Linux*)
            echo "linux"
            ;;
        *)
            echo "unknown"
            ;;
    esac
}

# Detect architecture
detect_arch() {
    case "$(uname -m)" in
        x86_64|amd64)
            echo "x86_64"
            ;;
        arm64|aarch64)
            echo "arm64"
            ;;
        *)
            echo "unknown"
            ;;
    esac
}

# Check if command exists
command_exists() {
    command -v "$1" >/dev/null 2>&1
}

# Get installation directory
get_install_dir() {
    # Try to install to /usr/local/bin if writable, otherwise use ~/.local/bin
    if [ -w "/usr/local/bin" ] 2>/dev/null; then
        echo "/usr/local/bin"
    else
        # Create ~/.local/bin if it doesn't exist
        mkdir -p "$HOME/.local/bin"
        echo "$HOME/.local/bin"
    fi
}

# Check if directory is in PATH
is_in_path() {
    case ":$PATH:" in
        *":$1:"*) return 0 ;;
        *) return 1 ;;
    esac
}

# Main installation function
main() {
    print_info "Starting OpenHands CLI installation..."
    
    # Check for required commands
    if ! command_exists curl && ! command_exists wget; then
        print_error "Neither curl nor wget is available. Please install one of them and try again."
        exit 1
    fi
    
    # Detect system
    OS=$(detect_os)
    ARCH=$(detect_arch)
    
    print_info "Detected OS: $OS"
    print_info "Detected Architecture: $ARCH"
    
    # Validate OS and architecture combination
    if [ "$OS" = "unknown" ]; then
        print_error "Unsupported operating system: $(uname -s)"
        print_error "OpenHands CLI currently supports macOS and Linux only."
        exit 1
    fi
    
    if [ "$ARCH" = "unknown" ]; then
        print_error "Unsupported architecture: $(uname -m)"
        print_error "OpenHands CLI currently supports x86_64 and ARM64 architectures only."
        exit 1
    fi
    
    # Determine binary name based on OS and architecture
    if [ "$OS" = "macos" ]; then
        if [ "$ARCH" = "arm64" ]; then
            REMOTE_BINARY_NAME="openhands-macos-arm64"
        elif [ "$ARCH" = "x86_64" ]; then
            REMOTE_BINARY_NAME="openhands-macos-intel"
        fi
    elif [ "$OS" = "linux" ]; then
        if [ "$ARCH" = "arm64" ]; then
            REMOTE_BINARY_NAME="openhands-linux-arm64"
        elif [ "$ARCH" = "x86_64" ]; then
            REMOTE_BINARY_NAME="openhands-linux-x86_64"
        fi
    fi
    
    # Get installation directory
    INSTALL_DIR=$(get_install_dir)
    INSTALL_PATH="$INSTALL_DIR/$BINARY_NAME"
    
    print_info "Installing to: $INSTALL_PATH"
    
    # Download URL
    DOWNLOAD_URL="https://github.com/$GITHUB_REPO/releases/download/$VERSION/$REMOTE_BINARY_NAME"
    
    print_info "Downloading OpenHands CLI v$VERSION..."
    
    # Download the binary
    if command_exists curl; then
        if ! curl -fsSL "$DOWNLOAD_URL" -o "$INSTALL_PATH"; then
            print_error "Failed to download OpenHands CLI. Please check your internet connection and try again."
            exit 1
        fi
    else
        if ! wget -q "$DOWNLOAD_URL" -O "$INSTALL_PATH"; then
            print_error "Failed to download OpenHands CLI. Please check your internet connection and try again."
            exit 1
        fi
    fi
    
    # Make it executable
    chmod +x "$INSTALL_PATH"
    
    print_success "OpenHands CLI v$VERSION installed successfully!"
    
    # Check if install directory is in PATH
    if ! is_in_path "$INSTALL_DIR"; then
        print_warning "The installation directory '$INSTALL_DIR' is not in your PATH."
        print_warning "Add the following line to your shell profile (~/.bashrc, ~/.zshrc, etc.):"
        echo ""
        echo "    export PATH=\"$INSTALL_DIR:\$PATH\""
        echo ""
        print_warning "Then restart your terminal or run: source ~/.bashrc (or ~/.zshrc)"
    fi
    
    # Verify installation
    if [ -x "$INSTALL_PATH" ]; then
        print_success "Installation verified. You can now run 'openhands --help' to get started."
        
        # Show version if possible
        if is_in_path "$INSTALL_DIR"; then
            print_info "Version information:"
            "$INSTALL_PATH" --version 2>/dev/null || echo "  OpenHands CLI v$VERSION"
        fi
    else
        print_error "Installation verification failed. Please check permissions and try again."
        exit 1
    fi
    
    print_info "For more information, visit: https://github.com/$GITHUB_REPO"
}

# Run main function
main "$@"