import fs from "fs";
import path from "path";
import { JSDOM } from "jsdom";

const QT_DOCS_PATH = "./public/docs/qt";
const QT_DOCS_WEIGHT = 0.5;

async function processQtDocs(dir: string) {
  const files = fs.readdirSync(dir);

  for (const file of files) {
    const fullPath = path.join(dir, file);
    if (fs.lstatSync(fullPath).isDirectory()) {
      await processQtDocs(fullPath);
      continue;
    }

    if (file.endsWith(".html")) {
      const html = fs.readFileSync(fullPath, "utf8");
      const dom = new JSDOM(html);
      const { document } = dom.window;

      // remove common Qt doc noise selectors
      const noiseSelectors = [
        ".sidebar",
        "nav",
        ".header",
        ".footer",
        ".heading",
        ".toc",
        ".navigationbar",
      ];

      noiseSelectors.forEach(selector => {
        document
          .querySelectorAll(selector)
          .forEach(el => el.remove());
      });

      // inject pagefind meta
      const metaSource = document.createElement("meta");
      metaSource.setAttribute("data-pagefind-meta", "source:Qt");
      document.head.appendChild(metaSource);

      // lower weight for qt docs
      const metaWeight = document.createElement("meta");
      metaWeight.setAttribute(
        "data-pagefind-weight",
        QT_DOCS_WEIGHT.toString()
      );
      document.head.appendChild(metaWeight);

      fs.writeFileSync(fullPath, dom.serialize());
    }
  }
}

processQtDocs(QT_DOCS_PATH).catch(console.error);
