#!/usr/bin/env bash
set -euo pipefail

# Rustelo Prerequisites Installer (Bootstrap)
# This script installs the minimal requirements to run the Nushell installer

echo "🚀 Rustelo Prerequisites Bootstrap Installer"
echo ""

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

case "$OS" in
    darwin) OS="macos" ;;
    linux) OS="linux" ;;
    msys*|mingw*|cygwin*) OS="windows" ;;
esac

case "$ARCH" in
    x86_64|amd64) ARCH="x86_64" ;;
    arm64|aarch64) ARCH="aarch64" ;;
    armv7*) ARCH="armv7" ;;
esac

echo "Detected: $OS on $ARCH"
echo ""

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

# Install Rust if not present
install_rust() {
    if command_exists rustc && command_exists cargo; then
        echo "✅ Rust already installed: $(rustc --version)"
    else
        echo "📦 Installing Rust..."
        curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y
        source "$HOME/.cargo/env"
        echo "✅ Rust installed successfully"
    fi
}

# Install Node.js and pnpm
install_node() {
    if command_exists node && command_exists pnpm; then
        echo "✅ Node.js and pnpm already installed"
        echo "   Node.js: $(node --version)"
        echo "   pnpm: $(pnpm --version)"
        return
    fi

    echo "📦 Installing Node.js and pnpm..."

    case "$OS" in
        macos)
            if command_exists brew; then
                brew install node
                npm install -g pnpm
            else
                echo "⚠️  Homebrew not found. Please install Node.js manually:"
                echo "   Visit: https://nodejs.org/"
                echo "   Then run: npm install -g pnpm"
                return 1
            fi
            ;;
        linux)
            if command_exists apt; then
                sudo apt update
                sudo apt install -y nodejs npm
                sudo npm install -g pnpm
            elif command_exists dnf; then
                sudo dnf install -y nodejs npm
                sudo npm install -g pnpm
            elif command_exists pacman; then
                sudo pacman -S nodejs npm
                sudo npm install -g pnpm
            else
                echo "⚠️  Package manager not found. Please install Node.js manually:"
                echo "   Visit: https://nodejs.org/"
                echo "   Then run: npm install -g pnpm"
                return 1
            fi
            ;;
        windows)
            echo "⚠️  Please install Node.js manually on Windows:"
            echo "   Visit: https://nodejs.org/"
            echo "   Then run: npm install -g pnpm"
            return 1
            ;;
    esac

    echo "✅ Node.js and pnpm installed successfully"
}

# Install Nushell
install_nushell() {
    if command_exists nu; then
        echo "✅ Nushell already installed: $(nu --version | head -n1)"
        return
    fi

    echo "📦 Installing Nushell..."

    case "$OS" in
        macos)
            if command_exists brew; then
                brew install nushell
            elif command_exists cargo; then
                cargo install nu --features=extra
            else
                install_nushell_binary
            fi
            ;;
        linux)
            if command_exists cargo; then
                cargo install nu --features=extra
            else
                install_nushell_binary
            fi
            ;;
        windows)
            echo "⚠️  Please install Nushell manually on Windows:"
            echo "   Visit: https://github.com/nushell/nushell/releases"
            echo "   Or run: cargo install nu --features=extra"
            return 1
            ;;
    esac

    echo "✅ Nushell installed successfully"
}

# Install Nushell from binary release
install_nushell_binary() {
    echo "  🔽 Installing Nushell from GitHub releases..."

    local version="0.88.1"
    local os_suffix
    local filename

    case "$OS-$ARCH" in
        macos-x86_64) os_suffix="apple-darwin" ;;
        macos-aarch64) os_suffix="apple-darwin" ;;
        linux-x86_64) os_suffix="unknown-linux-gnu" ;;
        linux-aarch64) os_suffix="unknown-linux-gnu" ;;
        *)
            echo "❌ Unsupported platform: $OS-$ARCH"
            echo "   Please install manually: cargo install nu --features=extra"
            return 1
            ;;
    esac

    filename="nu-${version}-${ARCH}-${os_suffix}.tar.gz"
    url="https://github.com/nushell/nushell/releases/download/${version}/${filename}"

    echo "  📥 Downloading: $filename"

    if ! curl -fsSL "$url" | tar -xz; then
        echo "❌ Failed to download Nushell binary"
        echo "   Please install via cargo: cargo install nu --features=extra"
        return 1
    fi

    sudo mv nu /usr/local/bin/
    echo "  ✅ Nushell binary installed to /usr/local/bin/nu"
}

# Install Just command runner
install_just() {
    if command_exists just; then
        echo "✅ Just already installed: $(just --version)"
        return
    fi

    echo "📦 Installing Just command runner..."

    if command_exists cargo; then
        cargo install just
        echo "✅ Just installed via cargo"
    else
        install_just_binary
    fi
}

# Install Just from binary release
install_just_binary() {
    echo "  🔽 Installing Just from GitHub releases..."

    local version="1.16.0"
    local os_suffix

    case "$OS" in
        macos) os_suffix="apple-darwin" ;;
        linux) os_suffix="unknown-linux-musl" ;;
        *)
            echo "❌ Unsupported OS for binary install: $OS"
            echo "   Please install via cargo: cargo install just"
            return 1
            ;;
    esac

    local filename="just-${version}-${ARCH}-${os_suffix}.tar.gz"
    local url="https://github.com/casey/just/releases/download/${version}/${filename}"

    echo "  📥 Downloading: $filename"

    if curl -fsSL "$url" | tar -xz && sudo mv just /usr/local/bin/; then
        echo "  ✅ Just binary installed to /usr/local/bin/just"
    else
        echo "❌ Failed to download Just binary"
        echo "   Please install via cargo: cargo install just"
        return 1
    fi
}

# Update PATH
update_path() {
    echo ""
    echo "🔧 Updating PATH..."

    local cargo_bin="$HOME/.cargo/bin"
    local local_bin="/usr/local/bin"

    # Add to current session
    export PATH="$PATH:$cargo_bin:$local_bin"

    # Determine shell config file
    local shell_config
    case "$SHELL" in
        */zsh) shell_config="$HOME/.zshrc" ;;
        */bash) shell_config="$HOME/.bashrc" ;;
        */fish) shell_config="$HOME/.config/fish/config.fish" ;;
        *) shell_config="$HOME/.bashrc" ;;
    esac

    # Add to shell config if not already present
    local path_export="export PATH=\"\$PATH:$cargo_bin:$local_bin\""
    if ! grep -q "$cargo_bin" "$shell_config" 2>/dev/null; then
        echo "$path_export" >> "$shell_config"
        echo "✅ Added Cargo and local bin to PATH in $shell_config"
    fi
}

# Main installation
main() {
    echo "Starting prerequisite installation..."
    echo ""

    # Install in order
    install_rust
    install_node
    install_nushell
    install_just

    # Update PATH
    update_path

    echo ""
    echo "✅ Bootstrap installation complete!"
    echo ""
    echo "🎯 Next steps:"
    echo "  1. Restart your terminal or run: source ~/.bashrc (or ~/.zshrc)"
    echo "  2. Run full installer: nu scripts/install-prerequisites.nu"
    echo "  3. Verify installation: nu scripts/verify-prerequisites.nu"
    echo "  4. Create your first project: rustelo new my-website"
    echo ""
    echo "📚 Documentation: BUILDING_WEBSITES_WITH_RUSTELO.md"
}

# Run main function
main "$@"
