#!/bin/bash
# macOS installer with improved usability
# Save this file as install.command to make it clickable in Finder

# Change to the directory where the script is located
cd "$(dirname "$0")"

# ANSI color codes
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
RED='\033[0;31m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# Print ASCII art logo
echo -e "${BLUE}"
cat << "EOF"
 ____                      _   ____                      _     _       
/ ___| _ __ ___   __ _ _ __| |_|  _ \ _ __ ___  _ __  ___| |__ (_)_ __  
\___ \| '_ ` _ \ / _` | '__| __| | | | '__/ _ \| '_ \/ __| '_ \| | '_ \ 
 ___) | | | | | | (_| | |  | |_| |_| | | | (_) | |_) \__ \ | | | | |_) |
|____/|_| |_| |_|\__,_|_|   \__|____/|_|  \___/| .__/|___/_| |_|_| .__/ 
                                               |_|               |_|    
EOF
echo -e "${NC}"
echo -e "${GREEN}=== SmartDropship Hyperautomation Platform Installer (macOS) ===${NC}\n"

# Check for permissions and request sudo if needed
check_permissions() {
    if [[ $EUID -ne 0 ]]; then
        echo -e "${YELLOW}Some operations may require administrative privileges${NC}"
        echo -e "You may be prompted for your password"
    fi
}

# Check for Homebrew
check_homebrew() {
    echo -e "\n${BLUE}Checking for Homebrew...${NC}"
    if command -v brew &> /dev/null; then
        echo -e "${GREEN}✓ Homebrew is installed${NC}"
    else
        echo -e "${RED}✗ Homebrew is not installed${NC}"
        install_homebrew
    fi
}

# Install Homebrew
install_homebrew() {
    echo -e "\n${BLUE}Installing Homebrew...${NC}"
    /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
    
    # Add Homebrew to PATH for this session
    if [[ -f /opt/homebrew/bin/brew ]]; then
        eval "$(/opt/homebrew/bin/brew shellenv)"
    elif [[ -f /usr/local/bin/brew ]]; then
        eval "$(/usr/local/bin/brew shellenv)"
    else
        echo -e "${RED}Failed to find Homebrew. Please install manually:${NC}"
        echo -e "${BLUE}https://brew.sh${NC}"
        exit 1
    fi
    
    echo -e "${GREEN}✓ Homebrew installed successfully${NC}"
}

# Check for Docker
check_docker() {
    echo -e "\n${BLUE}Checking for Docker...${NC}"
    if command -v docker &> /dev/null; then
        echo -e "${GREEN}✓ Docker is installed${NC}"
        docker --version
        
        # Check if Docker is running
        if ! docker info &> /dev/null; then
            echo -e "${RED}Docker is installed but not running${NC}"
            echo -e "${YELLOW}Please start Docker Desktop and try again${NC}"
            open -a Docker
            echo -e "Waiting for Docker to start..."
            for i in {1..30}; do
                if docker info &> /dev/null; then
                    echo -e "${GREEN}✓ Docker is now running${NC}"
                    break
                fi
                sleep 2
                if [ $i -eq 30 ]; then
                    echo -e "${RED}Timed out waiting for Docker to start${NC}"
                    echo -e "${YELLOW}Please start Docker Desktop manually and run this script again${NC}"
                    exit 1
                fi
            done
        fi
    else
        echo -e "${RED}✗ Docker is not installed${NC}"
        install_docker
    fi
}

# Install Docker Desktop for Mac
install_docker() {
    echo -e "\n${BLUE}Installing Docker Desktop for Mac...${NC}"
    echo -e "${YELLOW}Would you like to install Docker Desktop? (y/n)${NC}"
    read -r response
    if [[ "$response" =~ ^([yY][eE][sS]|[yY])$ ]]; then
        brew install --cask docker
        echo -e "${GREEN}✓ Docker Desktop installed successfully${NC}"
        echo -e "${YELLOW}Starting Docker Desktop...${NC}"
        open -a Docker
        
        echo -e "Waiting for Docker to start..."
        for i in {1..30}; do
            if docker info &> /dev/null; then
                echo -e "${GREEN}✓ Docker is now running${NC}"
                break
            fi
            sleep 2
            if [ $i -eq 30 ]; then
                echo -e "${RED}Timed out waiting for Docker to start${NC}"
                echo -e "${YELLOW}Please start Docker Desktop manually and run this script again${NC}"
                exit 1
            fi
        done
    else
        echo -e "${RED}Docker is required for this installation.${NC}"
        echo -e "${YELLOW}Please install Docker Desktop manually:${NC}"
        echo -e "${BLUE}https://docs.docker.com/desktop/install/mac-install/${NC}"
        exit 1
    fi
}

# Check for Git
check_git() {
    echo -e "\n${BLUE}Checking for Git...${NC}"
    if command -v git &> /dev/null; then
        echo -e "${GREEN}✓ Git is installed${NC}"
    else
        echo -e "${RED}✗ Git is not installed${NC}"
        install_git
    fi
}

# Install Git
install_git() {
    echo -e "\n${BLUE}Installing Git...${NC}"
    brew install git
    echo -e "${GREEN}✓ Git installed successfully${NC}"
}

# Clone the repository
clone_repository() {
    echo -e "\n${BLUE}Cloning SmartDropship repository...${NC}"
    
    if [ -d "smart-dropship-hyper" ]; then
        echo -e "${YELLOW}Directory already exists. Updating...${NC}"
        cd smart-dropship-hyper
        git pull
        cd ..
    else
        git clone https://github.com/smartdropship/smart-dropship-hyper.git
        if [ $? -ne 0 ]; then
            echo -e "${RED}Failed to clone repository${NC}"
            exit 1
        fi
        echo -e "${GREEN}✓ Repository cloned successfully${NC}"
    fi
}

# Set up environment variables
setup_environment() {
    echo -e "\n${BLUE}Setting up environment variables...${NC}"
    
    cd smart-dropship-hyper
    
    if [ ! -f ".env" ]; then
        echo -e "Creating .env file from template..."
        cp .env.example .env
        
        # Generate random secret keys
        JWT_SECRET=$(openssl rand -hex 32)
        ENCRYPTION_KEY=$(openssl rand -hex 32)
        
        # Update the .env file with random secrets
        sed -i '' "s/JWT_SECRET=.*/JWT_SECRET=$JWT_SECRET/" .env
        sed -i '' "s/ENCRYPTION_KEY=.*/ENCRYPTION_KEY=$ENCRYPTION_KEY/" .env
        
        echo -e "${GREEN}✓ Environment file created successfully${NC}"
    else
        echo -e "${YELLOW}Environment file already exists. Skipping...${NC}"
    fi
    
    cd ..
}

# Start the application
start_application() {
    echo -e "\n${BLUE}Starting SmartDropship Hyperautomation Platform...${NC}"
    
    cd smart-dropship-hyper
    
    echo -e "Building and starting containers..."
    docker-compose up -d --build
    
    if [ $? -ne 0 ]; then
        echo -e "${RED}Failed to start containers${NC}"
        cd ..
        exit 1
    fi
    
    echo -e "\n${GREEN}✓ SmartDropship Hyperautomation Platform started successfully!${NC}"
    
    # Get IP address
    IP_ADDRESS=$(ifconfig | grep "inet " | grep -v 127.0.0.1 | awk '{print $2}' | head -n 1)
    if [ -z "$IP_ADDRESS" ]; then
        IP_ADDRESS="localhost"
    fi
    
    echo -e "\n${GREEN}=============================================================${NC}"
    echo -e "${GREEN}  SmartDropship is now available at:${NC}"
    echo -e "${GREEN}  http://$IP_ADDRESS:3001${NC}"
    echo -e "${GREEN}=============================================================${NC}"
    
    echo -e "\n${YELLOW}Default credentials:${NC}"
    echo -e "Username: ${BLUE}admin@smartdropship.com${NC}"
    echo -e "Password: ${BLUE}password123${NC}"
    echo -e "\n${RED}IMPORTANT: Change these credentials immediately after logging in!${NC}"
    
    # Open in browser automatically
    open "http://$IP_ADDRESS:3001"
    
    cd ..
}

# Main installer flow
main() {
    check_permissions
    check_homebrew
    check_git
    check_docker
    clone_repository
    setup_environment
    start_application
    
    echo -e "\n${GREEN}Installation completed successfully!${NC}"
    echo -e "${YELLOW}Press any key to exit...${NC}"
    read -n 1
}

main