<?php
declare(strict_types=1);

/**
 * "Run now" from the Signals screen.
 *
 * A web request cannot run for minutes, so this does one bounded batch and
 * reports what is left. Press it again to continue. Cron remains the right way
 * to run the whole queue; this is for a first pass, or for checking one company
 * you are looking at right now.
 */

Auth::requireRole('analyst');
Csrf::check();

$company = post('company') !== null && post('company') !== '' ? (int) post('company') : null;

// Keep well inside PHP's execution limit, leaving room to write the summary.
$maxExecution = (int) ini_get('max_execution_time');
$budget = $maxExecution > 0 ? max(15, $maxExecution - 10) : 45;

// Finish the batch even if the person closes the tab mid-run.
ignore_user_abort(true);
@set_time_limit($maxExecution > 0 ? $maxExecution : 60);

$summary = Crawler::run([
    'limit'         => $company !== null ? 25 : 12,
    'company'       => $company,
    'min_age_hours' => $company !== null ? 0 : 20,
    'time_budget'   => $budget,
]);

if ($summary['skipped'] !== null) {
    Flash::add('warn', $summary['skipped']);
    redirect('signals', 'index');
}

Audit::log('update', 'fetch_run', $summary['run_id'], [
    'checked' => $summary['checked'],
    'changed' => $summary['changed'],
    'manual'  => true,
]);

$message = t('crawl_done', [
    'checked' => $summary['checked'],
    'changed' => $summary['changed'],
    'errors'  => $summary['errors'],
]);

if ($summary['remaining'] > 0) {
    $message .= ' ' . t('crawl_remaining', ['n' => $summary['remaining']]);
}

Flash::add($summary['changed'] > 0 ? 'ok' : 'warn', $message);

if ($company !== null) {
    redirect('companies', 'view', ['id' => $company]);
}
redirect('signals', 'index');
