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

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

const copyTargets = [
  { from: path.join(rootDir, "index.js"), to: path.join(distDir, "index.js") },
  { from: path.join(rootDir, "lib"), to: path.join(distDir, "lib") },
  { from: path.join(rootDir, "bin"), to: path.join(distDir, "bin") },
  { from: path.join(rootDir, "package.json"), to: path.join(distDir, "package.json") },
  { from: path.join(rootDir, "Readme.md"), to: path.join(distDir, "Readme.md") }
];

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

  for (const target of copyTargets) {
    await copy(target.from, target.to);
  }

  console.log("Build written to", distDir);
}

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

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