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");
const bridgeFile = path.resolve(__dirname, "..", "tauri-bridge.js");

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,
  });

  await fs.copy(bridgeFile, path.join(dest, "tauri-bridge.js"));
}

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 injectBridge() {
  const files = await findHtmlFiles(dest);
  await Promise.all(
    files.map(async (fullPath) => {
      const html = await fs.readFile(fullPath, "utf8");
      if (html.includes("tauri-bridge.js")) return;

      const scriptPath = path
        .relative(path.dirname(fullPath), path.join(dest, "tauri-bridge.js"))
        .replace(/\\/g, "/");
      const injection = `\n    <script type="module" src="${scriptPath}"></script>\n  </body>`;
      const updated = html.replace(/\n?\s*<\/body>/i, injection);
      await fs.writeFile(fullPath, updated, "utf8");
    })
  );
}

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

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