<?php

declare(strict_types=1);

// Lock file to prevent concurrent execution
$basePath = dirname(__DIR__);
$lockFile = $basePath . '/storage/logs/publish.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 publish process is running. Exiting.\n";
        exit(0);
    }
    unlink($lockFile);
}

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

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

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

    $publisher = new \App\Services\PublisherService();
    $result = $publisher->publishNext();

    echo $result['message'] . "\n";
} catch (\Throwable $e) {
    $message = "CRON Error: " . $e->getMessage();
    echo $message . "\n";

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