<?php
declare(strict_types=1);

/**
 * 将 “中文=>英文” 的历史映射（可临时放在 $legacy 变量里）转换为英文 key 映射：
 * - resource/translations/api/en.php: key=MSG_XXXXXXXX, value=英文
 * - resource/translations/api/zh.php: key=MSG_XXXXXXXX, value=中文
 *
 * 同时保留 resource/translations/api/{zh,en}.php 中已存在的显式英文错误码。
 */

$root = dirname(__DIR__);

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

$legacy = [];
$en = is_file($enPath) ? (require $enPath) : [];
$zh = is_file($zhPath) ? (require $zhPath) : [];

foreach ($legacy as $cn => $enVal) {
    if (!is_string($cn) || $cn === '' || !is_string($enVal)) {
        continue;
    }
    $key = 'MSG_' . strtoupper(sprintf('%08X', crc32($cn)));
    if (!isset($en[$key])) {
        $en[$key] = $enVal;
    }
    if (!isset($zh[$key])) {
        $zh[$key] = $cn;
    }
}

$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;
};

file_put_contents($enPath, $dump($en));
file_put_contents($zhPath, $dump($zh));

echo "done\n";

