import test from "node:test";
import assert from "node:assert/strict";

import { buildAnalyzeRequest } from "../sidepanel/services/request-builder.js";

test("buildAnalyzeRequest keeps page snapshot, screenshot and recent history only", () => {
  const payload = buildAnalyzeRequest({
    userInstruction: "  请总结这个页面  ",
    pageSnapshot: {
      page: {
        title: "Demo",
        url: "https://example.com"
      }
    },
    turnAttachments: {
      screenshotDataUrl: "data:image/png;base64,abc"
    },
    includePageContext: true,
    includeScreenshot: true,
    chatSession: {
      messages: Array.from({ length: 10 }, (_, index) => ({
        role: index % 2 === 0 ? "user" : "assistant",
        text: `message-${index}`
      }))
    }
  });

  assert.equal(payload.userInstruction, "请总结这个页面");
  assert.deepEqual(payload.pageContext.page, {
    title: "Demo",
    url: "https://example.com"
  });
  assert.equal(payload.screenshotDataUrl, "data:image/png;base64,abc");
  assert.equal(payload.includePageContext, true);
  assert.equal(payload.includeScreenshot, true);
  assert.equal(payload.conversationHistory.length, 8);
  assert.equal(payload.conversationHistory[0].text, "message-2");
  assert.equal(payload.conversationHistory.at(-1).text, "message-9");
});

test("buildAnalyzeRequest strips optional attachments when disabled", () => {
  const payload = buildAnalyzeRequest({
    userInstruction: "",
    pageSnapshot: { page: { title: "Demo" } },
    turnAttachments: { screenshotDataUrl: "data:image/png;base64,abc" },
    includePageContext: false,
    includeScreenshot: false,
    chatSession: { messages: [] }
  });

  assert.deepEqual(payload.pageContext, {});
  assert.equal(payload.screenshotDataUrl, "");
  assert.equal(payload.includePageContext, false);
  assert.equal(payload.includeScreenshot, false);
});
