<?php
/**
 * AuctionForge Sync Safety Net v4.0
 *
 * Runs hourly via external cron. Delegates to SafetySync::run()
 * which handles all safety-net logic:
 * 1. Reset stuck jobs (processing > 10 min)
 * 2. Spawn worker if pending jobs exist and no active worker
 * 3. Detect ended auctions whose webhook was missed (date-passed + API check)
 * 4. Discover newly published auctions from BidSpirit API
 * 5. Hourly delta check: compare API vs local state, sync changed auctions
 * 6. Fix orphaned lot posts missing taxonomy assignment
 * 7. Purge old queue/log data
 */

use auctionforge\inc\sync\SafetySync;
use auctionforge\inc\sync\SyncLogger;

if (!empty($_SERVER['DOCUMENT_ROOT'])) {
    die("Access denied — CLI only\n");
}

define('CRON_TASKS_BASE_PATH', __DIR__);
define('WP_USE_THEMES', false);
require(CRON_TASKS_BASE_PATH . '/../../../../wp-load.php');

if (!is_plugin_active(basename(dirname(__DIR__)) . '/' . basename(dirname(__DIR__)) . '.php')) {
    die("Plugin AuctionForge disabled\n");
}

SyncLogger::log('safety', 'Safety cron started (CLI)', 'info');

$summary = SafetySync::run();

// CLI summary output
echo sprintf(
    "Safety cron complete: %d reset, %d missed-ended, %d delta-synced, %d orphans-fixed, %d/%d purged\n",
    $summary['stuck_reset'],
    $summary['missed_ended'],
    $summary['delta_synced'],
    $summary['orphans_fixed'],
    $summary['queue_purged'],
    $summary['log_purged']
);
