/**
 * 把 assets-compressed/ 整目录打包成 cyber-star-assets.tar.gz
 * 用 node 自带 tar 模块的等价方式 (调系统 tar)
 */
import { spawn } from "node:child_process";
import { existsSync, statSync } from "node:fs";
import { resolve, dirname } from "node:path";
import { fileURLToPath } from "node:url";

const __dirname = dirname(fileURLToPath(import.meta.url));
const REPO_ROOT = resolve(__dirname, "..", "..");
const PARENT = resolve(REPO_ROOT, "..");
const SRC_DIR = "assets-compressed";
const OUT_FILE = "cyber-star-assets.tar.gz";

function fmt(n) {
  if (n >= 1024 * 1024 * 1024) return `${(n / 1024 / 1024 / 1024).toFixed(2)}GB`;
  if (n >= 1024 * 1024) return `${(n / 1024 / 1024).toFixed(1)}MB`;
  return `${(n / 1024).toFixed(0)}KB`;
}

const srcAbs = resolve(PARENT, SRC_DIR);
if (!existsSync(srcAbs)) {
  console.error(`❌ 找不到压缩输出目录: ${srcAbs}\n请先运行 npm run compress`);
  process.exit(1);
}

console.log("打包源:", srcAbs);
console.log("输出: ", resolve(PARENT, OUT_FILE));

const t0 = Date.now();
const tar = spawn(
  "tar",
  ["-czf", OUT_FILE, SRC_DIR],
  { cwd: PARENT, stdio: "inherit" },
);

tar.on("close", (code) => {
  if (code !== 0) {
    console.error(`❌ tar 退出码 ${code}`);
    process.exit(code ?? 1);
  }
  const size = statSync(resolve(PARENT, OUT_FILE)).size;
  console.log(
    `✅ 打包完成: ${OUT_FILE}  ${fmt(size)}  用时 ${((Date.now() - t0) / 1000).toFixed(1)}s`,
  );
});
