import assert from "node:assert/strict";
import test from "node:test";
import { ocrCheckpointsToParsedBook } from "../../lib/client/ocr/to-parsed-book.ts";

const checkpoint = (pageNumber, blocks) => ({
  bookId: "book-1",
  sourceFingerprint: "source-1",
  pageNumber,
  width: 700,
  height: 900,
  blocks,
  completedAt: "2026-08-12T02:00:00.000Z",
});

const block = (text, y, overrides = {}) => ({
  text,
  x: 60,
  y,
  width: 500,
  height: 28,
  confidence: 96,
  ...overrides,
});

test("turns OCR checkpoints into stable ten-page proofreading chapters", () => {
  const parsed = ocrCheckpointsToParsedBook({
    checkpoints: [
      checkpoint(1, [block("第一句。", 100), block("E = mc² + ∑ αᵢ", 200)]),
      checkpoint(2, [block("Second sentence.", 100)]),
      checkpoint(11, [block("第十一页。", 100)]),
    ],
    pageCount: 18,
    title: "扫描书",
    author: "作者",
  });

  assert.equal(parsed.format, "pdf");
  assert.equal(parsed.requiresOcr, true);
  assert.deepEqual(parsed.chapters.map(({ id, title, pageStart, pageEnd }) => ({ id, title, pageStart, pageEnd })), [
    { id: "ocr-pages-1-10", title: "第 1–10 页", pageStart: 1, pageEnd: 2 },
    { id: "ocr-pages-11-18", title: "第 11–18 页", pageStart: 11, pageEnd: 11 },
  ]);
  assert.equal(parsed.chapters[0].blocks[0].id, "ocr-page-1-block-1");
  assert.equal(parsed.chapters[0].blocks[0].included, true);
  assert.equal(parsed.chapters[0].blocks[1].kind, "formula");
  assert.equal(parsed.chapters[0].blocks[1].included, false);
  assert.equal(parsed.chapters[0].blocks[2].pageNumber, 2);
});

test("rejects impossible page counts and ignores duplicate checkpoint pages", () => {
  assert.throws(() => ocrCheckpointsToParsedBook({
    checkpoints: [],
    pageCount: 0,
    title: "书",
    author: "",
  }), /页数/);

  const parsed = ocrCheckpointsToParsedBook({
    checkpoints: [checkpoint(1, [block("首次。", 100)]), checkpoint(1, [block("重复。", 100)])],
    pageCount: 2,
    title: "书",
    author: "",
  });
  assert.deepEqual(parsed.chapters[0].blocks.map(({ text }) => text), ["首次。"]);
});
