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

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

const importObject = wasi.getImportObject();

let wasmExports = null;

const getWasmExportsLocal = async (headers) => {
    if(!wasmExports) {
        const bytes = await readFile('./.next/server/openship/wasm/openship_render.wasm');
        const wasmModule = new WebAssembly.Module(bytes);
        const instance = await WebAssembly.instantiate(wasmModule, importObject);
        wasi.initialize(instance); const { memory, render, dealloc_str } = instance.exports;
        wasmExports = { memory, render, dealloc_str };
    } return wasmExports;
}

export async function GET(request) {
 const { memory, render, dealloc_str } = await getWasmExportsLocal(request.headers);
 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);
}
