/**
 * 构建前删除 dist，带重试。缓解 Windows 上 Vite emptyDir 的 EPERM（文件被资源管理器预览、杀毒、vite preview 等占用）。
 */
import fs from "fs";
import path from "path";
import { fileURLToPath } from "url";

const __dirname = path.dirname(fileURLToPath(import.meta.url));
const root = path.resolve(__dirname, "..");
const dirs = [path.join(root, "dist"), path.join(root, "output")];

const sleep = (ms) => new Promise((r) => setTimeout(r, ms));

async function rmDirWithRetry(dir) {
  for (let i = 0; i < 10; i++) {
    if (!fs.existsSync(dir)) {
      return true;
    }
    try {
      fs.rmSync(dir, { recursive: true, force: true });
      return true;
    } catch (e) {
      const code = e && typeof e === "object" && "code" in e ? e.code : "";
      const retryable = code === "EPERM" || code === "EBUSY" || code === "ENOTEMPTY";
      if (!retryable || i === 9) {
        console.error(`[clean-dist] 无法删除 ${path.relative(root, dir) || dir}:`, e instanceof Error ? e.message : e);
        return false;
      }
      await sleep(350 * (i + 1));
    }
  }
  return false;
}

async function main() {
  let ok = true;
  for (const dir of dirs) {
    const r = await rmDirWithRetry(dir);
    if (!r) ok = false;
  }
  if (!ok) {
    console.error(
      "请关闭占用上述目录的程序：资源管理器预览、vite preview、IDE、杀毒实时扫描等后执行 npm run clean。"
    );
    process.exit(1);
  }
}

await main();
