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



declare(strict_types=1);

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

$batchId = $argv[1] ?? '';
if ($batchId === '') {
    echo "batch_id required\n";
    exit(1);
}

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

$tmpDir = APP_ROOT . '/storage/tmp';
$jobFile = $tmpDir . '/purchase-job-' . $batchId . '.json';
$progressFile = $tmpDir . '/purchase-progress-' . $batchId . '.json';
$pidFile = $tmpDir . '/purchase-pid-' . $batchId . '.pid';

if (!file_exists($jobFile)) {
    error_log("CataloguePurchase: Job file not found: $jobFile");
    exit(1);
}

 
file_put_contents($pidFile, (string) getmypid());

$job = json_decode(file_get_contents($jobFile), true);
if (!$job) {
    error_log("CataloguePurchase: Invalid job data for batch $batchId");
    @unlink($pidFile);
    exit(1);
}

 
 
CatalogueProcessor::runPurchaseJob($batchId);

error_log("CataloguePurchase: Batch $batchId complete");

 
 
$phpBin = PHP_BINARY ?: 'php';
$workerScript = APP_ROOT . '/bin/catalogue-worker.php';
if (is_file($workerScript) && function_exists('exec')) {
    for ($w = 0; $w < 3; $w++) {
        $wPidFile = $tmpDir . '/catalogue-worker-' . $w . '.pid';
        $shouldSpawn = true;
        if (file_exists($wPidFile)) {
            $pid = (int) @file_get_contents($wPidFile);
            if ($pid > 0 && file_exists('/proc/' . $pid)) {
                $shouldSpawn = false;
            }
        }
        if ($shouldSpawn) {
        @exec(escapeshellarg($phpBin) . ' ' . escapeshellarg($workerScript) . ' --worker=' . $w . ' > /dev/null 2>&1 &');
            break;  
        }
    }
}
