import assert from "node:assert/strict";
import test from "node:test";
import {
  cleanOcrPages,
  orderPageBlocks,
} from "../../lib/client/ocr/layout.ts";

const block = (text, x, y, width = 180, confidence = 95) => ({
  text,
  x,
  y,
  width,
  height: 24,
  confidence,
});

test("orders a single-column page from top to bottom", () => {
  const ordered = orderPageBlocks([
    block("第三段", 60, 300),
    block("第一段", 55, 100),
    block("第二段", 58, 200),
  ], 600);
  assert.deepEqual(ordered.map(({ text }) => text), ["第一段", "第二段", "第三段"]);
  assert.equal(ordered.layout, "single");
});

test("detects two columns and reads the left column before the right", () => {
  const ordered = orderPageBlocks([
    block("右二", 360, 220),
    block("左二", 50, 230),
    block("右一", 360, 100),
    block("左一", 50, 90),
  ], 700);
  assert.deepEqual(ordered.map(({ text }) => text), ["左一", "左二", "右一", "右二"]);
  assert.equal(ordered.layout, "two-column");
});

test("flags repeated headers, page numbers, low confidence, formulas, and tables", () => {
  const pages = [1, 2, 3].map((pageNumber) => ({
    pageNumber,
    width: 600,
    height: 800,
    blocks: [
      block("Journal of Tests", 100, 16, 300),
      block(`正文第 ${pageNumber} 页。`, 80, 150, 420),
      block("E = mc² + ∑ αᵢ / √2", 80, 240, 420),
      block("组别\t均值\tP 值", 80, 310, 420),
      block("识别可能有错", 80, 380, 420, 42),
      block(String(pageNumber), 290, 770, 20),
    ],
  }));

  const cleaned = cleanOcrPages(pages);
  const first = cleaned[0].blocks;
  assert.equal(first.find((item) => item.text === "Journal of Tests").included, false);
  assert.equal(first.find((item) => item.text === "Journal of Tests").warning, "repeated-header-footer");
  assert.equal(first.find((item) => item.text === "E = mc² + ∑ αᵢ / √2").warning, "formula");
  assert.equal(first.find((item) => item.text.includes("组别")).warning, "table");
  assert.equal(first.find((item) => item.text === "识别可能有错").warning, "low-confidence");
  assert.equal(first.find((item) => item.text === "正文第 1 页。").included, true);
  assert.equal(first.find((item) => item.text === "1").warning, "page-number");
});
