<?php
declare(strict_types=1);

/**
 * 修复替换结果：把代码里的 'E_XXXXXXXX'（crc32 的十六进制）替换为真正英文短句。
 * 英文短句来源：resource/translations/api/en.php 的 MSG_XXXXXXXX。
 *
 * 同时确保 translations/api/{en,zh}.php 中包含：
 * - key=英文短句, en=英文短句
 * - key=英文短句, zh=对应中文
 */

$root = dirname(__DIR__);
$serverDir = $root;

$enPath = $root . '/resource/translations/api/en.php';
$zhPath = $root . '/resource/translations/api/zh.php';

$enMap = is_file($enPath) ? (require $enPath) : [];
$zhMap = is_file($zhPath) ? (require $zhPath) : [];

$dump = static function (array $arr): string {
    ksort($arr);
    $out = "<?php\ndeclare(strict_types=1);\n\nreturn [\n";
    foreach ($arr as $k => $v) {
        $k = str_replace("'", "\\'", (string) $k);
        $v = str_replace("'", "\\'", (string) $v);
        $out .= "    '{$k}' => '{$v}',\n";
    }
    $out .= "];\n";
    return $out;
};

$files = [];
$it = new RecursiveIteratorIterator(
    new RecursiveDirectoryIterator($serverDir, FilesystemIterator::SKIP_DOTS)
);
foreach ($it as $file) {
    /** @var SplFileInfo $file */
    if (!$file->isFile()) {
        continue;
    }
    $path = $file->getPathname();
    if (substr($path, -4) !== '.php') {
        continue;
    }
    $norm = str_replace('\\', '/', $path);
    if (str_contains($norm, '/resource/translations/')) {
        continue;
    }
    if (str_contains($norm, '/scripts/')) {
        continue;
    }
    $files[] = $path;
}

$touchedFiles = 0;
$replaced = 0;
$added = 0;

foreach ($files as $path) {
    $content = file_get_contents($path);
    if (!is_string($content) || $content === '') {
        continue;
    }

    $newContent = preg_replace_callback(
        "/(['\"])E_([0-9A-Fa-f]{8})\\1/",
        function (array $m) use (&$enMap, &$zhMap, &$replaced, &$added) {
            $hex = strtoupper($m[2]);
            $msgKey = 'MSG_' . $hex;
            $en = $enMap[$msgKey] ?? null;
            $zh = $zhMap[$msgKey] ?? null;
            if (!is_string($en) || $en === '') {
                return $m[0];
            }
            if (!is_string($zh) || $zh === '') {
                $zh = $msgKey;
            }

            if (!isset($enMap[$en])) {
                $enMap[$en] = $en;
                $added++;
            }
            if (!isset($zhMap[$en])) {
                $zhMap[$en] = $zh;
                $added++;
            }

            $replaced++;
            return "'" . str_replace("'", "\\'", $en) . "'";
        },
        $content
    );

    if (is_string($newContent) && $newContent !== $content) {
        file_put_contents($path, $newContent);
        $touchedFiles++;
    }
}

file_put_contents($enPath, $dump($enMap));
file_put_contents($zhPath, $dump($zhMap));

echo "touched_files={$touchedFiles}\n";
echo "replaced={$replaced}\n";
echo "added_translation_pairs={$added}\n";

