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

import {
  buildAttachmentReuseMessage,
  createEmptyAttachmentCache,
  planAttachmentReuse
} from "../sidepanel/services/attachment-dedupe.js";

if (!globalThis.crypto) {
  const { webcrypto } = await import("node:crypto");
  Object.defineProperty(globalThis, "crypto", {
    value: webcrypto,
    configurable: true
  });
}

test("planAttachmentReuse skips unchanged page context and screenshot", async () => {
  const payload = {
    includePageContext: true,
    includeScreenshot: true,
    pageSnapshot: {
      page: { title: "Demo", url: "https://example.com" },
      visibleTextExcerpt: "hello"
    },
    turnAttachments: {
      screenshotDataUrl: "data:image/png;base64,abc"
    },
    attachmentCache: createEmptyAttachmentCache()
  };

  const firstPlan = await planAttachmentReuse(payload);
  assert.equal(firstPlan.includePageContext, true);
  assert.equal(firstPlan.includeScreenshot, true);

  const secondPlan = await planAttachmentReuse({
    ...payload,
    attachmentCache: firstPlan.nextAttachmentCache
  });

  assert.equal(secondPlan.includePageContext, false);
  assert.equal(secondPlan.includeScreenshot, false);
  assert.equal(
    buildAttachmentReuseMessage(secondPlan),
    "检测到页面无变化，本轮复用上次页面上下文，不重复发送截图。"
  );
});

test("planAttachmentReuse still sends changed screenshot", async () => {
  const firstPlan = await planAttachmentReuse({
    includePageContext: true,
    includeScreenshot: true,
    pageSnapshot: { page: { title: "Demo" } },
    turnAttachments: { screenshotDataUrl: "data:image/png;base64,abc" },
    attachmentCache: createEmptyAttachmentCache()
  });

  const secondPlan = await planAttachmentReuse({
    includePageContext: true,
    includeScreenshot: true,
    pageSnapshot: { page: { title: "Demo" } },
    turnAttachments: { screenshotDataUrl: "data:image/png;base64,xyz" },
    attachmentCache: firstPlan.nextAttachmentCache
  });

  assert.equal(secondPlan.includePageContext, false);
  assert.equal(secondPlan.includeScreenshot, true);
  assert.equal(buildAttachmentReuseMessage(secondPlan), "检测到页面内容无变化，本轮复用上次页面内容。");
});
