// This is a complicated little dance to load the DSP engine, which is a plain ES6 module, into Turbopack.
import type { MainModule } from '@/../dsp-artifacts/dsp-engine';

export type * from '@/../dsp-artifacts/dsp-engine';

// These need to be statically analyzable by Turbopack and Webpack
const dspEngineShimUrl = new URL(
  '@/../dsp-artifacts/dsp-engine.js',
  import.meta.url
);
const dspEngineWasmUrl = new URL(
  '@/../dsp-artifacts/dsp-engine.wasm',
  import.meta.url
);
const dspEngineAudioWorkletShimUrl = new URL(
  '@/../dsp-artifacts/dsp-engine.aw.js',
  import.meta.url
);
const dspEngineWorkerShimUrl = new URL(
  '@/../dsp-artifacts/dsp-engine.ww.js',
  import.meta.url
);

let dspEngineSingletonPromise: Promise<MainModule> | null = null;

const loadDspEngine = async () => {
  const createDspEngineModule = await import(
    /* webpackIgnore: true */ dspEngineShimUrl.toString()
  );
  const theModule = await createDspEngineModule.default({
    locateFile: (path: string, prefix: string) => {
      console.log('locateFile', path, prefix);
      if (path === 'dsp-engine.js') {
        return dspEngineShimUrl.toString();
      } else if (path === 'dsp-engine.wasm') {
        return dspEngineWasmUrl.toString();
      } else if (path === 'dsp-engine.aw.js') {
        return dspEngineAudioWorkletShimUrl.toString();
      } else if (path === 'dsp-engine.ww.js') {
        return dspEngineWorkerShimUrl.toString();
      } else {
        throw new Error(`Unknown DSP artifact: ${path}`);
      }
    },
  });
  return theModule;
};

export const dspEngineSingleton = () => {
  if (dspEngineSingletonPromise === null && typeof window !== 'undefined') {
    dspEngineSingletonPromise = loadDspEngine();
  }
  return dspEngineSingletonPromise!;
};
