#!/usr/bin/env bash
# Islets CLI Installation Script
# Usage: curl -fsSL https://get-islets.soupilar.com.br/install.sh | sh

set -e

# Configuration
INSTALL_DIR="${INSTALL_DIR:-$HOME/.islets/bin}"
REPO_URL="${REPO_URL:-https://gitlab.com/blintz/islets}"
VERSION="${VERSION:-latest}"
DOWNLOAD_BASE="${REPO_URL}/-/releases"

# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# Helper functions
info() {
    echo -e "${GREEN}[INFO]${NC} $1"
}

warn() {
    echo -e "${YELLOW}[WARN]${NC} $1"
}

error() {
    echo -e "${RED}[ERROR]${NC} $1"
    exit 1
}

# Detect OS and architecture
detect_platform() {
    local os=$(uname -s | tr '[:upper:]' '[:lower:]')
    local arch=$(uname -m)
    
    case "$os" in
        linux*)
            OS="linux"
            ;;
        darwin*)
            OS="darwin"
            ;;
        msys*|mingw*|cygwin*)
            OS="windows"
            ;;
        *)
            error "Unsupported operating system: $os"
            ;;
    esac
    
    case "$arch" in
        x86_64)
            ARCH="amd64"
            ;;
        aarch64|arm64)
            ARCH="arm64"
            ;;
        *)
            error "Unsupported architecture: $arch"
            ;;
    esac
    
    PLATFORM="${OS}-${ARCH}"
    info "Detected platform: ${PLATFORM}"
}

# Determine latest version
get_latest_version() {
    if [ "$VERSION" = "latest" ]; then
        info "Fetching latest version..."
        # For private projects, read version from GitLab Pages
        local latest_tag=$(curl -fsSL "https://get-islets.soupilar.com.br/latest-version.txt" 2>/dev/null | tr -d '\n\r' || echo "")
        
        if [ -n "$latest_tag" ]; then
            VERSION="$latest_tag"
            info "Latest version: $VERSION"
        else
            # No version file found
            error "No releases found. This installation script requires a tagged release.

To install from source using pip (requires Python 3.9+):
  pip install git+${REPO_URL}.git#subdirectory=cli

Or clone and install locally:
  git clone ${REPO_URL}.git
  cd islets/cli
  pip install -e .

Check for releases: ${REPO_URL}/-/releases"
        fi
    fi
}

# Download and install binary
install_binary() {
    info "Installing Islets CLI ${VERSION} for ${PLATFORM}..."
    
    # Create install directory
    mkdir -p "$INSTALL_DIR"
    
    # Determine binary name
    local binary_name="islets"
    if [ "$OS" = "windows" ]; then
        binary_name="islets.exe"
    fi
    
    # Download URL - Use GitLab Pages (publicly accessible even for private repos)
    local download_url="https://get-islets.soupilar.com.br/binaries/islets-${PLATFORM}"
    if [ "$OS" = "windows" ]; then
        download_url="${download_url}.exe"
    fi
    
    info "Downloading from: $download_url"
    
    # Download binary
    local temp_file=$(mktemp)
    if ! curl -fsSL "$download_url" -o "$temp_file"; then
        error "Failed to download binary. Please check the version and try again."
    fi
    
    # Check if the downloaded file is actually a binary (not HTML error page)
    if file "$temp_file" | grep -q "HTML"; then
        rm -f "$temp_file"
        error "Binary not found for ${VERSION}. The build may not have completed yet or artifacts expired.
        
Fallback installation options:
1. Install via pip (requires Python 3.9+):
   pip install git+https://gitlab.com/blintz/islets.git#subdirectory=cli

2. Wait for the next release or check if CI/CD pipeline is running.

See: ${REPO_URL}/-/pipelines"
    fi
    
    # Move to install directory and make executable
    mv "$temp_file" "${INSTALL_DIR}/${binary_name}"
    chmod +x "${INSTALL_DIR}/${binary_name}"
    
    info "Binary installed to: ${INSTALL_DIR}/${binary_name}"
}

# Update PATH configuration
update_path() {
    local shell_config=""
    
    # Detect shell configuration file
    if [ -n "$BASH_VERSION" ]; then
        if [ -f "$HOME/.bashrc" ]; then
            shell_config="$HOME/.bashrc"
        elif [ -f "$HOME/.bash_profile" ]; then
            shell_config="$HOME/.bash_profile"
        fi
    elif [ -n "$ZSH_VERSION" ]; then
        shell_config="$HOME/.zshrc"
    elif [ -f "$HOME/.profile" ]; then
        shell_config="$HOME/.profile"
    fi
    
    # Check if PATH already includes install directory
    if [[ ":$PATH:" != *":$INSTALL_DIR:"* ]]; then
        info "Adding ${INSTALL_DIR} to PATH..."
        
        if [ -n "$shell_config" ]; then
            # Check if the entry already exists in the config file
            if grep -q "# Islets CLI" "$shell_config" 2>/dev/null; then
                info "PATH entry already exists in ${shell_config} ✓"
            else
                echo "" >> "$shell_config"
                echo "# Islets CLI" >> "$shell_config"
                echo "export PATH=\"\$HOME/.islets/bin:\$PATH\"" >> "$shell_config"
                info "Updated ${shell_config}"
                warn "Please restart your shell or run: source ${shell_config}"
            fi
        else
            warn "Could not detect shell configuration file."
            warn "Please manually add to your PATH:"
            echo -e "${BLUE}  export PATH=\"\$HOME/.islets/bin:\$PATH\"${NC}"
        fi
    else
        info "PATH already includes ${INSTALL_DIR} ✓"
    fi
}

# Verify installation
verify_installation() {
    info "Verifying installation..."
    
    local islets_bin="${INSTALL_DIR}/islets"
    if [ "$OS" = "windows" ]; then
        islets_bin="${INSTALL_DIR}/islets.exe"
    fi
    
    if [ -x "$islets_bin" ]; then
        # Temporarily add to PATH for verification
        export PATH="${INSTALL_DIR}:${PATH}"
        
        if command -v islets &> /dev/null; then
            local version_output=$(islets --version 2>&1 || echo "")
            info "Successfully installed Islets CLI ✓"
            info "Version: ${version_output}"
            return 0
        fi
    fi
    
    error "Installation failed. Binary not found or not executable."
}

# Main installation flow
main() {
    echo ""
    echo "╔═══════════════════════════════════════╗"
    echo "║      Islets CLI Installation          ║"
    echo "╚═══════════════════════════════════════╝"
    echo ""
    
    detect_platform
    get_latest_version
    install_binary
    update_path
    verify_installation
    
    echo ""
    echo -e "${GREEN}╔════════════════════════════════════════════╗${NC}"
    echo -e "${GREEN}║  Installation Complete! 🎉                 ║${NC}"
    echo -e "${GREEN}╚════════════════════════════════════════════╝${NC}"
    echo ""
    info "Next steps:"
    echo "  1. Restart your shell or run: source ~/.bashrc (or ~/.zshrc)"
    echo "  2. Verify: islets --version"
    echo "  3. Get started: islets --help"
    echo ""
    info "Quick start:"
    echo "  ${BLUE}islets new service --name=\"myservice\" --team=\"myteam\"${NC}"
    echo "  ${BLUE}cd myservice${NC}"
    echo "  ${BLUE}islets new consumer --service=\"myservice\" --event=\"listing.sold\"${NC}"
    echo ""
    info "Documentation: ${REPO_URL}/-/blob/main/README.md"
}

# Run installation
main
