export function buildUserPrompt(payload) {
  const history = Array.isArray(payload.conversationHistory) ? payload.conversationHistory.slice(-8) : [];
  const sections = [
    "请基于当前网页材料帮助用户继续对话。",
    "如果页面信息不足，请明确说明缺失点；如果和历史对话冲突，优先使用最新页面材料。",
    ""
  ];

  if (history.length) {
    sections.push("最近对话：");
    sections.push(
      history
        .map((item) => `${item.role === "assistant" ? "Assistant" : "User"}: ${item.text}`)
        .join("\n")
    );
    sections.push("");
  }

  sections.push("本轮用户请求：");
  sections.push(String(payload.userInstruction || "").trim() || "解释当前页面，并给出下一步建议。");
  sections.push("");

  if (payload.includeScreenshot) {
    sections.push("本轮附带了一张页面截图。");
    sections.push("");
  }

  if (payload.includePageContext) {
    sections.push("页面内容：");
    sections.push(JSON.stringify(payload.pageContext || {}, null, 2));
  } else {
    sections.push("本轮没有附带新的页面内容。");
  }

  return sections.filter(Boolean).join("\n");
}
