import assert from "node:assert/strict";
import test from "node:test";
import {
  classifyParagraph,
  contentFingerprint,
  detectPrimaryLanguage,
  splitReadableSegments,
} from "../../lib/domain/text.ts";

test("detects the dominant Chinese or English voice per segment", () => {
  assert.equal(detectPrimaryLanguage("这是中文正文 with API."), "zh-CN");
  assert.equal(detectPrimaryLanguage("This sentence mentions 中文 once."), "en-US");
  assert.equal(detectPrimaryLanguage("12345 — …"), "zh-CN");
});

test("splits mixed prose on natural punctuation and respects the TTS limit", () => {
  const longEnglish = `${"word ".repeat(80)}done.`;
  const segments = splitReadableSegments(`第一句。第二句！\n${longEnglish}`, 120);

  assert.deepEqual(segments.slice(0, 2).map((segment) => segment.text), ["第一句。", "第二句！"]);
  assert.ok(segments.every((segment) => segment.text.length <= 120));
  assert.equal(segments.at(-1).language, "en-US");
  assert.equal(segments.map((segment) => segment.text).join(" ").includes("done."), true);
});

test("marks complex formula and table-like rows as skipped while retaining prose", () => {
  assert.equal(classifyParagraph("The experiment produced a clear improvement."), "readable");
  assert.equal(classifyParagraph("E = mc² + ∑ᵢ₌₁ⁿ αᵢxᵢ / √(2πσ²)"), "formula");
  assert.equal(classifyParagraph("样本\t均值\t标准差\tP 值"), "table");
  assert.equal(classifyParagraph("A    12.4    3.1    0.002"), "table");
});

test("normalizes equivalent text to the same stable fingerprint", async () => {
  assert.equal(
    await contentFingerprint("  Hello\r\nworld  "),
    await contentFingerprint("Hello\nworld"),
  );
  assert.notEqual(
    await contentFingerprint("Hello world"),
    await contentFingerprint("Hello worlds"),
  );
});
