import { describe, expect, it } from "vitest";
import { detailFingerprint, fingerprintDataUrl, isRepeatedProcessedPageFingerprint, screenFingerprint } from "./autoScanLoop";

describe("autoScanLoop fingerprints", () => {
  it("distinguishes captures that share the same prefix but differ later", () => {
    const sharedPrefix = "data:image/png;base64," + "A".repeat(180);
    const left = sharedPrefix + "LEFT-" + "B".repeat(600);
    const right = sharedPrefix + "RIGHT-" + "C".repeat(600);

    expect(fingerprintDataUrl(left)).not.toBe(fingerprintDataUrl(right));
  });

  it("stays stable for the same capture string", () => {
    const dataUrl = "data:image/png;base64," + "Q".repeat(2048);
    expect(fingerprintDataUrl(dataUrl)).toBe(fingerprintDataUrl(dataUrl));
  });

  it("uses the detail preview for detail-change verification instead of the full frame", () => {
    const captureA = {
      detailDataUrl: "data:image/png;base64," + "DETAIL-A".repeat(64),
      dataUrl: "data:image/png;base64," + "FULL-A".repeat(256),
    } as const;
    const captureB = {
      detailDataUrl: captureA.detailDataUrl,
      dataUrl: "data:image/png;base64," + "FULL-B".repeat(256),
    } as const;

    expect(detailFingerprint(captureA as never)).toBe(detailFingerprint(captureB as never));
  });

  it("uses the inventory preview for scroll verification when available", () => {
    const captureA = {
      inventoryDataUrl: "data:image/png;base64," + "GRID-A".repeat(64),
      dataUrl: "data:image/png;base64," + "FRAME-A".repeat(256),
    } as const;
    const captureB = {
      inventoryDataUrl: "data:image/png;base64," + "GRID-B".repeat(64),
      dataUrl: captureA.dataUrl,
    } as const;

    expect(screenFingerprint(captureA as never)).not.toBe(screenFingerprint(captureB as never));
  });

  it("treats repeated page fingerprints as a loop only after page one", () => {
    const seen = new Set(["abc"]);
    expect(isRepeatedProcessedPageFingerprint("abc", seen, 1)).toBe(false);
    expect(isRepeatedProcessedPageFingerprint("abc", seen, 2)).toBe(true);
    expect(isRepeatedProcessedPageFingerprint("", seen, 3)).toBe(false);
  });
});
