<?php

declare(strict_types=1);

// Read-only, redacted extraction. Never print a SQL statement or log line.
$path = '/tmp/zhct-dm-poc-20260928.fcpiiN/store/runtime/log/202610/03.log';
$marker = 'CDXDTR691B6A066970';
if (($argv[1] ?? '') !== '--redacted' || !is_file($path)
    || is_link($path) || filesize($path) > 10 * 1024 * 1024) {
    fwrite(STDERR, "Transfer log scan disabled\n");
    exit(78);
}
$file = fopen($path, 'rb');
if (!$file) throw new RuntimeException('Transfer log unavailable');
$rows = [];
$lineNumber = 0;
while (($line = fgets($file)) !== false) {
    $lineNumber++;
    $hasMarker = strpos($line, $marker) !== false;
    $isTransfer = stripos($line, 'Department') !== false
        && stripos($line, 'transfer') !== false;
    $isReplace = preg_match('/\bREPLACE\s+INTO\b/i', $line) === 1;
    $hasState = stripos($line, 'SQLSTATE') !== false;
    $hasDmCode = preg_match('/(?<!\d)-2\d{3}(?!\d)/', $line) === 1;
    if (!$hasMarker && !$isTransfer && !$isReplace && !$hasState && !$hasDmCode) {
        continue;
    }
    $codes = [];
    if (preg_match_all('/SQLSTATE\[[A-Z0-9]+\]|(?<!\d)-2\d{3}(?!\d)/i',
        $line, $matches)) {
        $codes = array_values(array_unique($matches[0]));
    }
    $time = null;
    if (preg_match('/(?:2026-10-03[ T])?\b(1[7-9]|20):[0-5]\d:[0-5]\d\b/',
        $line, $match)) {
        $time = $match[0];
    }
    $replaceShape = null;
    if ($isReplace && $hasMarker) {
        $fields = [];
        $createByTokens = [];
        if (preg_match('/REPLACE\s+INTO\s+[^()]+\(([^()]*)\)\s*VALUES\s*(.*)$/i',
            $line, $sqlMatch)) {
            $fields = array_map(static function (string $field): string {
                return strtoupper(trim($field, " \t`\""));
            }, explode(',', $sqlMatch[1]));
            $position = array_search('CREATE_BY', $fields, true);
            preg_match_all('/\(([^()]*)\)/', $sqlMatch[2], $tuples);
            foreach ($tuples[1] as $tuple) {
                $values = array_map('trim', explode(',', $tuple));
                if ($position === false || !array_key_exists($position, $values)) {
                    $createByTokens[] = 'unparsed';
                    continue;
                }
                $value = strtoupper(trim($values[$position]));
                $createByTokens[] = $value === 'NULL' ? 'literal_NULL'
                    : ($value === '?' ? 'placeholder' : 'other_redacted');
            }
        }
        $replaceShape = ['field_count' => count($fields),
            'has_create_by_column' => in_array('CREATE_BY', $fields, true),
            'select_rows' => count($createByTokens),
            'create_by_tokens' => $createByTokens,
            'total_null_literals' => preg_match_all('/\bNULL\b/i', $line)];
    }
    $rows[] = ['line' => $lineNumber, 'time' => $time,
        'marker' => $hasMarker, 'transfer_context' => $isTransfer,
        'sql_verb_replace_into' => $isReplace,
        'error_codes' => $codes,
        'syntax_error_word' => preg_match('/\bsyntax\b|语法/u', $line) === 1,
        'replace_shape' => $replaceShape,
        'line_sha12' => substr(hash('sha256', $line), 0, 12)];
}
fclose($file);
echo json_encode(['log_sha256' => hash_file('sha256', $path),
    'line_count' => $lineNumber,
    'matching_lines' => count($rows),
    'redacted_matches' => array_slice($rows, -50)],
    JSON_UNESCAPED_SLASHES), PHP_EOL;
