// 把 manual-content.html 中的截图内联为 data URL,输出可离线单文件阅读的使用说明书。
//
// 运行:node docs/user-manual/build_manual.mjs
// 输出:docs/user-manual/LinuxCNC-Web-使用说明书.html
import { readFile, stat, writeFile } from "node:fs/promises";
import { dirname, resolve } from "node:path";
import { fileURLToPath } from "node:url";
const here = dirname(fileURLToPath(import.meta.url));
const contentPath = resolve(here, "manual-content.html");
const outputPath = resolve(here, "LinuxCNC-Web-使用说明书.html");
const source = await readFile(contentPath, "utf8");
const references = [...source.matchAll(/src="(screenshots\/[^"]+\.png)"/g)].map((match) => match[1]);
const unique = [...new Set(references)];
let html = source;
let totalBytes = 0;
for (const reference of unique) {
const file = resolve(here, reference);
const info = await stat(file).catch(() => null);
if (!info) throw new Error(`缺少截图:${reference}`);
const base64 = (await readFile(file)).toString("base64");
totalBytes += info.size;
html = html.replaceAll(`src="${reference}"`, `src="data:image/png;base64,${base64}"`);
}
const remaining = [...html.matchAll(/src="(screenshots\/[^"]+)"/g)];
if (remaining.length) throw new Error(`仍有未内联的图片:${remaining.map((match) => match[1]).join(", ")}`);
await writeFile(outputPath, html);
const outputSize = (await stat(outputPath)).size;
console.log(`内联 ${unique.length} 张截图(原始 ${(totalBytes / 1024 / 1024).toFixed(2)} MiB)`);
console.log(`已生成 ${outputPath}(${(outputSize / 1024 / 1024).toFixed(2)} MiB)`);