#!/bin/bash
#
# Queue worker — picks pending jobs from the `jobs` table and processes them.
#
# Designed for cPanel: runs `--stop-when-empty` so every cron tick exits as
# soon as the queue drains. No long-running processes, no supervisor needed.
#
# Trigger from cPanel Cron Jobs every minute (`* * * * *`).
#
# Configurable via env vars in the cron line:
#   PHP_BIN  Path to the PHP binary (default: php on PATH).
#            Most cPanel hosts need something like:
#              PHP_BIN=/opt/cpanel/ea-php82/root/usr/bin/php
#              PHP_BIN=/usr/local/bin/php82
#            Run `which php` over SSH to find yours.
#   LOG_DIR  Where to write worker stdout/stderr (default: project storage/logs).
#

set -e

# Resolve project root from the wrapper's own location (../../ from this file).
PROJECT_ROOT="$(cd "$(dirname "$0")/../.." && pwd)"
PHP_BIN="${PHP_BIN:-php}"
LOG_DIR="${LOG_DIR:-$PROJECT_ROOT/storage/logs}"
mkdir -p "$LOG_DIR"

cd "$PROJECT_ROOT"

# Append the worker output to a separate log so it doesn't drown the app log.
# Rotated weekly via Laravel's daily channel — fine to keep small here.
exec "$PHP_BIN" artisan queue:work \
    --queue=analyses,analyses-priority,default \
    --stop-when-empty \
    --tries=3 \
    --timeout=300 \
    --memory=512 \
    >> "$LOG_DIR/cron-queue.log" 2>&1
