<?php
declare(strict_types=1);

/**
 * Background worker — called by upload.php via exec()
 * Usage: php process.php <job_id>
 */

// Only run from CLI
if (PHP_SAPI !== 'cli') {
    http_response_code(403);
    exit('CLI only');
}

require_once __DIR__ . '/includes/config.php';
require_once __DIR__ . '/includes/db.php';
require_once __DIR__ . '/includes/logger.php';
require_once __DIR__ . '/includes/scraper.php';
require_once __DIR__ . '/includes/excel_writer.php';
require_once __DIR__ . '/includes/queue_processor.php';

$jobId = (int)($argv[1] ?? 0);
if ($jobId <= 0) {
    fwrite(STDERR, "Usage: php process.php <job_id>\n");
    exit(1);
}

try {
    $processor = new QueueProcessor($jobId);
    $processor->run();
    exit(0);
} catch (Throwable $e) {
    fwrite(STDERR, "Error: " . $e->getMessage() . "\n");
    exit(1);
}
