import { build } from "esbuild";
import { mkdir, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { fileURLToPath, pathToFileURL } from "node:url";

// 把 src/i18n/locales/*.ts 的扁平字典产出为 JSON，供 iOS 原生侧读取（强约束②：i18n 单一
// 真源＝web catalog，见 ios/PLAN.md §5）。locale 变更后重跑：node web/scripts/emit-i18n.mjs
// 各 locale 产出完整字典（zh-TW / en-US 缺失键回退 zh-CN），故 iOS loader 无需再做回退。
const webDir = fileURLToPath(new URL("..", import.meta.url));
const repoRoot = join(webDir, "..");
const outDir = join(repoRoot, "ios", "CDrop", "Sources", "Resources", "i18n");
const cacheDir = join(webDir, "node_modules", ".cache");
const tmp = join(cacheDir, "cdrop-i18n-emit.mjs");

const entry = [
    'import { zhCN } from "./src/i18n/locales/zh-CN";',
    'import { zhTW } from "./src/i18n/locales/zh-TW";',
    'import { enUS } from "./src/i18n/locales/en-US";',
    "export const all = {",
    '    "zh-CN": zhCN,',
    '    "zh-TW": { ...zhCN, ...zhTW },',
    '    "en-US": { ...zhCN, ...enUS },',
    "};",
].join("\n");

const res = await build({
    stdin: { contents: entry, resolveDir: webDir, loader: "ts" },
    bundle: true,
    format: "esm",
    write: false,
    platform: "neutral",
});

await mkdir(cacheDir, { recursive: true });
await writeFile(tmp, res.outputFiles[0].text);
const mod = await import(pathToFileURL(tmp).href);

await mkdir(outDir, { recursive: true });
for (const [loc, dict] of Object.entries(mod.all))
{
    await writeFile(join(outDir, `${loc}.json`), `${JSON.stringify(dict, null, 2)}\n`);
}
console.log("emitted i18n:", Object.keys(mod.all).join(", "), "->", outDir);
