import { parseAnalyzePayload } from "../../shared/schema.js";

export function buildAnalyzeRequest({
  userInstruction,
  pageSnapshot,
  turnAttachments,
  includePageContext,
  includeScreenshot,
  chatSession
}) {
  return parseAnalyzePayload({
    userInstruction: String(userInstruction || "").trim(),
    pageContext: includePageContext ? pageSnapshot || {} : {},
    includePageContext,
    screenshotDataUrl: includeScreenshot ? turnAttachments?.screenshotDataUrl || "" : "",
    includeScreenshot,
    conversationHistory: buildConversationHistory(chatSession)
  });
}

function buildConversationHistory(chatSession) {
  return (Array.isArray(chatSession?.messages) ? chatSession.messages : []).slice(-8).map((item) => ({
    role: item.role,
    text: item.text
  }));
}
