import fs from "fs-extra";
import path from "node:path";
import { fileURLToPath } from "node:url";

const __dirname = path.dirname(fileURLToPath(import.meta.url));

const root = path.resolve(__dirname, "..", "..");
const source = path.join(root, "chat", "public");
const dest = path.resolve(__dirname, "..", "ui-dist");

async function copyUi() {
  if (!(await fs.pathExists(source))) {
    throw new Error(`Source UI folder not found: ${source}`);
  }

  await fs.emptyDir(dest);
  await fs.copy(source, dest, {
    filter: (src) => !src.endsWith(".map") && !src.includes(".DS_Store"),
    overwrite: true,
  });
}

async function findHtmlFiles(dir) {
  const entries = await fs.readdir(dir, { withFileTypes: true });
  const files = await Promise.all(
    entries.map(async (entry) => {
      const full = path.join(dir, entry.name);
      if (entry.isDirectory()) {
        return findHtmlFiles(full);
      }
      return entry.isFile() && entry.name.endsWith(".html") ? [full] : [];
    })
  );
  return files.flat();
}

async function main() {
  await copyUi();
  console.log(`UI prepared in ${dest}`);
}

main().catch((err) => {
  console.error(err);
  process.exit(1);
});
