"""Tests for _chunker module."""

from __future__ import annotations

import pytest

from murmr._chunker import split_into_chunks


class TestSplitIntoChunks:
    def test_empty_text(self) -> None:
        assert split_into_chunks("") == []

    def test_whitespace_only(self) -> None:
        assert split_into_chunks("   ") == []

    def test_short_text_single_chunk(self) -> None:
        text = "Hello, world!"
        assert split_into_chunks(text) == [text]

    def test_text_at_limit(self) -> None:
        text = "a" * 3500
        assert split_into_chunks(text) == [text]

    def test_splits_at_sentence_boundary(self) -> None:
        # Build two sentences that each fit within max_chars individually
        # but together exceed the limit
        s1 = "First sentence " + "a" * 2000 + "."
        s2 = "Second sentence " + "b" * 2000 + "."
        text = f"{s1} {s2}"
        chunks = split_into_chunks(text)
        assert len(chunks) == 2
        assert chunks[0].startswith("First")
        assert chunks[1].startswith("Second")

    def test_respects_max_chars_param(self) -> None:
        text = "Short. Also short. Tiny."
        chunks = split_into_chunks(text, max_chars=200)
        assert all(len(c) <= 200 for c in chunks)

    def test_splits_long_sentence_at_clauses(self) -> None:
        # Single sentence with clause boundaries, longer than max_chars
        clause = "word " * 30  # ~150 chars per clause
        sentence = ", ".join([clause.strip()] * 30)  # ~4500 chars, single sentence
        chunks = split_into_chunks(sentence, max_chars=500)
        assert len(chunks) > 1
        assert all(len(c) <= 500 for c in chunks)

    def test_splits_at_words_as_last_resort(self) -> None:
        # Single long word-like string — no punctuation
        text = " ".join(["word"] * 1000)  # ~5000 chars, no sentence/clause breaks
        chunks = split_into_chunks(text, max_chars=200)
        assert len(chunks) > 1
        assert all(len(c) <= 200 for c in chunks)

    def test_preserves_all_text(self) -> None:
        text = "First sentence. Second sentence. Third sentence. Fourth sentence."
        chunks = split_into_chunks(text, max_chars=200)
        rejoined = " ".join(chunks)
        # All words should be present
        for word in text.split():
            assert word in rejoined

    def test_min_max_chars_validation(self) -> None:
        with pytest.raises(ValueError, match="at least 100"):
            split_into_chunks("hello", max_chars=50)

    def test_max_chars_upper_bound(self) -> None:
        with pytest.raises(ValueError, match="at most 4096"):
            split_into_chunks("hello", max_chars=5000)

    def test_cjk_sentence_splitting(self) -> None:
        # Chinese sentence-ending punctuation
        text = "你好世界。" * 500 + "再见世界。" * 500
        chunks = split_into_chunks(text, max_chars=3500)
        assert len(chunks) >= 2
        assert all(len(c) <= 3500 for c in chunks)
