#!/usr/bin/env php
<?php

declare(strict_types=1);

use FeedManager\Repositories\SyncRunRepository;
use FeedManager\Support\DotenvLoader;
use FeedManager\Support\PdoFactory;

require_once __DIR__ . '/../bootstrap.php';

$client = $argv[1] ?? null;
$minIntervalMinutes = 60;
foreach (array_slice($argv, 2) as $arg) {
    if (str_starts_with((string) $arg, '--min-interval-minutes=')) {
        $minIntervalMinutes = max(1, (int) substr((string) $arg, strlen('--min-interval-minutes=')));
    }
}

if (!is_string($client) || trim($client) === '') {
    fwrite(STDERR, "Usage: php bin/sync-scheduled <client> [--min-interval-minutes=60]\n");
    exit(1);
}

try {
    DotenvLoader::load(__DIR__ . '/../.env');
    $pdo = PdoFactory::fromEnv();
    $syncRuns = new SyncRunRepository($pdo);

    $last = $syncRuns->getLatestStartedAt($client);
    if ($last !== null) {
        $secondsSince = time() - $last->getTimestamp();
        if ($secondsSince < ($minIntervalMinutes * 60)) {
            fwrite(STDOUT, sprintf(
                "Scheduled sync skipped: last run started %d seconds ago (< %d minutes)\n",
                $secondsSince,
                $minIntervalMinutes
            ));
            exit(0);
        }
    }

    $command = escapeshellcmd(PHP_BINARY) . ' ' . escapeshellarg(__DIR__ . '/sync-feed') . ' ' . escapeshellarg($client) . ' --trigger=cron';
    passthru($command, $exitCode);
    exit((int) $exitCode);
} catch (Throwable $e) {
    fwrite(STDERR, sprintf("Scheduled sync failed: %s\n", $e->getMessage()));
    exit(1);
}
