import assert from "node:assert/strict";
import test from "node:test";
import { prepareChaptersForSync } from "../../lib/client/import/prepare.ts";

test("prefixes chapter identity with the book and prepares included and skipped segments", async () => {
  const prepared = await prepareChaptersForSync("book-9", {
    format: "pdf",
    title: "Book",
    author: "Author",
    requiresOcr: false,
    chapters: [{
      id: "chapter-1",
      title: "第一章",
      sourceHref: "pages:1-1",
      pageStart: 1,
      pageEnd: 1,
      blocks: [
        { id: "pdf-1-0", text: "正文。", kind: "prose", included: true, pageNumber: 1 },
        { id: "pdf-1-1", text: "E = mc² + ∑ αᵢ", kind: "formula", included: false, pageNumber: 1, warning: "formula" },
      ],
    }],
  });

  assert.equal(prepared[0].id, "book-9:chapter:1");
  assert.equal(prepared[0].segments.length, 2);
  assert.equal(prepared[0].segments[0].included, true);
  assert.equal(prepared[0].segments[0].sourceKind, "pdf_text");
  assert.equal(prepared[0].segments[1].included, false);
  assert.equal(prepared[0].segments[1].warning, "formula");
  assert.match(prepared[0].segments[0].contentHash, /^[a-f0-9]{64}$/);
});

test("marks scanned-PDF segments as OCR and sends at most ten chapters per API batch", async () => {
  const chapters = Array.from({ length: 23 }, (_, index) => ({
    id: `local-${index}`,
    title: `第 ${index + 1} 章`,
    sourceHref: `pages:${index + 1}-${index + 1}`,
    pageStart: index + 1,
    pageEnd: index + 1,
    blocks: [{ id: `ocr-${index}`, text: "OCR 正文。", kind: "prose", included: true, confidence: 88 }],
  }));
  const prepared = await prepareChaptersForSync("book-1", {
    format: "pdf",
    title: "Scan",
    author: "Author",
    requiresOcr: true,
    chapters,
  });
  assert.equal(prepared[0].segments[0].sourceKind, "ocr");

  const { chapterBatches } = await import("../../lib/client/import/prepare.ts");
  assert.deepEqual(chapterBatches(prepared).map((batch) => batch.length), [10, 10, 3]);
});
