#!/usr/bin/env bash
#
# Locus Installation Script
# One-line installer: curl -fsSL https://yourdomain.com/install.sh | bash
#
# This script installs Locus with all required dependencies
# Supports: macOS, Linux, WSL

set -e

# Color codes for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
MAGENTA='\033[0;35m'
CYAN='\033[0;36m'
NC='\033[0m' # No Color

# Configuration
NODEJS_MIN_VERSION="18"
NPM_PACKAGE="@leverageaiapps/locus"
COMMAND_NAME="locus"

# Print colored output
print_color() {
    local color=$1
    local message=$2
    echo -e "${color}${message}${NC}"
}

# Print error and exit
error_exit() {
    print_color "$RED" "❌ Error: $1"
    exit 1
}

# Print banner
print_banner() {
    echo ""
    print_color "$CYAN" "╔════════════════════════════════════════╗"
    print_color "$CYAN" "║                                        ║"
    print_color "$CYAN" "║           Locus Installer              ║"
    print_color "$CYAN" "║                                        ║"
    print_color "$CYAN" "╚════════════════════════════════════════╝"
    echo ""
}

# Detect OS
detect_os() {
    local os=""
    if [[ "$OSTYPE" == "darwin"* ]]; then
        os="macos"
    elif [[ "$OSTYPE" == "linux-gnu"* ]] || [[ "$OSTYPE" == "linux" ]]; then
        # Check if running in WSL
        if [[ -n "$WSL_DISTRO_NAME" ]] || grep -qi microsoft /proc/version 2>/dev/null; then
            os="wsl"
        else
            os="linux"
        fi
    else
        error_exit "Unsupported operating system: $OSTYPE"
    fi
    echo "$os"
}

# Detect architecture
detect_arch() {
    local arch=$(uname -m)
    case $arch in
        x86_64|amd64)
            echo "x64"
            ;;
        aarch64|arm64)
            echo "arm64"
            ;;
        *)
            error_exit "Unsupported architecture: $arch"
            ;;
    esac
}

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

# Compare version numbers
version_compare() {
    local version1=$1
    local version2=$2

    if [[ "$version1" == "$version2" ]]; then
        return 0
    fi

    local IFS=.
    local i ver1=($version1) ver2=($version2)

    for ((i=0; i<${#ver1[@]} || i<${#ver2[@]}; i++)); do
        local num1=${ver1[i]:-0}
        local num2=${ver2[i]:-0}

        if ((num1 > num2)); then
            return 1
        elif ((num1 < num2)); then
            return 2
        fi
    done

    return 0
}

# Get Node.js version
get_node_version() {
    if command_exists node; then
        node --version | sed 's/v//'
    else
        echo "0"
    fi
}

# Install Node.js on macOS
install_nodejs_macos() {
    print_color "$YELLOW" "📦 Installing Node.js via Homebrew..."

    # Check if Homebrew is installed
    if ! command_exists brew; then
        print_color "$YELLOW" "🍺 Installing Homebrew first..."
        /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"

        # Add Homebrew to PATH for Apple Silicon Macs
        if [[ -f /opt/homebrew/bin/brew ]]; then
            eval "$(/opt/homebrew/bin/brew shellenv)"
        fi
    fi

    brew install node
    print_color "$GREEN" "✅ Node.js installed successfully"
}

# Install Node.js on Linux/WSL
install_nodejs_linux() {
    print_color "$YELLOW" "📦 Installing Node.js via NodeSource repository..."

    # Detect package manager
    local pkg_manager=""
    if command_exists apt-get; then
        pkg_manager="apt"
    elif command_exists dnf; then
        pkg_manager="dnf"
    elif command_exists yum; then
        pkg_manager="yum"
    elif command_exists zypper; then
        pkg_manager="zypper"
    else
        error_exit "No supported package manager found (apt, dnf, yum, or zypper)"
    fi

    # Install Node.js based on package manager
    case $pkg_manager in
        apt)
            curl -fsSL https://deb.nodesource.com/setup_20.x | sudo -E bash -
            sudo apt-get install -y nodejs
            ;;
        dnf)
            curl -fsSL https://rpm.nodesource.com/setup_20.x | sudo bash -
            sudo dnf install -y nodejs
            ;;
        yum)
            curl -fsSL https://rpm.nodesource.com/setup_20.x | sudo bash -
            sudo yum install -y nodejs
            ;;
        zypper)
            sudo zypper install -y nodejs20
            ;;
    esac

    print_color "$GREEN" "✅ Node.js installed successfully"
}


# Fix npm permissions on Linux
fix_npm_permissions() {
    local os=$1
    if [[ "$os" == "linux" ]] || [[ "$os" == "wsl" ]]; then
        print_color "$YELLOW" "🔧 Configuring npm permissions..."
        mkdir -p ~/.npm-global
        npm config set prefix '~/.npm-global'

        # Add to PATH if not already there
        if ! echo "$PATH" | grep -q "$HOME/.npm-global/bin"; then
            echo 'export PATH=~/.npm-global/bin:$PATH' >> ~/.bashrc
            export PATH=~/.npm-global/bin:$PATH

            # Also update .zshrc if it exists
            if [[ -f ~/.zshrc ]]; then
                echo 'export PATH=~/.npm-global/bin:$PATH' >> ~/.zshrc
            fi
        fi
    fi
}

# Install Locus
install_locus() {
    print_color "$YELLOW" "📦 Installing Locus..."

    # Check if already installed
    if command_exists "$COMMAND_NAME"; then
        print_color "$YELLOW" "🔄 Locus is already installed. Updating to latest version..."
        npm update -g "$NPM_PACKAGE"
    else
        npm install -g "$NPM_PACKAGE"
    fi

    print_color "$GREEN" "✅ Locus installed successfully"
}

# Verify installation
verify_installation() {
    print_color "$YELLOW" "🔍 Verifying installation..."

    # Check Node.js
    if ! command_exists node; then
        error_exit "Node.js installation verification failed"
    fi

    # Check npm
    if ! command_exists npm; then
        error_exit "npm installation verification failed"
    fi


    # Check locus
    if ! command_exists "$COMMAND_NAME"; then
        # Try with full path for Linux/WSL
        if [[ -f ~/.npm-global/bin/$COMMAND_NAME ]]; then
            print_color "$GREEN" "✅ Locus installed at ~/.npm-global/bin/$COMMAND_NAME"
            print_color "$YELLOW" "   Please restart your terminal or run: source ~/.bashrc"
        else
            error_exit "Locus installation verification failed"
        fi
    else
        local version=$($COMMAND_NAME --version 2>/dev/null || echo "unknown")
        print_color "$GREEN" "✅ Locus v$version is ready to use!"
    fi
}

# Print usage instructions
print_usage() {
    echo ""
    print_color "$BLUE" "🎉 Installation complete!"
    echo ""
    print_color "$CYAN" "📖 Quick Start:"
    echo ""
    echo "  Start a terminal session:"
    print_color "$GREEN" "    $COMMAND_NAME"
    echo ""
    echo "  Start with a specific command:"
    print_color "$GREEN" "    $COMMAND_NAME claude"
    print_color "$GREEN" "    $COMMAND_NAME python"
    echo ""
    echo "  Start with a custom PIN:"
    print_color "$GREEN" "    $COMMAND_NAME --pin 123456"
    echo ""
    print_color "$CYAN" "📱 Then scan the QR code with your phone to access your terminal!"
    echo ""
    print_color "$MAGENTA" "📚 Documentation: https://github.com/leverageaiapp/Locus"
    echo ""
}

# Main installation flow
main() {
    print_banner

    # Detect system
    local os=$(detect_os)
    local arch=$(detect_arch)

    print_color "$BLUE" "🖥️  Detected: $os ($arch)"
    echo ""

    # Check and install Node.js if needed
    local node_version=$(get_node_version)
    version_compare "$node_version" "$NODEJS_MIN_VERSION"
    local version_check=$?

    if [[ $version_check -eq 2 ]]; then
        print_color "$YELLOW" "📦 Node.js $node_version is installed but version $NODEJS_MIN_VERSION+ is required"

        case $os in
            macos)
                install_nodejs_macos
                ;;
            linux|wsl)
                install_nodejs_linux
                ;;
        esac
    elif [[ "$node_version" == "0" ]]; then
        print_color "$YELLOW" "📦 Node.js is not installed. Installing..."

        case $os in
            macos)
                install_nodejs_macos
                ;;
            linux|wsl)
                install_nodejs_linux
                ;;
        esac
    else
        print_color "$GREEN" "✅ Node.js $node_version is already installed"
    fi

    # Fix npm permissions on Linux/WSL
    fix_npm_permissions "$os"


    # Install Locus
    install_locus

    # Verify installation
    verify_installation

    # Print usage instructions
    print_usage
}

# Run main function
main "$@"