<?php

declare(strict_types=1);

$basePath = dirname(__DIR__);
$lockFile = $basePath . '/storage/logs/semstorm.lock';

if (file_exists($lockFile)) {
    $lockTime = filemtime($lockFile);
    if ($lockTime !== false && (time() - $lockTime) < 3600) {
        echo "Another SEMSTORM sync 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);

    $sites = \App\Models\Site::findActive();
    $sync = new \App\Services\SiteSeoSyncService();

    if (empty($sites)) {
        echo "No active sites found.\n";
        exit(0);
    }

    $saved = 0;
    $skipped = 0;
    $failed = 0;

    foreach ($sites as $site) {
        $result = $sync->syncSite($site);
        $status = (string) ($result['status'] ?? 'error');

        if ($status === 'saved') {
            $saved++;
        } elseif ($status === 'skipped') {
            $skipped++;
        } else {
            $failed++;
        }

        $message = (string) ($result['message'] ?? 'brak komunikatu');
        echo sprintf(
            "[%s] site_id=%d, status=%s, message=%s\n",
            date('Y-m-d H:i:s'),
            (int) ($site['id'] ?? 0),
            $status,
            $message
        );
    }

    $summary = "SEMSTORM sync summary: saved={$saved}, skipped={$skipped}, failed={$failed}";
    \App\Helpers\Logger::info($summary, 'semstorm');
    echo $summary . "\n";
} catch (\Throwable $e) {
    $message = 'SEMSTORM CRON Error: ' . $e->getMessage();
    echo $message . "\n";

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