export interface TeaVmJavaRegexModule {
  readonly bridgeAbiVersion: () => number;
  readonly engineIdentity: () => string;
  readonly selfTest: () => number;
  readonly execute: (
    pattern: string,
    subject: string,
    applicationFlags: number,
    iterate: boolean,
    maximumMatches: number,
    maximumCaptureRows: number,
  ) => string;
  readonly replace: (
    pattern: string,
    subject: string,
    replacement: string,
    applicationFlags: number,
    iterate: boolean,
    maximumMatches: number,
    maximumCaptureRows: number,
  ) => string;
}

function isJavaRegexModule(
  imported: Partial<TeaVmJavaRegexModule>,
): imported is TeaVmJavaRegexModule {
  return (
    typeof imported.bridgeAbiVersion === "function" &&
    typeof imported.engineIdentity === "function" &&
    typeof imported.selfTest === "function" &&
    typeof imported.execute === "function" &&
    typeof imported.replace === "function"
  );
}

export async function importJavaRegexModule(
  moduleUrl: URL,
): Promise<TeaVmJavaRegexModule> {
  const imported = (await import(
    /* @vite-ignore */ moduleUrl.href
  )) as Partial<TeaVmJavaRegexModule>;
  if (!isJavaRegexModule(imported)) {
    throw new Error(
      "The bundled TeaVM Java regex module is missing its bridge exports.",
    );
  }
  return imported;
}
