let model = null;

self.onmessage = async (ev) => {
    const msg = ev.data;

    if (msg.type === "init") {
        console.log("[Worker] carregando Whisper…");

        importScripts(
            self.location.origin + "/assets/whisper/main.js",
            self.location.origin + "/assets/whisper/helpers.js"
        );

        Module.onRuntimeInitialized = async () => {
            console.log("[Worker] WASM pronto");

            const resp = await fetch(self.location.origin + "/assets/whisper/ggml-tiny.en.bin");
            const buf  = await resp.arrayBuffer();
            const bytes = new Uint8Array(buf);

            const ptr = Module._malloc(bytes.length);
            Module.HEAPU8.set(bytes, ptr);

            model = Module._whisper_init_from_buffer(ptr, bytes.length);
            Module._free(ptr);

            console.log("[Worker] Modelo carregado");
            self.postMessage({ type: "ready" });
        };
    }

    if (msg.type === "pcm" && model) {
        const pcm = msg.pcm;
        const n   = pcm.length;

        const pcmPtr = Module._malloc(n * 4);
        Module.HEAPF32.set(pcm, pcmPtr / 4);

        Module._whisper_full(model, pcmPtr, n);

        const textPtr = Module._whisper_get_text(model);
        const text = Module.UTF8ToString(textPtr);

        Module._free(pcmPtr);

        if (text.trim() !== "")
            self.postMessage({ type: "final", text });
    }
};
