#!/bin/bash
########################################
# Queue Worker - LOCAL TESTING VERSION
# Use this for local Mac testing
########################################

PROJECT_ROOT="/Users/charlie/code/showprima"
PID_FILE="$PROJECT_ROOT/storage/queue-worker.pid"
LOG_FILE="$PROJECT_ROOT/storage/logs/queue-worker.log"

cd "$PROJECT_ROOT" || exit 1

echo "========================================="
echo "🧪 LOCAL QUEUE WORKER MONITOR TEST"
echo "========================================="
echo ""

# Check if worker is running using PID file
is_running() {
    if [ -f "$PID_FILE" ]; then
        PID=$(cat "$PID_FILE")
        echo "📄 Found PID file: $PID"

        if ps -p "$PID" > /dev/null 2>&1; then
            echo "✅ Process $PID is running"

            # Check if it's actually a queue:work process
            if ps -p "$PID" -o args= | grep -q "queue:work"; then
                echo "✅ Process is queue:work"
                return 0
            else
                echo "❌ Process exists but is NOT queue:work"
                echo "   Actual process: $(ps -p $PID -o args=)"
            fi
        else
            echo "❌ Process $PID is not running"
        fi

        # PID file exists but process is dead - clean up
        echo "🧹 Cleaning up stale PID file"
        rm -f "$PID_FILE"
    else
        echo "❌ No PID file found at: $PID_FILE"
    fi
    return 1
}

# Start the worker
start_worker() {
    echo ""
    echo "🚀 Starting queue worker..."

    # Kill any orphaned queue:work processes first
    echo "🧹 Checking for orphaned queue:work processes..."
    ORPHANED=$(ps aux | grep "artisan queue:work" | grep -v grep | awk '{print $2}')
    if [ -n "$ORPHANED" ]; then
        echo "   Found orphaned processes: $ORPHANED"
        pkill -f "artisan queue:work" 2>/dev/null
        sleep 1
        echo "   Cleaned up orphaned processes"
    else
        echo "   No orphaned processes found"
    fi

    # Start worker in background and save PID
    echo ""
    echo "📝 Starting worker with command:"
    echo "   php artisan queue:work \\"
    echo "     --queue=critical,emails,default,tickets,bulk \\"
    echo "     --tries=3 \\"
    echo "     --timeout=600 \\"
    echo "     --sleep=3 \\"
    echo "     --max-time=3600 \\"
    echo "     --max-jobs=500"
    echo ""

    nohup php 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 &

    NEW_PID=$!
    echo $NEW_PID > "$PID_FILE"

    echo "✅ Worker started with PID: $NEW_PID"
    echo "📝 PID saved to: $PID_FILE"
    echo "📋 Logs: $LOG_FILE"
    echo ""
    echo "[$(date '+%Y-%m-%d %H:%M:%S')] Worker started with PID $NEW_PID" >> "$LOG_FILE"

    # Verify it's actually running
    sleep 2
    if ps -p "$NEW_PID" > /dev/null 2>&1; then
        echo "✅ Verified: Worker is running"
    else
        echo "❌ WARNING: Worker may have failed to start"
        echo "   Check logs: tail -20 $LOG_FILE"
    fi
}

# Main logic
echo "🔍 Checking queue worker status..."
echo ""

if is_running; then
    echo ""
    echo "========================================="
    echo "✅ Result: Worker is RUNNING"
    echo "========================================="
    exit 0
else
    echo ""
    echo "========================================="
    echo "⚠️ Result: Worker is NOT running"
    echo "========================================="
    echo ""
    echo "[$(date '+%Y-%m-%d %H:%M:%S')] Worker not running - starting..." >> "$LOG_FILE"
    start_worker
    echo ""
    echo "========================================="
    echo "✅ Worker restart complete"
    echo "========================================="
fi
