<?php
// Diagnóstico de timing — REMOVER após análise
$t0 = microtime(true);

// 1) Autoloader
spl_autoload_register(function (string $class): void {
    $base = __DIR__ . '/../app/';
    $file = $base . str_replace(['App\\', '\\'], ['', '/'], $class) . '.php';
    if (file_exists($file)) require_once $file;
});

$t1 = microtime(true);

// 2) Cache init
use App\Core\Cache;
$t2 = microtime(true);

// 3) Conexão PDO
use App\Core\Database;
$connErr = null;
try { $pdo = Database::conectar(); } catch (\Throwable $e) { $connErr = $e->getMessage(); }
$t3 = microtime(true);

// 4) Query simples
$queryErr = null; $rowCount = 0;
try {
    $st = $pdo->query("SELECT COUNT(*) FROM NOTAS_CAB");
    $rowCount = $st->fetchColumn();
} catch (\Throwable $e) { $queryErr = $e->getMessage(); }
$t4 = microtime(true);

// 5) Cache lookup
use App\Services\FirebirdService;
$cacheHit = Cache::get('compras_ultima_data') !== null ? 'HIT' : 'MISS';
$t5 = microtime(true);

// 6) OPcache status
$opcache = function_exists('opcache_get_status') ? opcache_get_status(false) : null;
$t6 = microtime(true);

header('Content-Type: application/json');
echo json_encode([
    'ms' => [
        'autoloader'  => round(($t1 - $t0) * 1000, 2),
        'cache_use'   => round(($t2 - $t1) * 1000, 2),
        'pdo_connect' => round(($t3 - $t2) * 1000, 2),
        'query_count' => round(($t4 - $t3) * 1000, 2),
        'cache_check' => round(($t5 - $t4) * 1000, 2),
        'total'       => round(($t6 - $t0) * 1000, 2),
    ],
    'notas_count'  => $rowCount,
    'conn_error'   => $connErr,
    'query_error'  => $queryErr,
    'cache_ultima' => $cacheHit,
    'opcache_on'   => $opcache['opcache_enabled'] ?? null,
    'opcache_hits' => $opcache['opcache_statistics']['hits'] ?? null,
    'opcache_miss' => $opcache['opcache_statistics']['misses'] ?? null,
], JSON_PRETTY_PRINT);
