<?php
declare(strict_types=1);

// Isolated SQL log timing/table names only; no SQL text, params or row values.
$target = (string)getenv('CDX_LOG_TARGET');
$paths = [
    'A' => '/tmp/zhct-http-ai-macos.zjaU8h/runtime/api/log/20261002_sql.log',
    'B' => '/tmp/zhct-http-ai-macos.x2CCZX/runtime/api/log/20261002_sql.log',
];
$minute = (string)getenv('CDX_LOG_MINUTE');
if (!isset($paths[$target]) || !is_file($paths[$target])
    || !preg_match('/^2026-10-02 \d{2}:\d{2}$/', $minute)) {
    echo json_encode(['status' => 'invalid-readonly-log-target']), PHP_EOL;
    exit(2);
}
$rows = [];
foreach (file($paths[$target], FILE_IGNORE_NEW_LINES) ?: [] as $line) {
    if (strpos($line, '[' . $minute . ':') !== 0) continue;
    if (!preg_match('/\[ RunTime:([0-9]+(?:\.[0-9]+)?)s \]/', $line, $run)) continue;
    preg_match_all('/\b(?:yoshop|ydy)_[a-z0-9_]+\b/i', $line, $tables);
    $names = array_values(array_unique(array_map('strtolower', $tables[0] ?? [])));
    $rows[] = [
        'runtime_seconds' => round((float)$run[1], 3),
        'table_names_only' => $names,
    ];
}
usort($rows, static function (array $a, array $b): int {
    return $b['runtime_seconds'] <=> $a['runtime_seconds'];
});
echo json_encode(['status' => 'sql-timing-only', 'target' => $target,
    'minute' => $minute, 'matching_queries' => count($rows),
    'slowest' => array_slice($rows, 0, 10),
    'sql_or_business_values_output' => false],
    JSON_UNESCAPED_SLASHES), PHP_EOL;
