<?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');

function fx863_line($label, $value)
{
    echo $label . ': ' . $value . PHP_EOL;
}

try {
    $pdo = db();
    $service = new ExchangeRateService($pdo);

    echo "FINDIC REPAIR v8.6.3\n";
    fx863_line('php_version', PHP_VERSION);
    fx863_line('sapi', PHP_SAPI);
    fx863_line('curl_available', function_exists('curl_init') ? 'yes' : 'no');
    fx863_line('allow_url_fopen', filter_var(ini_get('allow_url_fopen'), FILTER_VALIDATE_BOOLEAN) ? 'yes' : 'no');
    fx863_line('findic_dns', gethostbyname('findic.cl'));

    $probeRow = $pdo->query("SELECT currency_code, issue_date
        FROM facto_documents
        WHERE received_issued_flag=1
          AND document_status=1
          AND UPPER(COALESCE(NULLIF(currency_code,''),'CLP')) IN ('USD','EUR')
          AND issue_date IS NOT NULL
        ORDER BY CASE WHEN COALESCE(exchange_rate_value,0)<=0 OR total_amount_clp IS NULL THEN 0 ELSE 1 END,
                 issue_date DESC, id DESC
        LIMIT 1")->fetch(PDO::FETCH_ASSOC);

    $probeCurrency = strtoupper((string)($probeRow['currency_code'] ?? 'USD'));
    $probeDate = (string)($probeRow['issue_date'] ?? date('Y-m-d'));
    fx863_line('probe_currency', $probeCurrency);
    fx863_line('probe_date', $probeDate);

    $probe = $service->probeProviderPaths($probeCurrency, $probeDate);
    foreach (($probe['paths'] ?? array()) as $name => $path) {
        fx863_line('probe_' . $name . '_ok', !empty($path['ok']) ? 'yes' : 'no');
        fx863_line('probe_' . $name . '_url', (string)($path['url'] ?? ''));
        fx863_line('probe_' . $name . '_bytes', (int)($path['bytes'] ?? 0));
        if (!empty($path['rate_date'])) fx863_line('probe_' . $name . '_rate_date', $path['rate_date']);
        if (!empty($path['rate_to_clp'])) fx863_line('probe_' . $name . '_rate_value', $path['rate_to_clp']);
        fx863_line('probe_' . $name . '_message', (string)($path['message'] ?? ''));
    }

    $before = (int)$pdo->query("SELECT COUNT(*)
        FROM facto_documents
        WHERE received_issued_flag=1
          AND document_status=1
          AND UPPER(COALESCE(NULLIF(currency_code,''),'CLP')) IN ('USD','EUR')
          AND (COALESCE(exchange_rate_value,0)<=0 OR total_amount_clp IS NULL)")->fetchColumn();
    fx863_line('pending_before', $before);

    $result = $service->backfillDocuments(5000, true);
    fx863_line('evaluated', (int)($result['evaluated'] ?? 0));
    fx863_line('resolved', (int)($result['resolved'] ?? 0));
    fx863_line('missing', (int)($result['missing'] ?? 0));
    fx863_line('errors', (int)($result['errors'] ?? 0));

    foreach (($result['details'] ?? array()) as $index => $detail) {
        $prefix = 'document_' . ($index + 1);
        fx863_line($prefix . '_number', (string)($detail['document_number'] ?? $detail['document_id'] ?? ''));
        fx863_line($prefix . '_currency', (string)($detail['currency'] ?? ''));
        fx863_line($prefix . '_issue_date', (string)($detail['issue_date'] ?? ''));
        fx863_line($prefix . '_status', (string)($detail['status'] ?? ''));
        if (isset($detail['rate_to_clp'])) fx863_line($prefix . '_rate', $detail['rate_to_clp']);
        if (!empty($detail['rate_date'])) fx863_line($prefix . '_rate_date', $detail['rate_date']);
        if (!empty($detail['source'])) fx863_line($prefix . '_source', $detail['source']);
        if (!empty($detail['message'])) fx863_line($prefix . '_message', $detail['message']);
    }

    $after = (int)$pdo->query("SELECT COUNT(*)
        FROM facto_documents
        WHERE received_issued_flag=1
          AND document_status=1
          AND UPPER(COALESCE(NULLIF(currency_code,''),'CLP')) IN ('USD','EUR')
          AND (COALESCE(exchange_rate_value,0)<=0 OR total_amount_clp IS NULL)")->fetchColumn();
    fx863_line('pending_after', $after);

    $analyticsRebuilt = false;
    if (($result['resolved'] ?? 0) > 0) {
        (new AnalyticsEngine($pdo))->rebuild();
        $analyticsRebuilt = true;
    }
    fx863_line('analytics_rebuilt', $analyticsRebuilt ? 'yes' : 'no');

    if ($after > 0) {
        echo "RESULT: PASS WITH WARNINGS\n";
        exit(0);
    }
    echo "RESULT: PASS\n";
} catch (Throwable $e) {
    if (PHP_SAPI !== 'cli') http_response_code(500);
    echo 'RESULT: FAIL' . PHP_EOL;
    echo 'error: ' . $e->getMessage() . PHP_EOL;
    exit(1);
}
