<?php

if (!defined('ABSPATH')) { fwrite(STDERR, "Run via: wp eval-file <this file> --allow-root\n"); return; }
if (!class_exists('AIEO_DMM_Tools') || !class_exists('AIEO_DMM_Brand_Extras_Data') || !function_exists('wc_get_product')) {
    echo "[ABORT] AIEO_DMM_Tools / Brand Extras / WooCommerce not available — is the plugin active?\n";
    return;
}

@set_time_limit(0); 
AIEO_DMM_Tools::suppress_bulk_product_save_hooks();

echo "== Apply brand margins -> Cost of Goods (CLI, hooks suppressed) ==\n";
$t0 = microtime(true);
$offset = 0; $U = 0; $S = 0; $total = 0; $batches = 0;
while (true) {
    $r = AIEO_DMM_Tools::apply_cogs_batch($offset, 250);
    $U += (int) $r['updated']; $S += (int) $r['skipped'];
    $offset = (int) $r['next_offset']; $total = (int) $r['total']; $batches++;
    if ($batches === 1 || $batches % 10 === 0 || !empty($r['done'])) {
        printf("  %d/%d  set=%d skipped=%d  (%.1fs)\n", min($offset, $total), $total, $U, $S, microtime(true) - $t0);
    }
    if (!empty($r['done'])) { break; }
    if ($batches > 100000) { echo "  GUARD hit\n"; break; }
}
printf("== DONE: set=%d skipped=%d of %d  in %.1fs ==\n", $U, $S, $total, microtime(true) - $t0);
