import pytest

from matheel import chunking
from matheel.chunking import available_chunking_methods, chunk_text, chunker_parameter_names, parse_chunker_options


def test_public_chunking_methods_are_chonkie_first():
    assert available_chunking_methods() == (
        "none",
        "code",
        "chonkie_token",
        "chonkie_sentence",
        "chonkie_recursive",
        "chonkie_fast",
    )


def test_legacy_line_chunking_is_removed():
    text = "a\nb\nc\nd"

    with pytest.raises(ValueError):
        chunk_text(text, method="lines", chunk_size=2, chunk_overlap=1)


def test_legacy_character_chunking_is_removed():
    with pytest.raises(ValueError):
        chunk_text("abcdef", method="characters", chunk_size=3, chunk_overlap=1)


def test_code_chunker_requires_chonkie_when_unavailable(monkeypatch):
    monkeypatch.setattr(chunking, "_load_chonkie_class", lambda class_name: None)

    with pytest.raises(ImportError):
        chunk_text(
            "line1\nline2\nline3",
            method="code",
            chunk_size=2,
            chunk_overlap=1,
            chunk_language="python",
            chunker_options=("include_line_numbers=true",),
        )


def test_parse_chunker_options_supports_strings():
    assert parse_chunker_options("flag=true,count=2,name=demo") == {
        "flag": True,
        "count": 2,
        "name": "demo",
    }


def test_chunker_parameter_names_exposes_native_chonkie_methods():
    assert chunker_parameter_names("code") == ("chunk_size", "language", "include_nodes", "tokenizer")
    assert chunker_parameter_names("codechunker") == ()
    assert chunker_parameter_names("chonkie_code") == ()
    assert chunker_parameter_names("chonkie_token") == ("chunk_size", "chunk_overlap", "tokenizer")
    assert chunker_parameter_names("chonkie_fast") == (
        "chunk_size",
        "delimiters",
        "pattern",
        "prefix",
        "consecutive",
        "forward_fallback",
    )


def test_native_chonkie_chunkers_work_when_installed():
    pytest.importorskip("chonkie")

    text = "def add(a, b):\n    total = a + b\n    return total\n\nclass Value:\n    pass\n"

    code_chunks = chunk_text(text, method="code", chunk_size=64, chunk_language="python")
    fast_chunks = chunk_text(text, method="chonkie_fast", chunk_size=64)

    assert len(code_chunks) >= 1
    assert len(fast_chunks) >= 1
    assert "def add" in code_chunks[0]
