<?php
// CLI用法：php tools/publish_cron.php
$root = realpath(__DIR__ . '/..');
$base = $root . '/data/content_center';
$now = time();
$changed = 0;
$rii = is_dir($base) ? new RecursiveIteratorIterator(new RecursiveDirectoryIterator($base, FilesystemIterator::SKIP_DOTS)) : null;
if($rii){
    foreach($rii as $info){
        if(!$info->isFile() || strtolower($info->getExtension()) !== 'php') continue;
        $file = $info->getPathname();
        $article = include $file;
        if(!is_array($article)) continue;
        if(($article['status'] ?? '') !== 'pending') continue;
        $publishTime = trim((string)($article['publish_time'] ?? ''));
        if($publishTime === '' || strtotime($publishTime) <= $now){
            if(!empty($article['delay_publish']) && empty($article['delay_applied'])){
                $delay = mt_rand(3, 45) * 60;
                $article['publish_time'] = date('Y-m-d H:i:s', $now + $delay);
                $article['delay_applied'] = 1;
            }else{
                $article['status'] = 'published';
                $article['published_at'] = date('Y-m-d H:i:s');
            }
            file_put_contents($file, "<?php\nreturn " . var_export($article, true) . ";\n", LOCK_EX);
            $changed++;
        }
    }
}
echo "publish_cron changed: " . $changed . PHP_EOL;
