import MateModule from './wasm/matec.js';
import packageJson from './package.json' with { type: 'json' };

export const version = packageJson.version;

const mateWasmUrl = new URL('./wasm/matec.wasm', import.meta.url).toString();

export async function Mate() {
  const module = await MateModule({
    locateFile(fileName) {
      if (fileName.endsWith('.wasm')) {
        return mateWasmUrl;
      }
      return fileName;
    },
  });

  const parseVariable = (variable) => {
    const len = module.lengthBytesUTF8(variable) + 1;
    const ptr = module._malloc(len);
    module.stringToUTF8(variable, ptr, len);
    return ptr;
  };

  const compile = (source, name) => {
    const sourcePtr = parseVariable(source);
    const namePtr = parseVariable(name);

    const resultPtr = module._parse_component(sourcePtr, namePtr);
    const result = module.UTF8ToString(resultPtr);

    module._free(sourcePtr);
    module._free(namePtr);
    module._free_string(resultPtr);

    return result;
  };

  return {
    compile,
  };
}
