<?php
declare(strict_types=1);

/**
 * Checks competitor pages for changes. Built to run from cron.
 *
 *   php tools/fetch_links.php                  check everything due
 *   php tools/fetch_links.php --limit=20       cap the run
 *   php tools/fetch_links.php --company=77     one company only
 *   php tools/fetch_links.php --min-age=12     skip anything checked in the last 12h
 *   php tools/fetch_links.php --dry-run        fetch and compare, write nothing
 *   php tools/fetch_links.php --quiet          for cron; only real events print
 *   php tools/fetch_links.php --verbose        print every link, including skips
 *
 * Nightly, staggered off the hour:
 *   17 3 * * *  cd /var/www/html/comp && php tools/fetch_links.php --quiet >> logs/fetch.log 2>&1
 *
 * The crawl itself lives in includes/Crawler.php, shared with the portal's
 * "Run now" button so both behave identically.
 */

if (PHP_SAPI !== 'cli') {
    exit("This script runs from the command line only. Use the Run now button on the Signals screen instead.\n");
}

require_once dirname(__DIR__) . '/config/config.php';
require_once dirname(__DIR__) . '/includes/helpers.php';
require_once dirname(__DIR__) . '/includes/Database.php';
require_once dirname(__DIR__) . '/includes/Fetcher.php';
require_once dirname(__DIR__) . '/includes/Extractor.php';
require_once dirname(__DIR__) . '/includes/Crawler.php';

$opts = getopt('', ['limit::', 'company::', 'min-age::', 'dry-run', 'quiet', 'verbose', 'help']);

if (isset($opts['help'])) {
    echo file_get_contents(__FILE__, false, null, 0, 1100);
    exit(0);
}

$quiet   = isset($opts['quiet']);
$verbose = isset($opts['verbose']);

$summary = Crawler::run([
    'limit'         => isset($opts['limit'])   ? (int) $opts['limit']   : 500,
    'company'       => isset($opts['company']) ? (int) $opts['company'] : null,
    'min_age_hours' => isset($opts['min-age']) ? (int) $opts['min-age'] : 20,
    'dry_run'       => isset($opts['dry-run']),
    'time_budget'   => null,          // cron has all the time it needs
    'on_line'       => static function (string $msg, string $level) use ($quiet, $verbose): void {
        if ($level === 'quiet' && !$verbose) {
            return;                    // routine "unchanged" lines
        }
        if ($quiet && !in_array($level, ['change', 'error'], true)) {
            return;
        }
        $tag = match ($level) {
            'change' => 'CHG ',
            'error'  => 'ERR ',
            default  => '    ',
        };
        echo $tag . $msg . "\n";
    },
]);

if ($summary['skipped'] !== null) {
    echo $summary['skipped'] . "\n";
    exit(0);
}

printf("\n%d checked · %d changed · %d feed item(s) · %d error(s)%s\n",
    $summary['checked'], $summary['changed'], $summary['feed_items'], $summary['errors'],
    $summary['remaining'] > 0 ? sprintf(' · %d still due', $summary['remaining']) : '');

exit($summary['errors'] > 0 ? 0 : 0);
