#!/usr/bin/env bash
#
# Install the supervisor worker that runs AI voice-analysis jobs.
#
# Why a separate worker: transcription of a long call takes minutes, while the
# existing ccsystem worker runs with --timeout=120 and would kill the job
# mid-flight. This program listens on the `ai` queue only, with a much longer
# timeout.
#
# Run it on the application server as root:
#
#     bash deploy/ai-voice-queue-worker.sh
#
# It is idempotent: running it again rewrites the same file and restarts the
# program. It never touches the existing /etc/supervisor/conf.d/laravel-queue.conf.

set -euo pipefail

APP_DIR="${APP_DIR:-/var/www/ccsystem}"
QUEUE="${AI_VOICE_QUEUE:-ai}"
PROGRAM="ccsystem-ai-queue"
CONF="/etc/supervisor/conf.d/ccsystem-ai-queue.conf"
LOG="/var/log/ccsystem-ai-queue.log"

if [[ ! -d "$APP_DIR" ]]; then
    echo "ERROR: $APP_DIR does not exist on this host." >&2
    exit 1
fi

if [[ ! -f /etc/supervisor/conf.d/laravel-queue.conf ]]; then
    echo "WARNING: /etc/supervisor/conf.d/laravel-queue.conf is missing — is supervisor the process manager here?" >&2
fi

# Pick the PHP CLI the application already runs under (the existing worker uses
# php8.2 on this box); fall back to whatever `php` resolves to.
PHP_BIN="$(command -v php8.2 || command -v php || true)"
if [[ -z "$PHP_BIN" ]]; then
    echo "ERROR: no PHP CLI found (looked for php8.2 and php)." >&2
    exit 1
fi

if ! command -v supervisorctl >/dev/null 2>&1; then
    echo "ERROR: supervisorctl not found — install supervisor first." >&2
    exit 1
fi

echo "==> Application : $APP_DIR"
echo "==> PHP binary  : $PHP_BIN"
echo "==> Queue       : $QUEUE"
echo "==> Config      : $CONF"

cat > "$CONF" <<EOF
[program:ccsystem-ai-queue]
process_name=%(program_name)s_%(process_num)02d
command=$PHP_BIN $APP_DIR/artisan queue:work database --queue=$QUEUE --sleep=3 --tries=2 --timeout=1800
directory=$APP_DIR
autostart=true
autorestart=true
stopwaitsecs=60
startretries=200
stopasgroup=true
killasgroup=true
user=www-data
redirect_stderr=true
stdout_logfile=$LOG
EOF

chown root:root "$CONF"
chmod 644 "$CONF"

touch "$LOG"
chown www-data:www-data "$LOG" 2>/dev/null || true

echo "==> Reloading supervisor"
supervisorctl reread
supervisorctl update

sleep 2
# process_name carries a _00 suffix, so the group is addressed as name:*
supervisorctl status | grep 'ccsystem-ai-queue' || supervisorctl status "${PROGRAM}:*" || true

cat <<'EOT'

Done. Useful checks:

  supervisorctl status | grep ccsystem-ai-queue           # RUNNING? (the process is ccsystem-ai-queue:ccsystem-ai-queue_00)
  tail -f /var/log/ccsystem-ai-queue.log                  # job output
  sudo -u www-data env HOME=/tmp php /var/www/ccsystem/artisan queue:monitor ai

Pending analyses are rows in call_ai_analyses with status = 'queued'; they are
picked up by this worker within a few seconds.
EOT
