"use strict";

/**
 * 音色试听（对齐 Electron aliyun:cosyvoice:synthesize + getPreCachedVoicePath）
 */

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 CACHE_DIR = path.join(os.tmpdir(), "aiclient-voice-preview-cache");

function buildPreviewText(title, customText) {
  if (customText && String(customText).trim()) {
    return String(customText).trim();
  }
  const shortName = String(title || "")
    .split("（")[0]
    .trim();
  return `你好，我是${shortName || "我"}，很高兴为您服务。`;
}

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 voice = String(p.voice || "").trim();
  if (!voice) {
    return { success: false, error: "缺少 voice 参数" };
  }

  const cacheKey = p.cacheKey ? String(p.cacheKey).trim() : "";
  fs.mkdirSync(CACHE_DIR, { recursive: true });

  let outputPath;
  if (cacheKey) {
    outputPath = path.join(CACHE_DIR, `${cacheKey.replace(/[^\w.-]/g, "_")}.wav`);
    if (fs.existsSync(outputPath)) {
      return { success: true, audioPath: outputPath, cached: true };
    }
  } else {
    outputPath = path.join(
      CACHE_DIR,
      `preview-${Date.now()}-${Math.random().toString(36).slice(2)}.wav`,
    );
  }

  const text = buildPreviewText(p.title, p.text);
  const result = await pipelineNative.qwenTtsSynthesize({
    apiKey,
    text,
    voice,
    model: p.model,
    instruction:
      p.instruction ||
      "请用自然、清晰、适合短视频配音的风格朗读。",
    outputPath,
  });

  if (!result.success) {
    return result;
  }
  return { ...result, cached: false };
};
