#!/bin/bash
###############################################################################
# Docker EasyStream Complete Setup Script
# Fixes 404 issues and sets up the complete system in Docker containers
###############################################################################

echo "🐳 EasyStream Docker Complete Setup"
echo "===================================="

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

# Function to print colored output
print_status() {
    echo -e "${GREEN}[INFO]${NC} $1"
}

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

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

print_step() {
    echo -e "${BLUE}[STEP]${NC} $1"
}

# Check if Docker and Docker Compose are available
check_docker() {
    print_step "Checking Docker environment..."
    
    if ! command -v docker &> /dev/null; then
        print_error "Docker is not installed or not in PATH"
        exit 1
    fi
    
    if ! command -v docker-compose &> /dev/null; then
        print_error "Docker Compose is not installed or not in PATH"
        exit 1
    fi
    
    print_status "Docker environment OK"
}

# Stop existing containers
stop_containers() {
    print_step "Stopping existing containers..."
    docker-compose down
    print_status "Containers stopped"
}

# Build and start containers
start_containers() {
    print_step "Building and starting containers..."
    docker-compose up -d --build
    
    # Wait for containers to be ready
    print_step "Waiting for containers to be ready..."
    sleep 10
    
    # Check container status
    print_step "Checking container status..."
    docker-compose ps
}

# Wait for database to be ready
wait_for_database() {
    print_step "Waiting for database to be ready..."
    
    local max_attempts=30
    local attempt=1
    
    while [ $attempt -le $max_attempts ]; do
        if docker exec vs-db mysqladmin ping -h 127.0.0.1 -u root -proot --silent; then
            print_status "Database is ready"
            return 0
        fi
        
        echo -n "."
        sleep 2
        ((attempt++))
    done
    
    print_error "Database failed to start within expected time"
    return 1
}

# Setup database
setup_database() {
    print_step "Setting up database..."
    
    # Run database setup scripts
    print_status "Running database initialization scripts..."
    
    # Check if tables exist, if not create them
    docker exec vs-db mysql -u easystream -peasystream easystream -e "SHOW TABLES;" > /dev/null 2>&1
    if [ $? -ne 0 ]; then
        print_warning "Database tables not found, creating..."
        docker exec vs-db mysql -u easystream -peasystream easystream < deploy/create_missing_tables.sql
        docker exec vs-db mysql -u easystream -peasystream easystream < deploy/init_settings.sql
    fi
    
    # Setup token system
    print_status "Setting up token system..."
    docker exec vs-php php -f /srv/easystream/deploy/create_token_system.sql 2>/dev/null || true
    
    print_status "Database setup complete"
}

# Fix container routing and permissions
fix_container_routing() {
    print_step "Fixing container routing and 404 issues..."
    
    # Run the container diagnostic
    print_status "Running container diagnostics..."
    docker exec vs-php php /srv/easystream/docker_diagnose_404.php > container_diagnostic.html
    
    # Apply container fixes
    print_status "Applying container fixes..."
    docker exec vs-php php /srv/easystream/docker_fix_404.php > container_fixes.html
    
    # Fix file permissions
    print_status "Fixing file permissions..."
    docker exec vs-php chmod 644 /srv/easystream/*.php
    docker exec vs-php chmod 755 /srv/easystream/f_*
    docker exec vs-php chown -R www-data:www-data /srv/easystream 2>/dev/null || true
    
    print_status "Container routing fixes applied"
}

# Test URLs
test_urls() {
    print_step "Testing container URLs..."
    
    # Wait a moment for services to restart
    sleep 5
    
    # Run URL tests
    docker exec vs-php php /srv/easystream/docker_test_urls.php > container_url_tests.html
    
    # Test main URLs
    local main_url="http://localhost:8083"
    
    print_status "Testing main URLs..."
    echo "Testing: $main_url"
    
    local urls=(
        "$main_url"
        "$main_url/browse"
        "$main_url/search"
        "$main_url/token_purchase"
        "$main_url/admin"
        "$main_url/health"
    )
    
    for url in "${urls[@]}"; do
        local status_code=$(curl -s -o /dev/null -w "%{http_code}" "$url" 2>/dev/null || echo "000")
        
        if [ "$status_code" = "200" ] || [ "$status_code" = "302" ]; then
            print_status "✅ $url - HTTP $status_code"
        else
            print_warning "⚠️  $url - HTTP $status_code"
        fi
    done
}

# Display final status
display_final_status() {
    print_step "Final setup status..."
    
    echo ""
    echo "🎉 EasyStream Docker Setup Complete!"
    echo "===================================="
    echo ""
    echo "📊 Container Status:"
    docker-compose ps
    echo ""
    echo "🌐 Access URLs:"
    echo "  Main Site: http://localhost:8083"
    echo "  Browse: http://localhost:8083/browse"
    echo "  Token Purchase: http://localhost:8083/token_purchase"
    echo "  Admin Panel: http://localhost:8083/admin"
    echo "  Health Check: http://localhost:8083/health"
    echo ""
    echo "🔧 Management Commands:"
    echo "  View logs: docker-compose logs -f"
    echo "  Enter PHP container: docker exec -it vs-php bash"
    echo "  Restart services: docker-compose restart"
    echo ""
    echo "📋 Generated Reports:"
    echo "  Container Diagnostic: container_diagnostic.html"
    echo "  Applied Fixes: container_fixes.html"
    echo "  URL Test Results: container_url_tests.html"
    echo ""
    echo "🆘 Troubleshooting:"
    echo "  If URLs don't work, check: docker-compose logs php caddy"
    echo "  Re-run fixes: docker exec -it vs-php php docker_fix_404.php"
    echo "  Re-run diagnostics: docker exec -it vs-php php docker_diagnose_404.php"
}

# Main execution
main() {
    echo "Starting EasyStream Docker setup..."
    echo ""
    
    check_docker
    stop_containers
    start_containers
    
    if wait_for_database; then
        setup_database
        fix_container_routing
        
        # Restart containers after fixes
        print_step "Restarting containers after fixes..."
        docker-compose restart php caddy
        sleep 5
        
        test_urls
        display_final_status
    else
        print_error "Setup failed - database not ready"
        exit 1
    fi
}

# Run main function
main "$@"