#!/bin/bash

#
# Hive.AI Auto-Installer
# One-command installation for Unix-like systems (Linux, macOS)
#
# Usage:
#   curl -fsSL https://github.com/hivetechs-collective/hive.ai/releases/latest/download/install.sh | bash
#   or 
#   wget -qO- https://github.com/hivetechs-collective/hive.ai/releases/latest/download/install.sh | bash
#

set -e

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

# Configuration
REPO="hivetechs-collective/hive.ai"
BINARY_NAME="hive-tools"
INSTALL_DIR="${HOME}/.local/bin"
CONFIG_DIR="${HOME}/.hive-ai"

# 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="macos"
            ;;
        *)
            echo -e "${RED}❌ Unsupported operating system: $os${NC}"
            echo "Supported platforms: Linux, macOS"
            exit 1
            ;;
    esac
    
    case "$arch" in
        x86_64|amd64)
            ARCH="amd64"
            ;;
        arm64|aarch64)
            ARCH="arm64"
            ;;
        *)
            echo -e "${RED}❌ Unsupported architecture: $arch${NC}"
            echo "Supported architectures: x86_64/amd64, arm64/aarch64"
            exit 1
            ;;
    esac
    
    PLATFORM="${OS}-${ARCH}"
    echo -e "${BLUE}🔍 Detected platform: ${PLATFORM}${NC}"
}

# Check dependencies
check_dependencies() {
    local missing_deps=()
    
    if ! command -v curl >/dev/null 2>&1 && ! command -v wget >/dev/null 2>&1; then
        missing_deps+=("curl or wget")
    fi
    
    if ! command -v tar >/dev/null 2>&1; then
        missing_deps+=("tar")
    fi
    
    if [ ${#missing_deps[@]} -ne 0 ]; then
        echo -e "${RED}❌ Missing required dependencies: ${missing_deps[*]}${NC}"
        echo "Please install the missing dependencies and try again."
        exit 1
    fi
}

# Get latest release info
get_latest_release() {
    echo -e "${BLUE}🔍 Fetching latest release information...${NC}"
    
    if command -v curl >/dev/null 2>&1; then
        RELEASE_INFO=$(curl -s "https://api.github.com/repos/${REPO}/releases/latest")
    elif command -v wget >/dev/null 2>&1; then
        RELEASE_INFO=$(wget -qO- "https://api.github.com/repos/${REPO}/releases/latest")
    fi
    
    if [ -z "$RELEASE_INFO" ]; then
        echo -e "${RED}❌ Failed to fetch release information${NC}"
        exit 1
    fi
    
    # Extract version and download URL
    VERSION=$(echo "$RELEASE_INFO" | grep '"tag_name":' | sed -E 's/.*"tag_name": "([^"]+)".*/\1/')
    DOWNLOAD_URL=$(echo "$RELEASE_INFO" | grep "\"browser_download_url\".*${BINARY_NAME}-${PLATFORM}" | sed -E 's/.*"browser_download_url": "([^"]+)".*/\1/')
    
    if [ -z "$VERSION" ] || [ -z "$DOWNLOAD_URL" ]; then
        echo -e "${RED}❌ Could not find compatible binary for platform: ${PLATFORM}${NC}"
        echo "Available releases at: https://github.com/${REPO}/releases"
        exit 1
    fi
    
    echo -e "${GREEN}✅ Found Hive.AI ${VERSION} for ${PLATFORM}${NC}"
}

# Create installation directory
create_install_dir() {
    if [ ! -d "$INSTALL_DIR" ]; then
        echo -e "${BLUE}📁 Creating installation directory: ${INSTALL_DIR}${NC}"
        mkdir -p "$INSTALL_DIR"
    fi
    
    if [ ! -d "$CONFIG_DIR" ]; then
        echo -e "${BLUE}📁 Creating configuration directory: ${CONFIG_DIR}${NC}"
        mkdir -p "$CONFIG_DIR"
    fi
}

# Download and install binary
install_binary() {
    local temp_file="/tmp/${BINARY_NAME}-${VERSION}"
    
    echo -e "${BLUE}📥 Downloading Hive.AI ${VERSION}...${NC}"
    
    if command -v curl >/dev/null 2>&1; then
        curl -L -o "$temp_file" "$DOWNLOAD_URL"
    elif command -v wget >/dev/null 2>&1; then
        wget -O "$temp_file" "$DOWNLOAD_URL"
    fi
    
    if [ ! -f "$temp_file" ]; then
        echo -e "${RED}❌ Download failed${NC}"
        exit 1
    fi
    
    echo -e "${BLUE}📦 Installing binary to ${INSTALL_DIR}/${BINARY_NAME}...${NC}"
    
    # Make executable and move to install directory
    chmod +x "$temp_file"
    mv "$temp_file" "${INSTALL_DIR}/${BINARY_NAME}"
    
    # Verify installation
    if [ -x "${INSTALL_DIR}/${BINARY_NAME}" ]; then
        echo -e "${GREEN}✅ Hive.AI installed successfully!${NC}"
    else
        echo -e "${RED}❌ Installation verification failed${NC}"
        exit 1
    fi
}

# Update PATH
update_path() {
    local shell_profile=""
    local shell_name=$(basename "$SHELL")
    
    case "$shell_name" in
        bash)
            if [ -f "$HOME/.bashrc" ]; then
                shell_profile="$HOME/.bashrc"
            elif [ -f "$HOME/.bash_profile" ]; then
                shell_profile="$HOME/.bash_profile"
            fi
            ;;
        zsh)
            shell_profile="$HOME/.zshrc"
            ;;
        fish)
            shell_profile="$HOME/.config/fish/config.fish"
            ;;
    esac
    
    # Check if PATH already includes install directory
    if [[ ":$PATH:" != *":$INSTALL_DIR:"* ]]; then
        echo -e "${BLUE}🔧 Adding ${INSTALL_DIR} to PATH...${NC}"
        
        if [ -n "$shell_profile" ]; then
            echo "export PATH=\"\$PATH:${INSTALL_DIR}\"" >> "$shell_profile"
            echo -e "${YELLOW}⚠️  Please restart your terminal or run: source ${shell_profile}${NC}"
        else
            echo -e "${YELLOW}⚠️  Please add ${INSTALL_DIR} to your PATH manually${NC}"
        fi
    else
        echo -e "${GREEN}✅ PATH is already configured${NC}"
    fi
}

# Display success message and next steps
show_success() {
    echo ""
    echo -e "${GREEN}🎉 Hive.AI installation completed successfully!${NC}"
    echo ""
    echo -e "${CYAN}📋 Next Steps:${NC}"
    echo "1. Restart your terminal or run: source ~/.bashrc (or your shell's config file)"
    echo "2. Configure your license key: hive-tools configure"
    echo "3. Set up your IDE integration: hive-tools configure-ide"
    echo "4. Run the onboarding guide: hive-tools onboard"
    echo ""
    echo -e "${CYAN}📚 Quick Start:${NC}"
    echo "  hive-tools --help                 # Show all commands"
    echo "  hive-tools configure              # Set up license key"
    echo "  hive-tools test-providers         # Test API connections"
    echo "  hive-tools consensus \"hello\"      # Try the AI consensus pipeline"
    echo ""
    echo -e "${CYAN}🔗 Resources:${NC}"
    echo "  Documentation: https://github.com/hivetechs-collective/hive.ai#readme"
    echo "  Get License:   https://hivetechs.io/pricing"
    echo "  Support:       https://hivetechs.io/support"
    echo ""
    echo -e "${PURPLE}Welcome to the future of AI development! 🚀${NC}"
}

# Main installation function
main() {
    echo -e "${PURPLE}🐝 Hive.AI Auto-Installer${NC}"
    echo -e "${PURPLE}================================${NC}"
    echo ""
    
    detect_platform
    check_dependencies
    get_latest_release
    create_install_dir
    install_binary
    update_path
    show_success
    
    echo ""
    echo -e "${GREEN}Installation completed in $(date)${NC}"
}

# Run installation
main "$@"