"""Unit tests for the knowledge plane embedding slice."""

from __future__ import annotations

from pathlib import Path

from cyberbrain26.knowledge_plane.chunker import TextChunker
from cyberbrain26.knowledge_plane.embedding_config import EmbeddingConfig
from cyberbrain26.knowledge_plane.vector_store import KnowledgeVectorStore, VectorDocument


def test_embedding_config_defaults() -> None:
    config = EmbeddingConfig()
    assert config.vector_dim == 1024
    assert config.max_context == 32_000
    assert config.model == "qwen3-embedding:0.6b"
    assert config.chunk_size_tokens == 512
    assert config.chunk_overlap_tokens == 100


def test_vector_store_roundtrip(tmp_path: Path) -> None:
    config = EmbeddingConfig(lancedb_directory=tmp_path / "lancedb")
    store = KnowledgeVectorStore(config)
    doc = VectorDocument(
        id="test-1",
        vector=[0.1] * config.vector_dim,
        text="Hello world",
        source_id="src",
        path="/tmp/test.txt",
        mtime=0.0,
        sha256="abc123",
        chunk_index=0,
    )
    store.add_documents([doc])
    assert store.count() == 1
    results = store.search([0.1] * config.vector_dim, limit=1)
    assert len(results) == 1
    assert results[0]["text"] == "Hello world"


def test_chunker_splits_text(tmp_path: Path) -> None:
    file_path = tmp_path / "test.txt"
    file_path.write_text("word " * 20, encoding="utf-8")
    config = EmbeddingConfig(chunk_size_tokens=5, chunk_overlap_tokens=2)
    chunker = TextChunker(config)
    chunks = chunker.chunk_file(file_path)
    assert len(chunks) > 1
    assert all(isinstance(c.text, str) for c in chunks)
    assert all(c.source_path == str(file_path) for c in chunks)
    assert all(c.chunk_index == i for i, c in enumerate(chunks))


def test_chunker_from_memory() -> None:
    config = EmbeddingConfig(chunk_size_tokens=4, chunk_overlap_tokens=1)
    chunker = TextChunker(config)
    chunks = chunker.chunk_text("one two three four five six", source_path="<memory>")
    assert len(chunks) > 1
    assert chunks[0].text == "one two three four"
    assert chunks[1].text == "four five six"


def test_chunker_overlap_does_not_exceed_size() -> None:
    config = EmbeddingConfig(chunk_size_tokens=5, chunk_overlap_tokens=10)
    chunker = TextChunker(config)
    chunks = chunker.chunk_text("a b c d e f g h i j", source_path="<memory>")
    assert len(chunks) == 1
