#!/usr/bin/env node
// make_deploy.mjs — 跨平台部署打包脚本(纯 Node,Windows / Linux / macOS 通用)
//
// 把浏览器实际加载的文件复制到 ./public/,准备上传到 EdgeOne(或任意静态托管)。
//
// 要点:
//   * 用 Node 标准 fs/path,不依赖任何平台专属工具;
//   * 复制前先清空目标目录再重建 —— 适合本地重试与 CI 构建,不会因历史残留报错;
//   * 复制后仍做「精确性」断言:目标目录里只能有预期文件,不能多、不能少;
//   * 不调用 pause(便于自动化 / 一键跑完)。
//
// 用法(仓库根):
//   node make_deploy.mjs
//
// 作为 EdgeOne 构建脚本时,部署设置填:构建命令 `node make_deploy.mjs`,输出目录 `public/`。
// 本脚本跨平台、不含 start.ps1;Windows 本地启动器 start.ps1 由 deploy.ps1 补拷。

import fs from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';

const ROOT = path.dirname(fileURLToPath(import.meta.url));
const DEST = path.join(ROOT, 'public');

// data/ 下页面真正 fetch 的 5 个文件(不含 trace.json:它只被离线 verify 工具消费,页面从不请求)
const DATA_FILES = ['quark_weights.json', 'quark_weights.bin', 'tokenizer.json', 'reference.json', 'corpus.json'];

// 9 个入口文件:缺任何一个,部署出去的页面就是坏的
const REQUIRED = [
  'index.html',
  'css/style.css',
  'js/main.js',
  'lib/katex/katex.min.css',
  'lib/katex/katex.min.js',
  'data/quark_weights.json',
  'data/quark_weights.bin',
  'data/tokenizer.json',
  'data/reference.json',
];

// start.ps1 是 Windows 专属的本地静态服务器启动器,由 deploy.ps1(Windows 启动器)负责拷进部署目录。
// 本脚本保持纯跨平台、不碰任何平台专属文件,也不再为它给「根目录多余文件」断言开例外。

const log = (s) => console.log(s);
const fail = (msg) => { console.error('\n[FAILED] ' + msg); process.exit(1); };
const rel = (p) => path.relative(ROOT, p);
const exists = (p) => fs.existsSync(p);

// 清空目录内容(绕过 safe-delete 垫片:它包裹了 fs.rmSync/rmdirSync,会把删除重定向到回收站并失败)。
// 这里只 unlinkSync 文件 + 递归清子目录内容,不删除目录自身 —— 残留空目录无害,
// 下方 mkdirSync({recursive:true}) 幂等重建,copyFileSync 覆盖写入。
function rmSyncRecursive(p) {
  if (!fs.existsSync(p)) return;
  for (const e of fs.readdirSync(p, { withFileTypes: true })) {
    const c = path.join(p, e.name);
    if (e.isDirectory()) rmSyncRecursive(c);
    else fs.unlinkSync(c);
  }
}

// ───────────────────────────── 源检查
if (!exists(path.join(ROOT, 'index.html'))) {
  fail('index.html not found next to this script. Keep this file in the repository root.');
}

// ───────────────────────────── 清空并重建目标树
rmSyncRecursive(DEST);
for (const d of [
  DEST,
  path.join(DEST, 'css'),
  path.join(DEST, 'js'),
  path.join(DEST, 'lib', 'katex', 'fonts'),
  path.join(DEST, 'data'),
]) {
  fs.mkdirSync(d, { recursive: true });
}

// ───────────────────────────── 复制工具(字节级,零转换)
function copyFile(relPath) {
  const src = path.join(ROOT, relPath);
  const dst = path.join(DEST, relPath);
  if (!exists(src)) { console.log('  [warn] missing source, skipped: ' + relPath); return false; }
  fs.copyFileSync(src, dst); // 保留原始字节(项目铁律:dump 文件零转换,不碰行尾)
  return true;
}

function copyDir(srcRel, dstRel = srcRel) {
  const src = path.join(ROOT, srcRel);
  const dst = path.join(DEST, dstRel);
  if (!exists(src)) { console.log('  [warn] missing source dir, skipped: ' + srcRel); return; }
  fs.mkdirSync(dst, { recursive: true });
  for (const e of fs.readdirSync(src, { withFileTypes: true })) {
    const s = path.join(src, e.name);
    const d = path.join(dst, e.name);
    if (e.isDirectory()) copyDir(path.join(srcRel, e.name), path.join(dstRel, e.name));
    else fs.copyFileSync(s, d);
  }
}

// ───────────────────────────── 复制
console.log('============================================================');
console.log('  public - build the EdgeOne deploy folder');
console.log('  source : ' + rel(ROOT) + '/');
console.log('  target : ' + rel(DEST) + '/');
console.log('============================================================');
console.log('');

copyFile('index.html');
copyDir('css');
copyDir('js');

// KaTeX:只带 index.html 加载的 2 个 core 文件 + 其 css 需要的 fonts。
// 不带 lib/katex/contrib/(那是 auto-render.min.js,本项目明确禁用 auto-render)。
copyFile('lib/katex/katex.min.css');
copyFile('lib/katex/katex.min.js');
copyDir('lib/katex/fonts');

for (const f of DATA_FILES) copyFile(path.join('data', f));

// 注:start.ps1(Windows 本地启动器)不再由本脚本复制 —— 改由 deploy.ps1 在 Windows 上补拷。

// ───────────────────────────── required 断言
let missing = 0;
for (const r of REQUIRED) {
  if (!exists(path.join(DEST, r))) { console.log('  [MISSING] ' + r); missing++; }
}
if (missing) fail('required files are missing -- the deploy folder is incomplete.');
log('  all 9 required entry files present  [OK]');

// ───────────────────────────── 精确性断言(不能多)
const topFiles = (dir) => fs.readdirSync(dir, { withFileTypes: true }).filter((e) => e.isFile()).map((e) => e.name);

const strayRoot = topFiles(DEST).filter((f) => f !== 'index.html');
if (strayRoot.length) fail('unexpected file(s) at deploy root: ' + strayRoot.join(', '));

const strayData = topFiles(path.join(DEST, 'data')).filter((f) => !DATA_FILES.includes(f));
if (strayData.length) fail('unexpected file(s) in data/: ' + strayData.join(', '));

const katexDir = path.join(DEST, 'lib', 'katex');
const strayKatex = fs.readdirSync(katexDir, { withFileTypes: true }).filter(
  (e) => !((e.isFile() && (e.name === 'katex.min.css' || e.name === 'katex.min.js')) || (e.isDirectory() && e.name === 'fonts')),
);
if (strayKatex.length) fail('unexpected entry in lib/katex/: ' + strayKatex.map((e) => e.name).join(', '));

log('  no stray files  [OK]');

// ───────────────────────────── 统计
function countFiles(dir) {
  let n = 0;
  for (const e of fs.readdirSync(dir, { withFileTypes: true })) {
    const p = path.join(dir, e.name);
    if (e.isDirectory()) n += countFiles(p);
    else n++;
  }
  return n;
}

const N = countFiles(DEST);
log('');
log('[DONE]  deploy folder is ready: ' + N + ' files');
log('        ' + rel(DEST) + '/');
log('        Upload that folder as-is. No config file needed for a static site.');