<?php

require_once __DIR__ . '/../services/QueueService.php';
require_once __DIR__ . '/../services/EconomicCalendarProviderService.php';
require_once __DIR__ . '/../services/NewsProviderRotationService.php';

$queue = $argv[1] ?? 'market_data';
$maxJobs = isset($argv[2]) ? (int)$argv[2] : 10;

for ($i = 0; $i < $maxJobs; $i++) {
    $job = QueueService::reserve($queue);

    if (!$job) {
        echo '[' . date('Y-m-d H:i:s') . '] No pending jobs.' . PHP_EOL;
        break;
    }

    try {
        $payload = $job['payload_array'] ?? [];

        if ($job['job_type'] === 'fetch_economic_calendar') {
            $result = EconomicCalendarProviderService::fetchUpcoming((int)($payload['hours_ahead'] ?? 48));

            if (empty($result['success'])) {
                throw new RuntimeException($result['error'] ?? 'Calendar fetch failed.');
            }
        } elseif ($job['job_type'] === 'fetch_market_news') {
            $result = NewsProviderRotationService::fetchMarketNews(
                $payload['query'] ?? 'gold OR forex OR bitcoin',
                (int)($payload['limit'] ?? 20)
            );

            if (empty($result['success'])) {
                throw new RuntimeException($result['error'] ?? 'News fetch failed.');
            }
        } else {
            throw new RuntimeException('Unknown job type: ' . $job['job_type']);
        }

        QueueService::complete((int)$job['id']);

        echo '[' . date('Y-m-d H:i:s') . '] Completed ' . $job['job_type'] . PHP_EOL;
    } catch (Throwable $e) {
        QueueService::fail($job, $e->getMessage());

        echo '[' . date('Y-m-d H:i:s') . '] Failed ' . $job['job_type'] . ': ' . $e->getMessage() . PHP_EOL;
    }
}
