<?php

declare(strict_types=1);

// Lock file to prevent concurrent execution
$basePath = dirname(__DIR__);
$lockFile = $basePath . '/storage/logs/statlink.lock';

if (file_exists($lockFile)) {
    $lockTime = filemtime($lockFile);
    // If lock is older than 30 minutes, assume stale and remove
    if (time() - $lockTime < 1800) {
        echo "Another statlink process is running. Exiting.\n";
        exit(0);
    }
    unlink($lockFile);
}

file_put_contents($lockFile, date('Y-m-d H:i:s'));
set_time_limit(300);

try {
    require_once $basePath . '/vendor/autoload.php';

    \App\Core\Config::load($basePath);
    \App\Helpers\Logger::setBasePath($basePath);

    $service = new \App\Services\StatLinkService();

    // One action per run: prioritize removing expired, then add new
    $removeResult = $service->removeExpiredLinks();

    if ($removeResult['removed'] > 0 || $removeResult['errors'] > 0) {
        echo sprintf("StatLink cron: removed=%d, errors=%d\n", $removeResult['removed'], $removeResult['errors']);
    } else {
        $addResult = $service->processNewArticles();
        echo sprintf("StatLink cron: added=%d, skipped=%d, errors=%d\n", $addResult['added'], $addResult['skipped'], $addResult['errors']);
    }
} catch (\Throwable $e) {
    $message = "StatLink CRON Error: " . $e->getMessage();
    echo $message . "\n";

    if (class_exists(\App\Helpers\Logger::class)) {
        \App\Helpers\Logger::error($message, 'statlink');
    }
} finally {
    if (file_exists($lockFile)) {
        unlink($lockFile);
    }
}
