"use strict";

/**
 * 文案转语音（对齐 Electron generateAudio / CosyVoice）
 */

const fs = require("fs");
const path = require("path");
const os = require("os");
const pipelineNative = require("./pipeline_native.js");
const desktopConfig = require("./desktop_config.js");

const OUTPUT_DIR = path.join(os.tmpdir(), "aiclient-generated-speech");

globalThis.__nodejsMain = async function (params) {
  const p = params || {};
  const apiKey =
    desktopConfig.get("BAILIAN_API_KEY") ||
    desktopConfig.get("DASHSCOPE_API_KEY");
  if (!apiKey) {
    return {
      success: false,
      error: "缺少 BAILIAN_API_KEY（或 DASHSCOPE_API_KEY），请在配置中设置",
    };
  }

  const text = String(p.text || "").trim();
  if (!text) {
    return { success: false, error: "请先在「视频文案编辑」中填写文案内容" };
  }

  const voice = String(p.voice || "").trim();
  if (!voice) {
    return { success: false, error: "请先选择音色" };
  }

  fs.mkdirSync(OUTPUT_DIR, { recursive: true });
  const ext = String(p.format || "mp3").toLowerCase() === "wav" ? ".wav" : ".mp3";
  const outputPath =
    p.outputPath ||
    path.join(OUTPUT_DIR, `speech_${Date.now()}${ext}`);

  return pipelineNative.qwenTtsSynthesize({
    apiKey,
    text,
    voice,
    model: p.model,
    instruction: p.instruction,
    languageType: p.languageType,
    outputPath,
  });
};
