<?php
declare(strict_types=1);

/**
 * One-off: visit each company's website, look for an RSS/Atom feed advertised
 * in the page head, and record it as a link. Companies that publish a feed are
 * far cheaper to monitor than ones where we have to diff whole pages.
 *
 *   php tools/seed_feeds.php            find and save
 *   php tools/seed_feeds.php --dry-run  report only
 */

if (PHP_SAPI !== 'cli') {
    exit("This script runs from the command line only.\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';

$opts   = getopt('', ['dry-run', 'limit::']);
$dryRun = isset($opts['dry-run']);
$limit  = isset($opts['limit']) ? max(1, (int) $opts['limit']) : 200;

$companies = Database::all(
    "SELECT c.id, c.name, c.website
       FROM companies c
      WHERE c.website IS NOT NULL AND c.website LIKE 'http%'
        AND NOT EXISTS (SELECT 1 FROM links l WHERE l.company_id = c.id AND l.is_feed = 1)
      ORDER BY c.name
      LIMIT " . $limit
);

echo sprintf("Looking for feeds on %d site(s)%s\n\n", count($companies), $dryRun ? ' (dry run)' : '');

$found = 0;

foreach ($companies as $c) {
    $response = Fetcher::get((string) $c['website']);

    if (!$response['ok'] || $response['body'] === '') {
        printf("  --   %-34s %s\n", mb_substr($c['name'], 0, 34), $response['error'] ?? 'no body');
        continue;
    }

    $feed = Extractor::discoverFeed($response['body'], $response['final_url']);

    if ($feed === null) {
        printf("  --   %-34s no feed advertised\n", mb_substr($c['name'], 0, 34));
        continue;
    }

    $found++;
    printf("  FEED %-34s %s\n", mb_substr($c['name'], 0, 34), mb_substr($feed, 0, 60));

    if ($dryRun) {
        continue;
    }

    $exists = Database::scalar(
        'SELECT 1 FROM links WHERE company_id = :c AND url = :u LIMIT 1',
        ['c' => $c['id'], 'u' => $feed]
    );

    if ($exists === null) {
        Database::run(
            "INSERT INTO links (company_id, link_type, url, label, is_feed)
             VALUES (:c, 'blog', :u, 'News feed', 1)",
            ['c' => $c['id'], 'u' => $feed]
        );
    } else {
        Database::run(
            'UPDATE links SET is_feed = 1 WHERE company_id = :c AND url = :u',
            ['c' => $c['id'], 'u' => $feed]
        );
    }
}

echo sprintf("\n%d feed(s) found across %d site(s).\n", $found, count($companies));
