<?php

if (!defined('ABSPATH')) {
    fwrite(STDERR, "Run via: wp eval-file <this file> --allow-root\n");
    return;
}
if (!class_exists('AIEO_DMM_Product_Orders_Analytics')) {
    echo "[ABORT] AIEO_DMM_Product_Orders_Analytics not loaded — is the plugin active?\n";
    return;
}

global $wpdb;
$p     = $wpdb->prefix;
$grain = AIEO_DMM_Product_Orders_Analytics::grain();
$asof  = AIEO_DMM_Product_Orders_Analytics::resolve_asof();
$lock  = 'aieo_analytics_job_sales_predictor';

echo "== Staged sales predictor ==\n";
echo "  grain={$grain}  asof={$asof}\n";

delete_transient($lock);
delete_transient('aieo_sp_started');

$t0 = microtime(true);
@set_time_limit(0); 

$wpdb->query($wpdb->prepare('SET @aieo_predictor_grain = %s', $grain));
$wpdb->query($wpdb->prepare('SET @aieo_predictor_asof = %s', $asof));

$wpdb->query("CALL `{$p}AIEO_SP_Prepare`()");
if ($wpdb->last_error) { echo "PREPARE ERROR: {$wpdb->last_error}\n"; return; }

$run = $wpdb->get_row("SELECT total_batches, total_products FROM `{$p}aieo_sp_run` WHERE id = 1", ARRAY_A);
$tb  = (int) ($run['total_batches'] ?? 0);
echo "  prepared: products=" . (int) ($run['total_products'] ?? 0) . "  batches={$tb}  (" . round(microtime(true) - $t0, 1) . "s)\n";

$i = 0; $guard = $tb + 50;
while (true) {
    $cur = (int) $wpdb->get_var("SELECT next_batch FROM `{$p}aieo_sp_run` WHERE id = 1");
    if ($cur >= $tb) { break; }
    $wpdb->query("CALL `{$p}AIEO_SP_Batch`()");
    if ($wpdb->last_error) { echo "BATCH ERROR at {$cur}: {$wpdb->last_error}\n"; return; }
    if (++$i === 1 || $i % 10 === 0) { echo "  batch {$i}/{$tb}  (" . round(microtime(true) - $t0, 1) . "s)\n"; }
    if ($i > $guard) { echo "GUARD hit ({$guard}) — aborting loop\n"; break; }
}
echo "  batches done: {$i}  (" . round(microtime(true) - $t0, 1) . "s)\n";

$wpdb->query("CALL `{$p}AIEO_SP_Finalize`()");
if ($wpdb->last_error) { echo "FINALIZE ERROR: {$wpdb->last_error}\n"; return; }

$rows = (int) $wpdb->get_var($wpdb->prepare(
    "SELECT COUNT(*) FROM `{$p}aieo_sales_predictor` WHERE prediction_date = %s",
    $asof
));
$dur = round(microtime(true) - $t0, 1);

$all = get_option(AIEO_DMM_Product_Orders_Analytics::LAST_RUN_OPTION, array());
if (!is_array($all)) { $all = array(); }
$all['sales_predictor'] = array(
    'finished_at' => current_time('mysql', true),
    'source'      => 'manual',
    'duration'    => $dur,
    'rows'        => $rows,
    'ok'          => true,
    'error'       => '',
);
update_option(AIEO_DMM_Product_Orders_Analytics::LAST_RUN_OPTION, $all, false);
delete_transient($lock);
delete_transient('aieo_sp_started');

foreach ($wpdb->get_results("SELECT grain, COUNT(*) c FROM `{$p}aieo_sales_predictor` GROUP BY grain") as $r) {
    echo "  grain {$r->grain}: {$r->c}\n";
}
echo "  rows@asof={$rows}  total={$dur}s\n";
echo "== DONE ==\n";
