#!/usr/bin/env node
import { promises as fs } from "fs";
import path from "path";
import { fileURLToPath } from "url";
import esbuild from "esbuild";

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const rootDir = path.resolve(__dirname, "..");
const distDir = path.join(rootDir, "dist");

async function main() {
  await fs.rm(distDir, { recursive: true, force: true });
  await fs.mkdir(distDir, { recursive: true });

  await esbuild.build({
    entryPoints: [path.join(rootDir, "index.js")],
    bundle: true,
    platform: "node",
    target: "node16",
    format: "esm",
    outfile: path.join(distDir, "index.js"),
    minify: true,
    external: ["sharp", "@cocos/fbx2gltf"],
  });

  // 添加 shebang
  const outPath = path.join(distDir, "index.js");
  const code = await fs.readFile(outPath, "utf8");
  await fs.writeFile(outPath, "#!/usr/bin/env node\n" + code.replace(/^#!.*\n?/, ""), "utf8");

  await copyDir(path.join(rootDir, "bin"), path.join(distDir, "bin"));
  console.log("Build written to", distDir);
}

async function copyDir(src, dest) {
  await fs.mkdir(dest, { recursive: true });
  const entries = await fs.readdir(src);
  for (const entry of entries) {
    await fs.copyFile(path.join(src, entry), path.join(dest, entry));
  }
}

main().catch(err => {
  console.error("Build failed:", err);
  process.exitCode = 1;
});
