<?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'));
    $backfill = $service->backfillDocuments(1000, false);
    $rebuilt = false;
    if (($backfill['resolved'] ?? 0) > 0) {
        (new AnalyticsEngine($pdo))->rebuild();
        $rebuilt = true;
    }
    echo "sync_exchange_rates OK\n";
    echo 'Tasas resueltas: ' . (int)($daily['resolved'] ?? 0) . "\n";
    echo 'Tasas sin dato: ' . (int)($daily['missing'] ?? 0) . "\n";
    echo 'Documentos evaluados: ' . (int)($backfill['evaluated'] ?? 0) . "\n";
    echo 'Documentos normalizados: ' . (int)($backfill['resolved'] ?? 0) . "\n";
    echo 'Documentos pendientes: ' . (int)($backfill['missing'] ?? 0) . "\n";
    echo 'Errores: ' . (int)($backfill['errors'] ?? 0) . "\n";
    echo 'Analytics reconstruido: ' . ($rebuilt ? 'si' : 'no') . "\n";
} catch (Throwable $e) {
    if (PHP_SAPI !== 'cli') http_response_code(500);
    echo 'sync_exchange_rates ERROR: ' . $e->getMessage() . "\n";
    exit(1);
}
