const g = globalThis as typeof globalThis & {
  DOMMatrix?: typeof DOMMatrix;
  Path2D?: typeof Path2D;
  ImageData?: typeof ImageData;
};

if (typeof g.DOMMatrix === "undefined") {
  g.DOMMatrix = class DOMMatrix {
    a = 1;
    b = 0;
    c = 0;
    d = 1;
    e = 0;
    f = 0;
    constructor(init?: number[]) {
      if (init && init.length >= 6) {
        [this.a, this.b, this.c, this.d, this.e, this.f] = init;
      }
    }
  } as typeof DOMMatrix;
}

if (typeof g.Path2D === "undefined") {
  g.Path2D = class Path2D {} as typeof Path2D;
}

if (typeof g.ImageData === "undefined") {
  g.ImageData = class ImageData {
    width = 0;
    height = 0;
    data = new Uint8ClampedArray(0);
    constructor(width?: number, height?: number) {
      this.width = width ?? 0;
      this.height = height ?? 0;
    }
  } as typeof ImageData;
}

export async function importPdfJs() {
  const pdfUrl = new URL("../../../node_modules/@llamaindex/liteparse/dist/src/vendor/pdfjs/pdf.mjs", import.meta.url);
  const pdfjs = await import(/* @vite-ignore */ pdfUrl.href);
  const dir = new URL("../../../node_modules/@llamaindex/liteparse/dist/src/vendor/pdfjs/", import.meta.url).href;
  return {
    fn: pdfjs.getDocument,
    dir,
  };
}
