"""Tests for statute chunker."""

from ars25.ingestion.chunker import chunk_statute, estimate_tokens
from ars25.models.statute import StatuteRecord


def _record() -> StatuteRecord:
    return StatuteRecord(
        chapter_number=4,
        chapter_title="DISSOLUTION",
        article_number=6,
        article_title="Custody",
        section="25-403",
        title="Best interests",
        url="https://example.com",
    )


def test_empty_text_returns_no_chunks():
    chunks = chunk_statute(_record(), "")
    assert chunks == []


def test_whitespace_only_returns_no_chunks():
    chunks = chunk_statute(_record(), "   \n\n  ")
    assert chunks == []


def test_short_text_single_chunk():
    text = "This is a short statute about child custody."
    chunks = chunk_statute(_record(), text)
    assert len(chunks) == 1
    assert chunks[0].section == "25-403"
    assert chunks[0].chunk_index == 0
    assert chunks[0].chunk_text == text


def test_long_text_splits_on_subsections():
    # Create text with subsection boundaries that exceeds 500 tokens
    parts = []
    for letter in "ABCDEFGHIJ":
        # ~80 words per subsection = ~104 tokens each
        words = f"\n{letter}. " + " ".join(f"word{i}" for i in range(80))
        parts.append(words)
    text = "Introduction paragraph.\n" + "".join(parts)

    chunks = chunk_statute(_record(), text)
    assert len(chunks) > 1
    # All chunks have correct metadata
    for c in chunks:
        assert c.section == "25-403"
        assert c.chapter_number == 4


def test_chunk_indices_sequential():
    parts = []
    for letter in "ABCDEFGHIJ":
        words = f"\n{letter}. " + " ".join(f"word{i}" for i in range(80))
        parts.append(words)
    text = "Intro.\n" + "".join(parts)

    chunks = chunk_statute(_record(), text)
    indices = [c.chunk_index for c in chunks]
    assert indices == list(range(len(chunks)))


def test_estimate_tokens():
    assert estimate_tokens("one two three") == int(3 * 1.3 + 0.5)
    assert estimate_tokens("") == 0
