"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.run = run;
const node_worker_threads_1 = require("node:worker_threads");
const node_path_1 = require("node:path");
let messageIdCounter = 0;
const pendingPromises = new Map();
// Resolve worker path - explicitly use .js extension as worker threads require compiled files
// When running tests from src/, __filename is src/utils/main/workerPool.ts
// We need to resolve to dist/utils/main/tokenizer.worker.js
// Use platform-aware path component manipulation to handle Windows backslashes
const currentDir = (0, node_path_1.dirname)(__filename);
const pathParts = currentDir.split(node_path_1.sep);
const srcIndex = pathParts.indexOf("src");
let workerDir;
if (srcIndex !== -1) {
    // Replace 'src' with 'dist' in the path (works on Windows and Unix)
    pathParts[srcIndex] = "dist";
    workerDir = pathParts.join(node_path_1.sep);
}
else {
    workerDir = currentDir;
}
const workerPath = (0, node_path_1.join)(workerDir, "tokenizer.worker.js");
const worker = new node_worker_threads_1.Worker(workerPath);
// Handle messages from worker
worker.on("message", (response) => {
    const pending = pendingPromises.get(response.messageId);
    if (!pending) {
        console.error(`[workerPool] No pending promise for messageId ${response.messageId}`);
        return;
    }
    pendingPromises.delete(response.messageId);
    if ("error" in response) {
        const error = new Error(response.error.message);
        error.stack = response.error.stack;
        pending.reject(error);
    }
    else {
        pending.resolve(response.result);
    }
});
// Handle worker errors
worker.on("error", (error) => {
    console.error("[workerPool] Worker error:", error);
    // Reject all pending promises
    for (const pending of pendingPromises.values()) {
        pending.reject(error);
    }
    pendingPromises.clear();
});
// Handle worker exit
worker.on("exit", (code) => {
    if (code !== 0) {
        console.error(`[workerPool] Worker stopped with exit code ${code}`);
        const error = new Error(`Worker stopped with exit code ${code}`);
        for (const pending of pendingPromises.values()) {
            pending.reject(error);
        }
        pendingPromises.clear();
    }
});
// Don't block process exit
worker.unref();
/**
 * Run a task on the worker thread
 * @param taskName The name of the task to run (e.g., "countTokens", "encodingName")
 * @param data The data to pass to the task
 * @returns A promise that resolves with the task result
 */
function run(taskName, data) {
    const messageId = messageIdCounter++;
    const request = { messageId, taskName, data };
    return new Promise((resolve, reject) => {
        pendingPromises.set(messageId, {
            resolve: resolve,
            reject,
        });
        worker.postMessage(request);
    });
}
//# sourceMappingURL=workerPool.js.map