# Il check iniziale garantisce che i worker siano sempre attivi (es. dopo un crash)
echo "Verificando stato dei worker..."
RUNNING_WORKERS=0
for pid in $(pgrep -u $(whoami) -f "php artisan queue:work"); do
    # Confronto diretto degli inode (robusto a symlink, alias e percorsi diversi)
    if [ "/proc/$pid/cwd" -ef "$PROJECT_DIR" ]; then
        ((RUNNING_WORKERS++))
    fi
done

echo "Worker attivi per questo progetto: $RUNNING_WORKERS"

if [ "$RUNNING_WORKERS" -lt 3 ]; then
    echo "⚠️ Rilevati solo $RUNNING_WORKERS worker attivi (richiesti 3). Avvio ripristino code..."
    
    # Arresto eventuali worker orfani di questo progetto
    for pid in $(pgrep -u $(whoami) -f "php artisan queue:work"); do
        if [ "/proc/$pid/cwd" -ef "$PROJECT_DIR" ]; then
            kill $pid 2>/dev/null
            echo "Terminato worker orfano PID $pid"
        fi
    done
    sleep 2
    
    # Avvio dei 3 worker specifici
    echo "Avvio nuovi worker..."
    nohup php artisan queue:work --queue=scans --memory=1024 --tries=3 --daemon --max-jobs=1000 > storage/logs/queue-scans.log 2>&1 &
    nohup php artisan queue:work --queue=reports --memory=1024 --tries=3 --daemon --max-jobs=1000 > storage/logs/queue-reports.log 2>&1 &
    nohup php artisan queue:work --queue=high-priority,low-priority,default --memory=512 --tries=3 --daemon --max-jobs=1000 > storage/logs/queue-general.log 2>&1 &
    
    echo "✅ Code ripristinate con successo."
fi
