import { describe, expect, it } from 'vitest';

import { extractReadyParagraphs, getUnsentFinalChunks } from './text-chunking.js';

describe('extractReadyParagraphs', () => {
  it('keeps partial prose buffered by default', () => {
    expect(extractReadyParagraphs('Boa pergunta, deixa-me verificar!', 2000)).toEqual({
      ready: [],
      tail: 'Boa pergunta, deixa-me verificar!',
    });
  });

  it('force-flushes partial prose when requested', () => {
    expect(
      extractReadyParagraphs('Boa pergunta, deixa-me verificar!', 2000, {
        forceFlushTail: true,
      }),
    ).toEqual({
      ready: ['Boa pergunta, deixa-me verificar!'],
      tail: '',
    });
  });

  it('force-flushes complete paragraphs and the remaining tail together', () => {
    expect(
      extractReadyParagraphs('Primeiro paragrafo.\n\nSegundo sem quebra final.', 2000, {
        forceFlushTail: true,
      }),
    ).toEqual({
      ready: ['Primeiro paragrafo.', 'Segundo sem quebra final.'],
      tail: '',
    });
  });
});

describe('getUnsentFinalChunks', () => {
  it('drops streamed prefix chunks from the final result', () => {
    const finalText = "All set! I'm Kai, and I'll keep things casual between us.\n\nSo what are you working on?";
    expect(
      getUnsentFinalChunks(
        finalText,
        ["All set! I'm Kai, and I'll keep things casual between us."],
        2000,
      ),
    ).toEqual(['So what are you working on?']);
  });

  it('keeps the full final result when streamed chunks do not match the prefix', () => {
    const finalText = 'First paragraph.\n\nSecond paragraph.';
    expect(
      getUnsentFinalChunks(finalText, ['Different paragraph.'], 2000),
    ).toEqual(['First paragraph.', 'Second paragraph.']);
  });
});
