#!/bin/bash

# AutoRia Telegram Bot - Docker Installation Script
# ================================================

set -e  # Exit on any error

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

# Functions
print_header() {
    echo -e "${BLUE}"
    echo "🐳 AutoRia Telegram Bot - Docker Installation"
    echo "=============================================="
    echo -e "${NC}"
}

print_success() {
    echo -e "${GREEN}✅ $1${NC}"
}

print_warning() {
    echo -e "${YELLOW}⚠️  $1${NC}"
}

print_error() {
    echo -e "${RED}❌ $1${NC}"
}

print_info() {
    echo -e "${BLUE}ℹ️  $1${NC}"
}

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

# Check system requirements
check_requirements() {
    print_info "Checking system requirements..."
    
    # Check Docker
    if ! command_exists docker; then
        print_error "Docker is not installed!"
        echo "Please install Docker first: https://docs.docker.com/get-docker/"
        exit 1
    fi
    
    # Check Docker Compose
    if ! command_exists docker-compose && ! docker compose version >/dev/null 2>&1; then
        print_error "Docker Compose is not installed!"
        echo "Please install Docker Compose first: https://docs.docker.com/compose/install/"
        exit 1
    fi
    
    # Check Docker daemon
    if ! docker info >/dev/null 2>&1; then
        print_error "Docker daemon is not running!"
        echo "Please start Docker daemon first"
        exit 1
    fi
    
    # Check available space (need at least 2GB)
    AVAILABLE_SPACE=$(df . | tail -1 | awk '{print $4}')
    if [ "$AVAILABLE_SPACE" -lt 2097152 ]; then  # 2GB in KB
        print_warning "Less than 2GB of free space available. Installation may fail."
    fi
    
    print_success "System requirements check passed"
}

# Create directories
create_directories() {
    print_info "Creating necessary directories..."
    
    mkdir -p logs
    mkdir -p temp
    
    print_success "Directories created"
}

# Setup environment file
setup_env() {
    print_info "Setting up environment configuration..."
    
    if [ ! -f .env ]; then
        if [ -f env.example ]; then
            cp env.example .env
            print_success "Environment file created from template"
        else
            print_error "env.example file not found!"
            exit 1
        fi
    else
        print_info "Environment file already exists"
    fi
}

# Setup database
setup_database() {
    print_info "Setting up database file..."
    
    if [ ! -f database.db ]; then
        touch database.db
        chmod 644 database.db
        print_success "Database file created"
    else
        print_info "Database file already exists"
    fi
}

# Get user input for environment variables
configure_env() {
    print_info "Configuring environment variables..."
    
    echo ""
    echo "Please provide the required configuration:"
    echo ""
    
    # Bot Token
    if grep -q "your_telegram_bot_token_here" .env; then
        read -p "🤖 Enter your Telegram Bot Token: " BOT_TOKEN
        if [ ! -z "$BOT_TOKEN" ]; then
            sed -i "s/your_telegram_bot_token_here/$BOT_TOKEN/" .env
            print_success "Bot token configured"
        else
            print_warning "Bot token not provided - you'll need to edit .env manually"
        fi
    fi
    
    # TurboSMS API Token
    if grep -q "your_turbosms_api_token" .env; then
        read -p "📱 Enter your TurboSMS API Token: " TOKEN_PHONE
        if [ ! -z "$TOKEN_PHONE" ]; then
            sed -i "s/your_turbosms_api_token/$TOKEN_PHONE/" .env
            print_success "TurboSMS API token configured"
        else
            print_warning "TurboSMS API token not provided - you'll need to edit .env manually"
        fi
    fi
    
    # Admin User ID (optional)
    read -p "👤 Enter your Telegram User ID (optional, for admin notifications): " ADMIN_USER_ID
    if [ ! -z "$ADMIN_USER_ID" ]; then
        sed -i "s/your_telegram_user_id/$ADMIN_USER_ID/" .env
        print_success "Admin user ID configured"
    fi
    
    echo ""
    print_info "You can edit .env file later to modify these settings"
}

# Build Docker image
build_image() {
    print_info "Building Docker image (this may take several minutes)..."
    
    if docker-compose build; then
        print_success "Docker image built successfully"
    else
        print_error "Failed to build Docker image"
        exit 1
    fi
}

# Test installation
test_installation() {
    print_info "Testing installation..."
    
    # Start container
    if docker-compose up -d; then
        print_success "Container started"
        
        # Wait for container to be ready
        sleep 10
        
        # Check if container is running
        if docker-compose ps | grep -q "Up"; then
            print_success "Container is running"
            
            # Basic health check
            if docker exec autoria_telegram_bot python -c "import requests; requests.get('https://api.telegram.org', timeout=10)" 2>/dev/null; then
                print_success "Internet connectivity test passed"
            else
                print_warning "Internet connectivity test failed"
            fi
            
            # Stop test container
            docker-compose down
            print_info "Test completed, container stopped"
        else
            print_error "Container failed to start properly"
            print_info "Check logs with: docker-compose logs"
            exit 1
        fi
    else
        print_error "Failed to start container"
        exit 1
    fi
}

# Print final instructions
print_final_instructions() {
    echo ""
    print_success "Installation completed successfully! 🎉"
    echo ""
    echo "Next steps:"
    echo "==========="
    echo ""
    echo "1. Edit .env file if needed:"
    echo "   nano .env"
    echo ""
    echo "2. Start the bot:"
    echo "   make up"
    echo "   # or"
    echo "   docker-compose up -d"
    echo ""
    echo "3. View logs:"
    echo "   make logs"
    echo "   # or"
    echo "   docker-compose logs -f autoria-bot"
    echo ""
    echo "4. Check status:"
    echo "   make status"
    echo "   # or"
    echo "   docker-compose ps"
    echo ""
    echo "5. For help with all available commands:"
    echo "   make help"
    echo ""
    print_info "Full documentation: doc/DOCKER_README.md"
}

# Main installation process
main() {
    print_header
    
    # Check if we're in the right directory
    if [ ! -f "Dockerfile" ] || [ ! -f "docker-compose.yml" ]; then
        print_error "Docker files not found! Please run this script from the project root directory."
        exit 1
    fi
    
    # Run installation steps
    check_requirements
    create_directories
    setup_env
    setup_database
    
    # Ask if user wants to configure now
    echo ""
    read -p "Do you want to configure environment variables now? (y/N): " configure_now
    if [[ "$configure_now" =~ ^[Yy]$ ]]; then
        configure_env
    else
        print_info "Skipping configuration - edit .env file manually before starting"
    fi
    
    # Ask if user wants to build now
    echo ""
    read -p "Do you want to build the Docker image now? (Y/n): " build_now
    if [[ ! "$build_now" =~ ^[Nn]$ ]]; then
        build_image
        
        # Ask if user wants to test
        echo ""
        read -p "Do you want to run installation test? (Y/n): " test_now
        if [[ ! "$test_now" =~ ^[Nn]$ ]]; then
            test_installation
        fi
    fi
    
    print_final_instructions
}

# Handle interrupts
trap 'echo ""; print_error "Installation interrupted"; exit 1' INT TERM

# Run main function
main "$@" 