#!/bin/bash
########################################
# Queue Worker - Cron Compatible
# Simple version that works reliably with cron
########################################

# Get the directory where this script lives
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(dirname "$SCRIPT_DIR")"
PID_FILE="$PROJECT_ROOT/storage/queue-worker.pid"
LOG_FILE="$PROJECT_ROOT/storage/logs/queue-worker.log"

# Load cron context library
source "$SCRIPT_DIR/_cron-context.sh" 2>/dev/null || true

cd "$PROJECT_ROOT" || exit 1

# Detect correct PHP binary (CLI, not CGI)
# On cPanel, "php" resolves to php-cgi which has execution time limits
# We need the CLI binary for long-running queue workers
if [ -f "/opt/cpanel/ea-php82/root/usr/bin/php" ]; then
    PHP_BIN="/opt/cpanel/ea-php82/root/usr/bin/php"
elif [ -f "/opt/cpanel/ea-php81/root/usr/bin/php" ]; then
    PHP_BIN="/opt/cpanel/ea-php81/root/usr/bin/php"
else
    # Local development or non-cPanel server
    PHP_BIN="php"
fi

# Check if worker is running using PID file
is_running() {
    if [ -f "$PID_FILE" ]; then
        PID=$(cat "$PID_FILE")
        if ps -p "$PID" > /dev/null 2>&1; then
            # Check if it's actually a queue:work process
            if ps -p "$PID" -o args= | grep -q "queue:work"; then
                return 0
            fi
        fi
        # PID file exists but process is dead - clean up
        rm -f "$PID_FILE"
    fi
    return 1
}

# Start the worker
start_worker() {
    # Kill any orphaned queue:work processes first (only from this project)
    pkill -f "$PROJECT_ROOT.*artisan queue:work" 2>/dev/null
    sleep 1

    # Start worker in background and save PID
    # Use detected PHP CLI binary (not php-cgi which has time limits)
    nohup "$PHP_BIN" artisan queue:work \
        --queue=critical,emails,default,tickets,bulk \
        --tries=3 \
        --timeout=600 \
        --sleep=3 \
        --max-time=3600 \
        --max-jobs=500 \
        >> "$LOG_FILE" 2>&1 &

    echo $! > "$PID_FILE"

    echo "[$(date '+%Y-%m-%d %H:%M:%S')] Worker started with PID $!" >> "$LOG_FILE"
}

# Main logic
if is_running; then
    # Worker is running - do nothing (silent success)
    exit 0
else
    # Worker is not running - start it (output context for email)
    get_cron_context "$PROJECT_ROOT" 2>/dev/null || true
    echo "⚠️  Queue worker was not running - restarting..."
    echo ""
    echo "[$(date '+%Y-%m-%d %H:%M:%S')] Worker not running - starting..." >> "$LOG_FILE"
    start_worker

    if [ $? -eq 0 ]; then
        cron_success "Queue worker restarted successfully" "queue-worker-cron.sh" 2>/dev/null || echo "✅ Worker restarted"
    else
        cron_error "Failed to start queue worker" "queue-worker-cron.sh" 2>/dev/null || echo "❌ Worker start failed"
        exit 1
    fi
fi
