"use strict";

/**
 * 生成标题、标签、分组关键词（对齐 Electron ipAgent:generateTitleTags）
 */
const pipelineNative = require("./pipeline_native.js");
const desktopConfig = require("./desktop_config.js");

const KEYWORD_GROUPS = ["重点词/成语词", "描述词", "行动词", "情感词"];

const DEFAULT_TITLE_TAG_PROMPT = `你是短视频标题与标签助手。分析以下文案内容，生成：
1. 一个最吸引人的标题（不超过30字，若需多个建议可写在 title 字段内用换行分隔）
2. 8-10 个相关话题标签（带 # 号）
3. 四个分组关键词，每组 0-2 个词：重点词/成语词、描述词、行动词、情感词

文案内容：
{{content}}

请只返回 JSON，不要 markdown，格式如下：
{
  "title": "标题",
  "tags": ["#标签1", "#标签2"],
  "keywords": {
    "重点词/成语词": ["词1"],
    "描述词": [],
    "行动词": [],
    "情感词": []
  }
}`;

function buildPrompt(template, content) {
  let prompt = String(template || "").trim();
  if (!prompt) prompt = DEFAULT_TITLE_TAG_PROMPT;
  return prompt
    .replace(/\{\{content\}\}/g, content)
    .replace(/\{content\}/g, content);
}

function cleanJsonText(raw) {
  let text = String(raw || "").trim();
  text = text.replace(/```json\s*/gi, "");
  text = text.replace(/```\s*/g, "");
  text = text.trim();
  text = text.replace(/"/g, '"').replace(/"/g, '"');
  text = text.replace(/'/g, "'").replace(/'/g, "'");
  text = text.replace(/，/g, ",");
  const m = text.match(/\{[\s\S]*\}/);
  if (m) text = m[0];
  return text;
}

function normalizeTags(tags) {
  if (Array.isArray(tags)) {
    return tags
      .map((t) => String(t || "").trim())
      .filter(Boolean)
      .join(", ");
  }
  return String(tags || "").trim();
}

function normalizeKeywordGroup(val) {
  if (Array.isArray(val)) {
    return val
      .map((w) => String(w || "").trim())
      .filter(Boolean)
      .join("\n");
  }
  if (typeof val === "string") {
    return val
      .split(/[,，\n]/)
      .map((w) => w.trim())
      .filter(Boolean)
      .join("\n");
  }
  return "";
}

function parseTitleTagsContent(content) {
  let title = "";
  let tags = "";
  const keywords = {};

  try {
    const parsed = JSON.parse(cleanJsonText(content));
    title = String(parsed.title || "").trim();
    tags = normalizeTags(parsed.tags);
    const kw = parsed.keywords;
    if (kw && typeof kw === "object" && !Array.isArray(kw)) {
      for (const group of KEYWORD_GROUPS) {
        keywords[group] = normalizeKeywordGroup(kw[group]);
      }
    } else if (Array.isArray(kw)) {
      keywords["重点词/成语词"] = normalizeKeywordGroup(kw);
    } else if (typeof kw === "string") {
      keywords["重点词/成语词"] = normalizeKeywordGroup(kw);
    }
  } catch {
    const lines = String(content).split("\n");
    for (const line of lines) {
      if (/标题|Title/i.test(line)) {
        title = (line.split(/[：:]/)[1] || "").trim() || line.trim();
      } else if (/标签|Tags|#/i.test(line)) {
        tags = (line.split(/[：:]/)[1] || "").trim() || line.trim();
      } else if (/关键词|Keywords/i.test(line)) {
        keywords["重点词/成语词"] = normalizeKeywordGroup(
          (line.split(/[：:]/)[1] || "").trim(),
        );
      }
    }
  }

  for (const group of KEYWORD_GROUPS) {
    if (!keywords[group]) keywords[group] = "";
  }

  const hasKeywords = KEYWORD_GROUPS.some((g) => keywords[g]);
  if (!title && !tags && !hasKeywords) {
    return null;
  }
  return { title, tags, keywords };
}

globalThis.__nodejsMain = async function main(params) {
  const p = params || {};
  const content = String(p.content || p.script || "").trim();
  if (!content) {
    return { success: false, error: "请先填写视频文案" };
  }

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

  const prompt = buildPrompt(p.titleTagPrompt, content);

  globalThis.__native?.emitProgress?.("正在生成标题、标签和关键词…");

  const chat = await pipelineNative.openaiChat({
    apiUrl: modelConfig.apiUrl,
    apiKey: modelConfig.apiKey,
    model: modelConfig.apiModelId,
    messages: [{ role: "user", content: prompt }],
    temperature: typeof p.temperature === "number" ? p.temperature : 0.7,
    max_tokens: p.max_tokens || 2000,
  });

  if (!chat.success || !chat.content) {
    return { success: false, error: chat.error || "模型返回为空" };
  }

  const parsed = parseTitleTagsContent(chat.content);
  if (!parsed) {
    return {
      success: false,
      error: "解析结果为空，请检查模型返回格式",
      rawContent: chat.content,
    };
  }

  return {
    success: true,
    title: parsed.title,
    tags: parsed.tags,
    keywords: parsed.keywords,
    titleTags: JSON.stringify({
      title: parsed.title,
      tags: parsed.tags,
      keywords: parsed.keywords,
    }),
  };
};
