import { readFile } from 'node:fs/promises';
import { WASI } from 'node:wasi';
import path from 'path';

import wasm from '@openship/nextjs/openship_render.wasm?module';

const wasi = new WASI({ 
    version: 'preview1',
    args: process.argv, 
    env: process.env, 
    preopens: { '/cwd': process.cwd(), }
  });

// const file = path.join(process.cwd(), '.next/wasm/openship_render.wasm')
// console.log('FFF', file);

// const wasmBuffer = await readFile(new URL(file, import.meta.url));
// const wasm = await WebAssembly.compile(wasmBuffer);
const importObject = wasi.getImportObject();
const instance = await WebAssembly.instantiate(wasm, importObject);
const { memory, render, dealloc_str } = instance.exports;
wasi.initialize(instance);

export async function GET() {
    console.log('CWD', process.cwd());
    const ptr = render();

    let result = '';
    const view = new Uint8Array(memory.buffer);
    let i = ptr;
    while (view[i] !== 0) {
      result += String.fromCharCode(view[i]);
      i++;
    }
    dealloc_str(ptr);
  
    const data = JSON.parse(result);
    return Response.json(data);
}