"use strict";

/**
 * 选题库一键仿写标题（对齐 Electron ipAgent:rewriteTitles）
 */

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

const DEFAULT_TOPIC_REWRITE_PROMPT = `参考以下标题，帮我生成新的标题。要求：
1. 保持相似的主题和风格
2. 标题简洁有力
3. 不要添加表情符号和标签
4. 直接输出与参考数量相同的新标题，每行一个，不要编号

参考标题：
{{content}}

请生成新标题：`;

function buildTopicRewritePrompt(titles, customPrompt) {
  const titlesText = titles.map((t, i) => `${i + 1}. ${t}`).join("\n");
  let prompt = String(customPrompt || "").trim();
  if (!prompt) {
    prompt = DEFAULT_TOPIC_REWRITE_PROMPT;
  }
  return prompt
    .replace(/\{\{content\}\}/g, titlesText)
    .replace(/\{content\}/g, titlesText);
}

function parseRewrittenLines(content, fallbackTitles) {
  const lines = String(content || "")
    .trim()
    .split("\n")
    .map((line) => line.replace(/^[\d\s.\-、]+/, "").trim())
    .filter(Boolean);

  if (lines.length >= fallbackTitles.length) {
    return lines.slice(0, fallbackTitles.length);
  }
  const out = [...lines];
  for (let i = lines.length; i < fallbackTitles.length; i++) {
    out.push(fallbackTitles[i]);
  }
  return out;
}

globalThis.__nodejsMain = async function (params) {
  const titles = Array.isArray(params?.titles) ? params.titles.filter(Boolean) : [];
  if (titles.length === 0) {
    return { success: false, error: "没有可仿写的标题" };
  }

  const modelConfig = desktopConfig.buildModelConfig();
  const check = desktopConfig.validateModelConfig(modelConfig);
  if (!check.ok) {
    return { success: false, error: check.error };
  }

  const prompt = buildTopicRewritePrompt(titles, params?.rewritePrompt);
  const chat = await pipelineNative.openaiChat({
    apiUrl: modelConfig.apiUrl,
    apiKey: modelConfig.apiKey,
    model: modelConfig.apiModelId,
    messages: [{ role: "user", content: prompt }],
    temperature: 0.85,
    max_tokens: 1500,
  });

  if (!chat?.success || !chat.content) {
    return { success: false, error: chat?.error || "标题仿写失败" };
  }

  const rewrittenTitles = parseRewrittenLines(chat.content, titles);
  return { success: true, rewrittenTitles };
};
