#!/bin/bash

# Load environment variables from current directory
if [ ! -f .env ]; then
    echo "Error: .env file not found in current directory!"
    exit 1
fi

source .env

# Rest of the original script follows
cat <<'EOF' >> /Users/ben/dev/upskill-event-manager/bin/verify-dev-fixed.sh
# Colors for output
GREEN='\033[0;32m'
RED='\033[0;31m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m'

# Function to check if a command was successful
check_status() {
    if [ $? -eq 0 ]; then
        echo -e "${GREEN}✓ $1${NC}"
        return 0
    else
        echo -e "${RED}✗ $1${NC}"
        return 1
    fi
}

# Function to monitor container logs
monitor_container_logs() {
    local container=$1
    local lines=${2:-50}
    local error_patterns=("error" "fatal" "exception" "failed" "warning")
    local log_output
    
    echo -e "\n${BLUE}Analyzing logs for $container container...${NC}"
    
    # Get recent logs
    log_output=$(docker-compose logs --tail="$lines" "$container")
    
    # Check for errors and warnings
    local error_count=0
    local warning_count=0
    
    for pattern in "${error_patterns[@]}"; do
        local count
        count=$(echo "$log_output" | grep -i "$pattern" | wc -l)
        
        if [ "$pattern" = "warning" ]; then
            warning_count=$((warning_count + count))
        else
            error_count=$((error_count + count))
        fi
    done
    
    # Display log summary
    echo "Log Summary:"
    echo "- Last $lines lines analyzed"
    echo "- Found $error_count errors"
    echo "- Found $warning_count warnings"
    
    # Display recent errors if any
    if [ $error_count -gt 0 ]; then
        echo -e "\n${RED}Recent Errors:${NC}"
        echo "$log_output" | grep -i -E "error|fatal|exception|failed" | tail -n 5
    fi
    
    # Display recent warnings if any
    if [ $warning_count -gt 0 ]; then
        echo -e "\n${YELLOW}Recent Warnings:${NC}"
        echo "$log_output" | grep -i "warning" | tail -n 5
    fi
    
    # Check log disk usage
    local log_size
    log_size=$(docker-compose exec "$container" du -sh /var/log 2>/dev/null | cut -f1)
    echo -e "\nLog directory size: $log_size"
    
    # Return status based on error count
    if [ $error_count -gt 0 ]; then
        return 1
    fi
    return 0
}

echo -e "${YELLOW}Starting development environment verification...${NC}"

# Check if containers are running
echo "Checking Docker containers..."
if ! docker-compose ps | grep -q "wordpress.*Up"; then
    echo -e "${RED}WordPress container is not running${NC}"
    exit 1
fi
if ! docker-compose ps | grep -q "db.*Up"; then
    echo -e "${RED}Database container is not running${NC}"
    exit 1
fi
check_status "Container status check"

# Monitor container logs
echo -e "\n${BLUE}Monitoring container logs...${NC}"
monitor_container_logs wordpress
check_status "WordPress container logs"

monitor_container_logs db
check_status "Database container logs"

# Check log rotation configuration
echo -e "\nChecking log rotation configuration..."
if docker-compose exec wordpress test -f /etc/logrotate.d/wordpress; then
    echo -e "${GREEN}✓ WordPress log rotation configured${NC}"
else
    echo -e "${YELLOW}⚠ WordPress log rotation not configured${NC}"
fi

if docker-compose exec db test -f /etc/logrotate.d/mysql; then
    echo -e "${GREEN}✓ MySQL log rotation configured${NC}"
else
    echo -e "${YELLOW}⚠ MySQL log rotation not configured${NC}"
fi

# Check database connection
echo "Verifying database connection..."
if ! docker-compose exec db mysql -u"$DEV_DB_USER" -p"$DEV_DB_PASSWORD" -e "SELECT 1;" > /dev/null 2>&1; then
    echo -e "${RED}Database connection failed${NC}"
    exit 1
fi
check_status "Database connection"

# Add logrotate configuration for WordPress
echo "Configuring log rotation..."
docker-compose exec wordpress /bin/bash -c 'cat > /etc/logrotate.d/wordpress << EOF
/var/www/html/wp-content/debug.log {
    daily
    missingok
    rotate 7
    compress
    delaycompress
    notifempty
    create 0640 www-data www-data
}
EOF'
check_status "WordPress log rotation configuration"

# Add logrotate configuration for MySQL
docker-compose exec db /bin/bash -c 'cat > /etc/logrotate.d/mysql << EOF
/var/log/mysql/*.log {
    daily
    rotate 7
    missingok
    create 0640 mysql mysql
    compress
    delaycompress
    postrotate
        /usr/bin/mysqladmin --defaults-file=/etc/mysql/debian.cnf flush-logs
    endscript
}
EOF'
check_status "MySQL log rotation configuration"

# Verify WordPress installation
echo "Verifying WordPress installation..."
if ! docker-compose exec wordpress wp core is-installed --allow-root; then
    echo -e "${RED}WordPress is not properly installed${NC}"
    exit 1
fi
check_status "WordPress installation"

# Check WordPress version
echo "Checking WordPress version..."
WP_VERSION=$(docker-compose exec -T wordpress wp core version --allow-root)
echo -e "${GREEN}WordPress version: $WP_VERSION${NC}"

# Verify required plugins
echo "Checking required plugins..."
REQUIRED_PLUGINS=(
    "the-events-calendar"
    "events-calendar-pro"
    "event-tickets"
    "event-tickets-plus"
    "tribe-community-events"
)

for plugin in "${REQUIRED_PLUGINS[@]}"; do
    if ! docker-compose exec wordpress wp plugin is-active "$plugin" --allow-root > /dev/null 2>&1; then
        echo -e "${RED}Required plugin not active: $plugin${NC}"
        exit 1
    fi
    echo -e "${GREEN}✓ Plugin active: $plugin${NC}"
done

# Check site URL configuration
echo "Verifying site URLs..."
SITE_URL=$(docker-compose exec -T wordpress wp option get siteurl --allow-root)
HOME_URL=$(docker-compose exec -T wordpress wp option get home --allow-root)

if [ "$SITE_URL" != "http://localhost:8080" ] || [ "$HOME_URL" != "http://localhost:8080" ]; then
    echo -e "${RED}Site URLs are not correctly set${NC}"
    echo "Current site URL: $SITE_URL"
    echo "Current home URL: $HOME_URL"
    exit 1
fi
check_status "URL configuration"

# Check file permissions
echo "Checking file permissions..."
docker-compose exec wordpress stat -c "%U:%G" /var/www/html | grep -q "www-data:www-data"
check_status "File permissions"

# Test homepage accessibility
echo "Testing homepage accessibility..."
if ! curl -s -I "http://localhost:8080" | grep -q "200 OK"; then
    echo -e "${RED}Homepage is not accessible${NC}"
    exit 1
fi
check_status "Homepage accessibility"

# Check debug settings
echo "Verifying debug settings..."
docker-compose exec wordpress wp config get WP_DEBUG --type=constant | grep -q "true"
check_status "WP_DEBUG setting"

echo -e "${GREEN}Development environment verification completed successfully!${NC}"
echo -e "${YELLOW}Note: Some functionality may require manual testing:${NC}"
echo "1. Log in to WordPress admin (http://localhost:8080/wp-admin)"
echo "2. Create a test event"
echo "3. Test event registration"
echo "4. Verify email functionality"
EOF# Colors for output
GREEN='\033[0;32m'
RED='\033[0;31m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m'

# Function to check if a command was successful
check_status() {
    if [ $? -eq 0 ]; then
        echo -e "${GREEN}✓ $1${NC}"
        return 0
    else
        echo -e "${RED}✗ $1${NC}"
        return 1
    fi
}

# Function to monitor container logs
monitor_container_logs() {
    local container=$1
    local lines=${2:-50}
    local error_patterns=("error" "fatal" "exception" "failed" "warning")
    local log_output
    
    echo -e "\n${BLUE}Analyzing logs for $container container...${NC}"
    
    # Get recent logs
    log_output=$(docker-compose logs --tail="$lines" "$container")
    
    # Check for errors and warnings
    local error_count=0
    local warning_count=0
    
    for pattern in "${error_patterns[@]}"; do
        local count
        count=$(echo "$log_output" | grep -i "$pattern" | wc -l)
        
        if [ "$pattern" = "warning" ]; then
            warning_count=$((warning_count + count))
        else
            error_count=$((error_count + count))
        fi
    done
    
    # Display log summary
    echo "Log Summary:"
    echo "- Last $lines lines analyzed"
    echo "- Found $error_count errors"
    echo "- Found $warning_count warnings"
    
    # Display recent errors if any
    if [ $error_count -gt 0 ]; then
        echo -e "\n${RED}Recent Errors:${NC}"
        echo "$log_output" | grep -i -E "error|fatal|exception|failed" | tail -n 5
    fi
    
    # Display recent warnings if any
    if [ $warning_count -gt 0 ]; then
        echo -e "\n${YELLOW}Recent Warnings:${NC}"
        echo "$log_output" | grep -i "warning" | tail -n 5
    fi
    
    # Check log disk usage
    local log_size
    log_size=$(docker-compose exec "$container" du -sh /var/log 2>/dev/null | cut -f1)
    echo -e "\nLog directory size: $log_size"
    
    # Return status based on error count
    if [ $error_count -gt 0 ]; then
        return 1
    fi
    return 0
}

echo -e "${YELLOW}Starting development environment verification...${NC}"

# Check if containers are running
echo "Checking Docker containers..."
if ! docker-compose ps | grep -q "wordpress.*Up"; then
    echo -e "${RED}WordPress container is not running${NC}"
    exit 1
fi
if ! docker-compose ps | grep -q "db.*Up"; then
    echo -e "${RED}Database container is not running${NC}"
    exit 1
fi
check_status "Container status check"

# Monitor container logs
echo -e "\n${BLUE}Monitoring container logs...${NC}"
monitor_container_logs wordpress
check_status "WordPress container logs"

monitor_container_logs db
check_status "Database container logs"

# Check log rotation configuration
echo -e "\nChecking log rotation configuration..."
if docker-compose exec wordpress test -f /etc/logrotate.d/wordpress; then
    echo -e "${GREEN}✓ WordPress log rotation configured${NC}"
else
    echo -e "${YELLOW}⚠ WordPress log rotation not configured${NC}"
fi

if docker-compose exec db test -f /etc/logrotate.d/mysql; then
    echo -e "${GREEN}✓ MySQL log rotation configured${NC}"
else
    echo -e "${YELLOW}⚠ MySQL log rotation not configured${NC}"
fi

# Check database connection
echo "Verifying database connection..."
if ! docker-compose exec db mysql -u"$DEV_DB_USER" -p"$DEV_DB_PASSWORD" -e "SELECT 1;" > /dev/null 2>&1; then
    echo -e "${RED}Database connection failed${NC}"
    exit 1
fi
check_status "Database connection"

# Add logrotate configuration for WordPress
echo "Configuring log rotation..."
docker-compose exec wordpress /bin/bash -c 'cat > /etc/logrotate.d/wordpress << EOF
/var/www/html/wp-content/debug.log {
    daily
    missingok
    rotate 7
    compress
    delaycompress
    notifempty
    create 0640 www-data www-data
}
EOF'
check_status "WordPress log rotation configuration"

# Add logrotate configuration for MySQL
docker-compose exec db /bin/bash -c 'cat > /etc/logrotate.d/mysql << EOF
/var/log/mysql/*.log {
    daily
    rotate 7
    missingok
    create 0640 mysql mysql
    compress
    delaycompress
    postrotate
        /usr/bin/mysqladmin --defaults-file=/etc/mysql/debian.cnf flush-logs
    endscript
}
EOF'
check_status "MySQL log rotation configuration"

# Verify WordPress installation
echo "Verifying WordPress installation..."
if ! docker-compose exec wordpress wp core is-installed --allow-root; then
    echo -e "${RED}WordPress is not properly installed${NC}"
    exit 1
fi
check_status "WordPress installation"

# Check WordPress version
echo "Checking WordPress version..."
WP_VERSION=$(docker-compose exec -T wordpress wp core version --allow-root)
echo -e "${GREEN}WordPress version: $WP_VERSION${NC}"

# Verify required plugins
echo "Checking required plugins..."
REQUIRED_PLUGINS=(
    "the-events-calendar"
    "events-calendar-pro"
    "event-tickets"
    "event-tickets-plus"
    "tribe-community-events"
)

for plugin in "${REQUIRED_PLUGINS[@]}"; do
    if ! docker-compose exec wordpress wp plugin is-active "$plugin" --allow-root > /dev/null 2>&1; then
        echo -e "${RED}Required plugin not active: $plugin${NC}"
        exit 1
    fi
    echo -e "${GREEN}✓ Plugin active: $plugin${NC}"
done

# Check site URL configuration
echo "Verifying site URLs..."
SITE_URL=$(docker-compose exec -T wordpress wp option get siteurl --allow-root)
HOME_URL=$(docker-compose exec -T wordpress wp option get home --allow-root)

if [ "$SITE_URL" != "http://localhost:8080" ] || [ "$HOME_URL" != "http://localhost:8080" ]; then
    echo -e "${RED}Site URLs are not correctly set${NC}"
    echo "Current site URL: $SITE_URL"
    echo "Current home URL: $HOME_URL"
    exit 1
fi
check_status "URL configuration"

# Check file permissions
echo "Checking file permissions..."
docker-compose exec wordpress stat -c "%U:%G" /var/www/html | grep -q "www-data:www-data"
check_status "File permissions"

# Test homepage accessibility
echo "Testing homepage accessibility..."
if ! curl -s -I "http://localhost:8080" | grep -q "200 OK"; then
    echo -e "${RED}Homepage is not accessible${NC}"
    exit 1
fi
check_status "Homepage accessibility"

# Check debug settings
echo "Verifying debug settings..."
docker-compose exec wordpress wp config get WP_DEBUG --type=constant | grep -q "true"
check_status "WP_DEBUG setting"

echo -e "${GREEN}Development environment verification completed successfully!${NC}"
echo -e "${YELLOW}Note: Some functionality may require manual testing:${NC}"
echo "1. Log in to WordPress admin (http://localhost:8080/wp-admin)"
echo "2. Create a test event"
echo "3. Test event registration"
echo "4. Verify email functionality"
