#!/bin/bash

# Download Staging Plugins Script
# Downloads all plugins from staging server and copies them to Docker development environment

set -e

# Load environment variables
if [ -f .env ]; then
    source .env
else
    echo "Error: .env file not found"
    exit 1
fi

echo "=== Downloading Staging Plugins for Development Environment ==="
echo "Staging Server: $UPSKILL_STAGING_IP"
echo "Docker Environment: http://localhost:8080"
echo "================================================================"

# Create temporary directory for plugin downloads
TEMP_PLUGINS_DIR="/tmp/staging-plugins"
rm -rf "$TEMP_PLUGINS_DIR"
mkdir -p "$TEMP_PLUGINS_DIR"

echo "Step 1: Downloading plugin files from staging server..."

# Download all plugins from staging wp-content/plugins directory
echo "Downloading plugins directory..."
sshpass -p "$UPSKILL_STAGING_PASS" scp -r -o StrictHostKeyChecking=no \
    "$UPSKILL_STAGING_SSH_USER@$UPSKILL_STAGING_IP:$UPSKILL_STAGING_PATH/wp-content/plugins" \
    "$TEMP_PLUGINS_DIR/"

if [ $? -ne 0 ]; then
    echo "Error: Failed to download plugins from staging"
    exit 1
fi

echo "✅ Successfully downloaded plugins from staging"

# List downloaded plugins
echo ""
echo "Downloaded plugins:"
ls -la "$TEMP_PLUGINS_DIR/plugins" | grep "^d" | awk '{print "- " $9}' | grep -v "^\- \.$" | grep -v "^\- \.\.$"

echo ""
echo "Step 2: Waiting for WordPress container to be ready..."

# Wait for WordPress container to be ready
max_attempts=30
attempt=1
while [ $attempt -le $max_attempts ]; do
    if curl -s http://localhost:8080 > /dev/null 2>&1; then
        echo "✅ WordPress container is ready"
        break
    else
        echo "Waiting for WordPress container... ($attempt/$max_attempts)"
        sleep 10
        ((attempt++))
    fi
done

if [ $attempt -gt $max_attempts ]; then
    echo "❌ WordPress container failed to start"
    exit 1
fi

echo ""
echo "Step 3: Copying plugins to Docker volume..."

# Get WordPress container volume mount path
CONTAINER_ID=$(docker ps -qf "name=hvac-wordpress-test")
if [ -z "$CONTAINER_ID" ]; then
    echo "Error: WordPress container not found"
    exit 1
fi

echo "WordPress container ID: $CONTAINER_ID"

# Copy plugins to container
echo "Copying plugins to container..."
for plugin_dir in "$TEMP_PLUGINS_DIR/plugins"/*; do
    if [ -d "$plugin_dir" ]; then
        plugin_name=$(basename "$plugin_dir")
        if [ "$plugin_name" != "hvac-community-events" ]; then  # Don't overwrite our development plugin
            echo "Copying plugin: $plugin_name"
            docker cp "$plugin_dir" "$CONTAINER_ID:/var/www/html/wp-content/plugins/"
        else
            echo "Skipping hvac-community-events (using development version)"
        fi
    fi
done

echo "✅ Plugins copied to Docker container"

echo ""
echo "Step 4: Setting correct permissions in container..."

# Set correct permissions
docker exec "$CONTAINER_ID" chown -R www-data:www-data /var/www/html/wp-content/plugins/
docker exec "$CONTAINER_ID" find /var/www/html/wp-content/plugins/ -type d -exec chmod 755 {} \;
docker exec "$CONTAINER_ID" find /var/www/html/wp-content/plugins/ -type f -exec chmod 644 {} \;

echo "✅ Permissions set correctly"

echo ""
echo "Step 5: Installing WP-CLI and activating plugins..."

# Install WP-CLI in container if not present
docker exec "$CONTAINER_ID" bash -c "
if ! command -v wp &> /dev/null; then
    echo 'Installing WP-CLI...'
    curl -O https://raw.githubusercontent.com/wp-cli/wp-cli/v2.8.1/phar/wp-cli.phar
    chmod +x wp-cli.phar
    mv wp-cli.phar /usr/local/bin/wp
fi
"

# Wait for WordPress installation to complete
echo "Waiting for WordPress installation to complete..."
sleep 30

# Get list of plugins to activate from staging
echo "Getting list of active plugins from staging..."
sshpass -p "$UPSKILL_STAGING_PASS" ssh -o StrictHostKeyChecking=no \
    "$UPSKILL_STAGING_SSH_USER@$UPSKILL_STAGING_IP" \
    "cd $UPSKILL_STAGING_PATH && wp plugin list --status=active --field=name" > "$TEMP_PLUGINS_DIR/active_plugins.txt"

if [ $? -eq 0 ]; then
    echo "✅ Retrieved active plugins list from staging"
    echo ""
    echo "Active plugins on staging:"
    cat "$TEMP_PLUGINS_DIR/active_plugins.txt" | sed 's/^/- /'
    
    echo ""
    echo "Activating plugins in development environment..."
    
    # Activate each plugin
    while IFS= read -r plugin_name; do
        if [ -n "$plugin_name" ] && [ "$plugin_name" != "hvac-community-events" ]; then
            echo "Activating plugin: $plugin_name"
            docker exec "$CONTAINER_ID" wp plugin activate "$plugin_name" --allow-root --path=/var/www/html || echo "Warning: Failed to activate $plugin_name"
        fi
    done < "$TEMP_PLUGINS_DIR/active_plugins.txt"
    
    # Always activate our development plugin last
    echo "Activating hvac-community-events plugin..."
    docker exec "$CONTAINER_ID" wp plugin activate hvac-community-events --allow-root --path=/var/www/html || echo "Warning: Failed to activate hvac-community-events"
    
else
    echo "Warning: Could not retrieve active plugins list from staging"
    echo "Manually activating critical plugins..."
    
    # Manually activate critical plugins
    critical_plugins=("the-events-calendar" "event-tickets" "spectra-pro")
    for plugin in "${critical_plugins[@]}"; do
        echo "Activating critical plugin: $plugin"
        docker exec "$CONTAINER_ID" wp plugin activate "$plugin" --allow-root --path=/var/www/html 2>/dev/null || echo "Plugin $plugin not found or failed to activate"
    done
    
    # Activate our development plugin
    echo "Activating hvac-community-events plugin..."
    docker exec "$CONTAINER_ID" wp plugin activate hvac-community-events --allow-root --path=/var/www/html || echo "Warning: Failed to activate hvac-community-events"
fi

echo ""
echo "Step 6: Verifying plugin installation..."

# List active plugins in development environment
echo "Active plugins in development environment:"
docker exec "$CONTAINER_ID" wp plugin list --status=active --allow-root --path=/var/www/html --format=table

echo ""
echo "Step 7: Clean up temporary files..."
rm -rf "$TEMP_PLUGINS_DIR"
echo "✅ Temporary files cleaned up"

echo ""
echo "🎉 SUCCESS: Staging plugins successfully downloaded and installed!"
echo ""
echo "Next steps:"
echo "1. Run: docker exec hvac-wordpress-test wp plugin list --status=active --allow-root --path=/var/www/html"
echo "2. Access development environment: http://localhost:8080"
echo "3. Run comprehensive seeding: ./seed-data.sh dev"
echo "4. Run tests: HEADLESS=true BASE_URL=http://localhost:8080 node test-master-trainer-e2e.js"