<?php
require_once __DIR__ . '/../core/cron_guard.php';
icylab_require_cron_access();
require_once __DIR__ . '/../core/config.php';
require_once __DIR__ . '/../core/database.php';
require_once __DIR__ . '/../services/finance/ExchangeRateService.php';
require_once __DIR__ . '/../services/analytics/AnalyticsEngine.php';

if (PHP_SAPI !== 'cli') header('Content-Type: text/plain; charset=utf-8');
$pdo = db();
try {
    $service = new ExchangeRateService($pdo);
    $daily = $service->syncDailyRates(date('Y-m-d'));
    $result = $service->backfillDocuments(5000, false);
    (new AnalyticsEngine($pdo))->rebuild();
    echo "BACKFILL OK\n";
    echo 'Tasas diarias resueltas: ' . (int)($daily['resolved'] ?? 0) . "\n";
    echo 'Documentos evaluados: ' . (int)($result['evaluated'] ?? 0) . "\n";
    echo 'Documentos normalizados: ' . (int)($result['resolved'] ?? 0) . "\n";
    echo 'Documentos pendientes: ' . (int)($result['missing'] ?? 0) . "\n";
    echo 'Errores: ' . (int)($result['errors'] ?? 0) . "\n";
    echo "Analytics reconstruido: si\n";
} catch (Throwable $e) {
    if (PHP_SAPI !== 'cli') http_response_code(500);
    echo 'BACKFILL ERROR: ' . $e->getMessage() . "\n";
    exit(1);
}
