"""SentenceRegrouper: streamed token deltas -> complete sentences."""
import brain


def _feed(regrouper, deltas):
    out = []
    for d in deltas:
        out.extend(regrouper.push(d))
    tail = regrouper.flush()
    if tail:
        out.append(tail)
    return out


def test_splits_on_sentence_punctuation():
    r = brain.SentenceRegrouper()
    got = _feed(r, ["Hello, sir. ", "How are you today? ", "All good."])
    assert got == ["Hello, sir.", "How are you today?", "All good."]


def test_streams_first_sentence_before_the_rest_arrives():
    r = brain.SentenceRegrouper()
    # first push completes exactly one sentence; the rest is still buffered
    first = r.push("Right away, sir. And then")
    assert first == ["Right away, sir."]
    assert r.push(" I will do it.") == []  # no terminal punct+space yet
    assert r.flush() == "And then I will do it."


def test_hard_flush_on_runaway_without_punctuation():
    r = brain.SentenceRegrouper()
    long_run = "word " * 60  # ~300 chars, no sentence end
    out = r.push(long_run)
    assert out, "a long punctuation-less run must be force-flushed"
    assert all(len(s) <= brain._MAX_CHUNK for s in out)


def test_arabic_sentence_end():
    r = brain.SentenceRegrouper()
    assert r.push("ما اسمك؟ ") == ["ما اسمك؟"]


def test_newline_flushes():
    r = brain.SentenceRegrouper()
    assert r.push("Line one\nLine two.") == ["Line one"]


def test_emotion_tag_survives_cleaning():
    r = brain.SentenceRegrouper()
    # markdown stripped, but the [warm] emotion tag must be preserved for TTS
    got = r.push("[warm] *Well* done, sir. ")
    assert got == ["[warm] Well done, sir."]


def test_clean_for_tts_strips_markdown_keeps_brackets():
    assert brain.clean_for_tts("**bold** and `code`") == "bold and code"
    assert brain.clean_for_tts("[excited] go!") == "[excited] go!"
