"use strict";

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

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

const ELECTRON_DEFAULT_TITLE_TAG_PROMPT =
  "你是短视频标题与标签助手。分析文案内容 {{content}}，生成5个吸引眼球的标题建议、10个相关标签、4个分组关键词（每组：重点词/成语词、描述词、行动词、情感词，每个分组只要0-2个词不要多）。";

const JSON_OUTPUT_SUFFIX = `

请只返回 JSON，不要 markdown，格式如下：
{
  "title": "最推荐标题（多个标题建议可用换行分隔）",
  "tags": ["#标签1", "#标签2"],
  "keywords": {
    "重点词/成语词": ["词1"],
    "描述词": [],
    "行动词": [],
    "情感词": []
  }
}`;

function logInfo(tag, payload) {
  if (payload === undefined) {
    console.info(tag);
    return;
  }
  if (typeof payload === "string") {
    console.info(`${tag} - ${payload}`);
    return;
  }
  console.info(`${tag} - ${JSON.stringify(payload)}`);
}

function buildPrompt(template, content) {
  let prompt = String(template || "").trim();
  if (!prompt) prompt = ELECTRON_DEFAULT_TITLE_TAG_PROMPT;
  prompt = prompt
    .replace(/\{\{content\}\}/g, content)
    .replace(/\{content\}/g, content);
  if (!/json|JSON/.test(prompt)) {
    prompt += JSON_OUTPUT_SUFFIX;
  }
  return prompt;
}

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 normalizeTitle(val) {
  if (Array.isArray(val)) {
    return val
      .map((t) => String(t || "").trim())
      .filter(Boolean)
      .join("\n");
  }
  return String(val || "").trim();
}

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

  try {
    const parsed = JSON.parse(cleanJsonText(content));
    logInfo("ipAgent.generateTitleTags.cleanedContent", cleanJsonText(content));
    title = normalizeTitle(parsed.title || parsed.titles);
    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);
    }
    logInfo("ipAgent.generateTitleTags.parsed", { title, tags, keywords });
  } catch (err) {
    logInfo("ipAgent.generateTitleTags.jsonParseFailed", {
      error: err instanceof Error ? err.message : String(err),
      content,
    });
    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 };
}

function validateLlmConfig(modelConfig) {
  if (!modelConfig.apiKey) {
    return { ok: false, error: "缺少配置 LLM_API_KEY（desktop_configs 表）" };
  }
  if (!modelConfig.apiUrl) {
    return { ok: false, error: "缺少配置 LLM_BASE_URL（或 LLM_API_URL）" };
  }
  return { ok: true };
}

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 = validateLlmConfig(modelConfig);
  if (!check.ok) {
    return { success: false, error: check.error };
  }

  const prompt = buildPrompt(p.titleTagPrompt, content);
  const requestPayload = {
    model: modelConfig.apiModelId,
    messages: [{ role: "user", content: prompt }],
  };

  logInfo("ipAgent.generateTitleTags", {
    scriptLength: content.length,
    modelConfig: {
      providerId: modelConfig.providerId,
      modelId: modelConfig.apiModelId,
      apiUrl: modelConfig.apiUrl,
      apiHost: "",
      apiKey: modelConfig.apiKey,
      type: modelConfig.type,
    },
  });
  logInfo("ipAgent.generateTitleTags.REQUEST", {
    apiUrl: modelConfig.apiUrl,
    model: modelConfig.apiModelId,
    promptLength: prompt.length,
    hasApiKey: Boolean(modelConfig.apiKey),
  });
  logInfo("ipAgent.generateTitleTags.REQUEST_FULL_PROMPT", prompt);
  logInfo(
    "ipAgent.generateTitleTags.REQUEST_FULL_PAYLOAD",
    JSON.stringify(requestPayload, null, 2),
  );

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

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

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

  logInfo("ipAgent.generateTitleTags.RESPONSE_CONTENT", chat.content);
  logInfo("ipAgent.generateTitleTags.rawContent", { content: chat.content });

  const parsed = parseTitleTagsContent(chat.content);
  if (!parsed) {
    logInfo("ipAgent.generateTitleTags.emptyResult", { content: chat.content });
    return {
      success: false,
      error: "解析结果为空，AI返回内容: " + chat.content,
      rawContent: chat.content,
    };
  }

  logInfo("ipAgent.generateTitleTags.success", {
    title: parsed.title,
    tags: parsed.tags,
    keywords: parsed.keywords,
  });

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