#!/usr/bin/env php
<?php



declare(strict_types=1);

if (php_sapi_name() !== 'cli') {
    echo "CLI only\n";
    exit(1);
}

 
$workerNum = 1;
foreach ($argv ?? [] as $arg) {
    if (preg_match('/^--worker=(\d+)$/', $arg, $m)) {
        $workerNum = (int) $m[1];
    }
}

require dirname(__DIR__) . '/config/php-guard.php';  
require dirname(__DIR__) . '/config/app.php';

$tmpDir = APP_ROOT . '/storage/tmp';
if (!is_dir($tmpDir)) {
    mkdir($tmpDir, 0755, true);
}

$pidFile = $tmpDir . '/catalogue-worker-' . $workerNum . '.pid';
file_put_contents($pidFile, (string) getmypid());

$respawned = false;
try {
     
    Database::reconnect();

    error_log("CatalogueProcessor: Worker #{$workerNum} started (PID " . getmypid() . ")");
     
     
     
     
    while (true) {
        $reason = CatalogueProcessor::workerLoop();
        if ($reason !== 'timeout') {
            break;  
        }
        if (memory_get_usage(true) > 256 * 1048576) {
            $respawned = true;
            @unlink($pidFile);
            @exec(escapeshellarg(PHP_BINARY) . ' ' . escapeshellarg(__FILE__) . ' --worker=' . $workerNum . ' > /dev/null 2>&1 &');
            error_log("CatalogueProcessor: Worker #{$workerNum} handed over (memory)");
            break;
        }
        try { Database::reconnect(); } catch (\Throwable $e) { sleep(3); }
    }
    if (!$respawned) {
        error_log("CatalogueProcessor: Worker #{$workerNum} finished");
    }
} finally {
    if (!$respawned) {
        @unlink($pidFile);
    }
}
