// translation-worker-handler（Phase 1 引擎抽象与 Worker 化）。
// 纯处理器：接收协议信封 → 绑定 session → 分发到共享 OnnxLocalTranslator
// （模型管理/可用性/prepare/translate/cancel）。
// 不依赖全局 self / chrome，便于 Node 测试注入 fake 端点和真实类。
// 旧 session（sessionId 不匹配）的消息直接丢弃。
import { OnnxLocalTranslator } from "./onnx-translator.js";
import { ProviderError } from "./providers.js";
import { encodeWorkerEvent, encodeWorkerResponse, isWorkerRequestMessage } from "./worker-protocol.js";
export function createTranslationWorkerHandler(deps) {
    const translator = deps.translator ?? new OnnxLocalTranslator();
    let sessionId;
    let lastRequestSequence = 0;
    let eventSequence = 0;
    const postEvent = (event) => {
        if (!sessionId)
            return;
        deps.post(encodeWorkerEvent(sessionId, ++eventSequence, event));
    };
    translator.setDiagnostics((line) => postEvent({ type: "diagnostic", line }));
    async function handle(message) {
        if (!isWorkerRequestMessage(message))
            return;
        if (sessionId === undefined)
            sessionId = message.sessionId;
        else if (message.sessionId !== sessionId)
            return;
        if (message.sequence <= lastRequestSequence)
            return;
        lastRequestSequence = message.sequence;
        try {
            const request = message.request;
            switch (request.type) {
                case "model.status":
                    reply(message, await translator.modelStatus());
                    break;
                case "model.inspect":
                    reply(message, await translator.inspectModel());
                    break;
                case "model.download":
                    reply(message, { ok: translator.beginModelDownload() });
                    break;
                case "model.cancel":
                    await translator.cancelDownload();
                    reply(message, { ok: true });
                    break;
                case "model.remove":
                    await translator.removeModel();
                    reply(message, { ok: true });
                    break;
                case "models.clear":
                    await translator.removeModel();
                    reply(message, { ok: true });
                    break;
                case "availability":
                    reply(message, await translator.availability());
                    break;
                case "prepare":
                    await translator.prepare(request.sourceLanguage);
                    reply(message, { ok: true });
                    break;
                case "translate": {
                    const text = await translator.translate(request.requestId, request.text, request.sourceLanguage, request.priority, request.context);
                    reply(message, { text, ...(request.context ? { requestId: request.requestId, context: request.context } : {}) });
                    break;
                }
                case "cancel":
                    translator.cancel(request.requestId);
                    reply(message, { ok: true });
                    break;
                default: throw new Error("translation_unknown_request");
            }
        }
        catch (error) {
            deps.post(encodeWorkerResponse(message.sessionId, message.sequence, { ok: false, error: errorCode(error) }));
        }
    }
    function reply(message, result) {
        deps.post(encodeWorkerResponse(message.sessionId, message.sequence, { ok: true, result }));
    }
    return {
        handle,
        dispose() {
            // 挂起的 translate 由客户端 WorkerConnection 在 terminate/failure 时统一 reject，
            // worker 内部无需主动清理队列。
            return Promise.resolve();
        },
    };
}
function errorCode(error) {
    if (error instanceof ProviderError)
        return error.code;
    if (error instanceof Error)
        return error.message;
    return String(error);
}
