#!/bin/bash
set -e

# TEC Template Enhancement Deployment Script
# Comprehensive deployment with backup, rollback, and validation procedures

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

# Get script directory
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(dirname "$SCRIPT_DIR")"

# Load environment variables
if [ -f "$PROJECT_ROOT/.env" ]; then
    export $(cat "$PROJECT_ROOT/.env" | sed 's/#.*//g' | xargs)
fi

# Function to display usage
usage() {
    echo "Usage: $0 [staging|production] [options]"
    echo ""
    echo "Environments:"
    echo "  staging    - Deploy to staging server (default)"
    echo "  production - Deploy to production server (requires confirmation)"
    echo ""
    echo "Options:"
    echo "  --skip-backup     - Skip backup creation (not recommended)"
    echo "  --skip-tests      - Skip test suite execution"
    echo "  --force           - Force deployment without validation"
    echo "  --rollback        - Rollback to previous deployment"
    echo ""
    exit 1
}

# Parse arguments
ENVIRONMENT="${1:-staging}"
SKIP_BACKUP=false
SKIP_TESTS=false
FORCE_DEPLOY=false
ROLLBACK=false

for arg in "${@:2}"; do
    case $arg in
        --skip-backup)
            SKIP_BACKUP=true
            ;;
        --skip-tests)
            SKIP_TESTS=true
            ;;
        --force)
            FORCE_DEPLOY=true
            ;;
        --rollback)
            ROLLBACK=true
            ;;
        *)
            echo -e "${RED}Unknown option: $arg${NC}"
            usage
            ;;
    esac
done

# Validate environment
if [ "$ENVIRONMENT" != "staging" ] && [ "$ENVIRONMENT" != "production" ]; then
    echo -e "${RED}Error: Invalid environment '$ENVIRONMENT'${NC}"
    usage
fi

# Set variables based on environment
if [ "$ENVIRONMENT" = "staging" ]; then
    SERVER_IP=$UPSKILL_STAGING_IP
    SSH_USER=$UPSKILL_STAGING_SSH_USER
    SSH_PASS=$UPSKILL_STAGING_PASS
    SERVER_PATH=$UPSKILL_STAGING_PATH
    SITE_URL=$UPSKILL_STAGING_URL
    ENV_NAME="STAGING"
    ENV_COLOR=$YELLOW
else
    SERVER_IP=$UPSKILL_PROD_IP
    SSH_USER=$UPSKILL_PROD_SSH_USER
    SSH_PASS=$UPSKILL_PROD_SSH_PASS
    SERVER_PATH=$UPSKILL_PROD_PATH
    SITE_URL=$UPSKILL_PROD_URL
    ENV_NAME="PRODUCTION"
    ENV_COLOR=$RED
fi

# Validate required variables
if [ -z "$SERVER_IP" ] || [ -z "$SSH_USER" ] || [ -z "$SSH_PASS" ] || [ -z "$SERVER_PATH" ]; then
    echo -e "${RED}Error: Missing required environment variables for $ENVIRONMENT${NC}"
    echo "Please check your .env file"
    exit 1
fi

# Display header
echo -e "${ENV_COLOR}=== TEC TEMPLATE ENHANCEMENT DEPLOYMENT ===${NC}"
echo "Date: $(date)"
echo ""
echo -e "${YELLOW}Target Environment:${NC} ${ENV_COLOR}$ENV_NAME${NC}"
echo -e "${YELLOW}Target Server:${NC} $SERVER_IP"
echo -e "${YELLOW}Site URL:${NC} $SITE_URL"
echo -e "${YELLOW}Deployment Mode:${NC} $([ "$ROLLBACK" = true ] && echo "ROLLBACK" || echo "ENHANCEMENT")"
echo ""

# Production safety check
if [ "$ENVIRONMENT" = "production" ] && [ "$FORCE_DEPLOY" = false ]; then
    echo -e "${RED}⚠️  WARNING: You are about to deploy TEC template enhancements to PRODUCTION!${NC}"
    echo -e "${RED}This will affect the live event creation system at $SITE_URL${NC}"
    echo ""
    echo "Deployment includes:"
    echo "- Enhanced TEC Community Events template"
    echo "- New WordPress field support (excerpt, categories, featured images, tags)"
    echo "- Backend field processors and security managers"
    echo "- Updated JavaScript field population system"
    echo ""
    read -p "Deploy TEC enhancements to production? (y/n): " confirm
    
    if [ "$confirm" != "y" ] && [ "$confirm" != "Y" ]; then
        echo -e "${YELLOW}Deployment cancelled.${NC}"
        exit 0
    fi
fi

# Pre-deployment validation
if [ "$FORCE_DEPLOY" = false ] && [ "$ROLLBACK" = false ]; then
    echo -e "${BLUE}Running pre-deployment validation...${NC}"
    
    # Check if template files exist
    TEMPLATE_FILES=(
        "templates/community-edit-event-enhanced.php"
        "templates/partials/excerpt-field.php"
        "templates/partials/categories-field.php"
        "templates/partials/featured-image-field.php"
        "templates/partials/tags-field.php"
        "includes/tec-fields/class-hvac-tec-field-processor.php"
        "includes/tec-fields/class-hvac-tec-security-manager.php"
    )
    
    for file in "${TEMPLATE_FILES[@]}"; do
        if [ ! -f "$PROJECT_ROOT/$file" ]; then
            echo -e "${RED}❌ Required file missing: $file${NC}"
            exit 1
        else
            echo -e "${GREEN}✅ Found: $file${NC}"
        fi
    done
    
    # Check if test files exist
    if [ "$SKIP_TESTS" = false ]; then
        if [ ! -f "$PROJECT_ROOT/test-enhanced-tec-template.js" ]; then
            echo -e "${YELLOW}⚠️ Test suite not found, tests will be skipped${NC}"
            SKIP_TESTS=true
        fi
    fi
    
    echo -e "${GREEN}✅ Pre-deployment validation passed${NC}"
    echo ""
fi

# Rollback procedure
if [ "$ROLLBACK" = true ]; then
    echo -e "${YELLOW}🔄 Starting rollback procedure...${NC}"
    
    # List available backups
    echo "Checking available backups..."
    sshpass -p "$SSH_PASS" ssh -o StrictHostKeyChecking=no "$SSH_USER@$SERVER_IP" "
        cd $SERVER_PATH/wp-content/plugins
        if [ -d hvac-backups ]; then
            echo 'Available backups:'
            ls -la hvac-backups/ | grep hvac-community-events-backup | tail -5
        else
            echo 'No backups directory found'
        fi
    "
    
    read -p "Enter backup timestamp (YYYYMMDD-HHMMSS) to restore or 'cancel': " backup_timestamp
    
    if [ "$backup_timestamp" = "cancel" ]; then
        echo -e "${YELLOW}Rollback cancelled${NC}"
        exit 0
    fi
    
    # Restore from backup
    echo -e "${YELLOW}Restoring from backup: hvac-community-events-backup-$backup_timestamp${NC}"
    sshpass -p "$SSH_PASS" ssh -o StrictHostKeyChecking=no "$SSH_USER@$SERVER_IP" "
        cd $SERVER_PATH/wp-content/plugins
        if [ -d hvac-backups/hvac-community-events-backup-$backup_timestamp ]; then
            rm -rf hvac-community-events
            cp -r hvac-backups/hvac-community-events-backup-$backup_timestamp hvac-community-events
            chmod -R 755 hvac-community-events
            echo 'Rollback completed successfully'
        else
            echo 'Backup not found!'
            exit 1
        fi
    "
    
    # Reactivate plugin
    echo -e "${YELLOW}Reactivating plugin...${NC}"
    sshpass -p "$SSH_PASS" ssh -o StrictHostKeyChecking=no "$SSH_USER@$SERVER_IP" "
        cd $SERVER_PATH
        wp plugin deactivate hvac-community-events --quiet
        wp plugin activate hvac-community-events --quiet
        wp cache flush --quiet
        echo 'Plugin reactivated'
    "
    
    echo -e "${GREEN}✅ Rollback completed successfully${NC}"
    exit 0
fi

# Create deployment package
echo -e "${BLUE}📦 Creating TEC enhanced deployment package...${NC}"
TEMP_DIR=$(mktemp -d)
PLUGIN_DIR="$TEMP_DIR/hvac-community-events"

# Copy plugin files
mkdir -p "$PLUGIN_DIR"
cp -r "$PROJECT_ROOT/includes" "$PLUGIN_DIR/"
cp -r "$PROJECT_ROOT/templates" "$PLUGIN_DIR/"
cp -r "$PROJECT_ROOT/assets" "$PLUGIN_DIR/"
cp "$PROJECT_ROOT/hvac-community-events.php" "$PLUGIN_DIR/"
cp "$PROJECT_ROOT/README.md" "$PLUGIN_DIR/" 2>/dev/null || true

# Add deployment metadata
cat > "$PLUGIN_DIR/DEPLOYMENT_INFO.txt" << EOF
TEC Template Enhancement Deployment
===================================
Deployment Date: $(date)
Environment: $ENV_NAME
Enhancements:
- Enhanced TEC Community Events template (community-edit-event-enhanced.php)
- WordPress field support (excerpt, categories, featured images, tags)
- Field processors and security managers
- Enhanced JavaScript field population system
- Responsive design and accessibility improvements

Target: 100% field population success rate
EOF

# Create deployment zip
cd "$TEMP_DIR"
zip -r hvac-community-events-enhanced.zip hvac-community-events > /dev/null

echo -e "${GREEN}✅ Deployment package created${NC}"

# Create backup on server
if [ "$SKIP_BACKUP" = false ]; then
    echo -e "${BLUE}💾 Creating backup on server...${NC}"
    BACKUP_TIMESTAMP=$(date +%Y%m%d-%H%M%S)
    sshpass -p "$SSH_PASS" ssh -o StrictHostKeyChecking=no "$SSH_USER@$SERVER_IP" "
        cd $SERVER_PATH/wp-content/plugins
        if [ -d hvac-community-events ]; then
            mkdir -p hvac-backups
            cp -r hvac-community-events hvac-backups/hvac-community-events-backup-$BACKUP_TIMESTAMP
            echo 'Backup created: hvac-community-events-backup-$BACKUP_TIMESTAMP'
        else
            echo 'No existing plugin found to backup'
        fi
    "
    echo -e "${GREEN}✅ Backup created: $BACKUP_TIMESTAMP${NC}"
else
    echo -e "${YELLOW}⚠️ Skipping backup creation${NC}"
fi

# Deploy to server
echo -e "${BLUE}🚀 Deploying TEC enhancements to server...${NC}"

echo "Step 1: Uploading deployment package..."
sshpass -p "$SSH_PASS" ssh -o StrictHostKeyChecking=no "$SSH_USER@$SERVER_IP" "mkdir -p tmp"
sshpass -p "$SSH_PASS" scp -o StrictHostKeyChecking=no "$TEMP_DIR/hvac-community-events-enhanced.zip" "$SSH_USER@$SERVER_IP:tmp/"

echo "Step 2: Extracting and deploying..."
sshpass -p "$SSH_PASS" ssh -o StrictHostKeyChecking=no "$SSH_USER@$SERVER_IP" "
    cd $SERVER_PATH/wp-content/plugins
    mv ~/tmp/hvac-community-events-enhanced.zip .
    rm -rf hvac-community-events
    unzip -q hvac-community-events-enhanced.zip
    chmod -R 755 hvac-community-events
    rm hvac-community-events-enhanced.zip
    echo 'Deployment extracted successfully'
"

echo "Step 3: Setting up TEC template override..."
sshpass -p "$SSH_PASS" ssh -o StrictHostKeyChecking=no "$SSH_USER@$SERVER_IP" "
    cd $SERVER_PATH/wp-content/themes
    ACTIVE_THEME=\$(wp theme status | grep 'Active:' | sed 's/.*Active: //' | awk '{print \$1}')
    echo \"Active theme: \$ACTIVE_THEME\"
    
    # Create tribe template directory in active theme
    mkdir -p \$ACTIVE_THEME/tribe-events/community
    
    # Copy enhanced template to theme directory
    cp $SERVER_PATH/wp-content/plugins/hvac-community-events/templates/community-edit-event-enhanced.php \$ACTIVE_THEME/tribe-events/community/edit-event.php
    
    # Create partials directory
    mkdir -p \$ACTIVE_THEME/tribe-events/community/partials
    cp -r $SERVER_PATH/wp-content/plugins/hvac-community-events/templates/partials/* \$ACTIVE_THEME/tribe-events/community/partials/
    
    echo 'TEC template override installed'
"

echo "Step 4: Clearing cache and activating..."
sshpass -p "$SSH_PASS" ssh -o StrictHostKeyChecking=no "$SSH_USER@$SERVER_IP" "
    cd $SERVER_PATH
    wp cache flush 2>/dev/null || echo 'WP-CLI cache flush not available'
    wp breeze purge --cache=all 2>/dev/null || echo 'Breeze cache plugin not available'
    wp eval 'if (function_exists(\"opcache_reset\")) { opcache_reset(); echo \"OPcache cleared\"; }' 2>/dev/null || echo 'OPcache reset not available'
"

echo "Step 5: Activating plugin and creating pages..."
sshpass -p "$SSH_PASS" ssh -o StrictHostKeyChecking=no "$SSH_USER@$SERVER_IP" "
    cd $SERVER_PATH
    echo 'Deactivating plugin for clean activation...'
    wp plugin deactivate hvac-community-events --quiet
    echo 'Activating plugin with TEC enhancements...'
    wp plugin activate hvac-community-events --quiet
    echo 'Flushing rewrite rules...'
    wp rewrite flush --quiet
    
    if wp plugin list --name=hvac-community-events --status=active --format=count | grep -q '1'; then
        echo '✅ Plugin activated successfully with TEC enhancements'
    else
        echo '❌ Plugin activation failed!'
        exit 1
    fi
"

# Cleanup
rm -rf "$TEMP_DIR"

echo -e "${GREEN}✅ TEC template enhancement deployment completed!${NC}"

# Run tests if not skipped
if [ "$SKIP_TESTS" = false ]; then
    echo ""
    echo -e "${BLUE}🧪 Running enhanced template test suite...${NC}"
    
    cd "$PROJECT_ROOT"
    if command -v node &> /dev/null; then
        echo "Starting comprehensive E2E tests..."
        UPSKILL_STAGING_URL="$SITE_URL" node test-enhanced-tec-template.js || {
            echo -e "${YELLOW}⚠️ Some tests failed, but deployment completed${NC}"
        }
    else
        echo -e "${YELLOW}⚠️ Node.js not available, skipping automated tests${NC}"
        echo "Please run tests manually: UPSKILL_STAGING_URL=\"$SITE_URL\" node test-enhanced-tec-template.js"
    fi
fi

# Final verification
echo ""
echo -e "${BLUE}🔍 Final deployment verification...${NC}"
sshpass -p "$SSH_PASS" ssh -o StrictHostKeyChecking=no "$SSH_USER@$SERVER_IP" "
    cd $SERVER_PATH
    echo 'Checking plugin status...'
    if wp plugin list --name=hvac-community-events --status=active --format=count | grep -q '1'; then
        echo '✅ Plugin is active'
    else
        echo '❌ Plugin is not active'
    fi
    
    echo 'Checking TEC template override...'
    ACTIVE_THEME=\$(wp theme status | grep 'Active:' | sed 's/.*Active: //' | awk '{print \$1}')
    if [ -f \"\$ACTIVE_THEME/tribe-events/community/edit-event.php\" ]; then
        echo '✅ TEC template override is in place'
    else
        echo '❌ TEC template override not found'
    fi
    
    echo 'Checking required pages...'
    if wp post list --post_type=page --name=training-login --format=count | grep -q '1'; then
        echo '✅ Login page exists'
    else
        echo '❌ Login page missing'
    fi
"

# Success summary
echo ""
echo -e "${GREEN}=== TEC ENHANCEMENT DEPLOYMENT COMPLETE! ===${NC}"
echo ""
echo -e "${YELLOW}✅ Enhanced TEC template deployed to ${ENV_COLOR}$ENV_NAME${NC}"
echo ""
echo -e "${YELLOW}Key Enhancements:${NC}"
echo "• 100% WordPress field support (excerpt, categories, featured images, tags)"
echo "• Enhanced responsive design and accessibility"
echo "• Advanced field population system"
echo "• Secure form processing with validation"
echo "• Media library integration"
echo ""
echo -e "${YELLOW}Test URLs:${NC}"
echo "1. Event Creation: ${SITE_URL}events/community/add/"
echo "2. Dashboard: ${SITE_URL}trainer/dashboard/"
echo "3. Login: ${SITE_URL}training-login/"
echo ""

if [ "$ENVIRONMENT" = "production" ]; then
    echo -e "${RED}⚠️  IMPORTANT: This was a PRODUCTION deployment!${NC}"
    echo -e "${RED}Please verify the enhanced template is working correctly${NC}"
fi

echo ""
echo -e "${YELLOW}Rollback command (if needed):${NC}"
echo "$0 $ENVIRONMENT --rollback"
echo ""
echo -e "${YELLOW}Manual test command:${NC}"
echo "UPSKILL_STAGING_URL=\"$SITE_URL\" node test-enhanced-tec-template.js"