"""Tests for space convenience layer — default chunking config."""

import json

import httpx

from goodmem.registries.convenience import DEFAULT_CHUNKING_CONFIG, apply_convenience_transforms
from tests.conftest import SPACE_RESPONSE


def _apply(kwargs):
    apply_convenience_transforms(("spaces", "create"), kwargs)
    return kwargs


def test_default_chunking_applied_when_missing():
    kwargs = {"name": "Test Space"}
    result = _apply(kwargs)
    assert "default_chunking_config" in result
    assert result["default_chunking_config"] == DEFAULT_CHUNKING_CONFIG


def test_explicit_chunking_wins():
    custom_config = {"sentence": {"min_chunk_size": 100}}
    kwargs = {"name": "Test Space", "default_chunking_config": custom_config}
    result = _apply(kwargs)
    assert result["default_chunking_config"] == custom_config


def test_none_chunking_preserved():
    """Passing {"none": {}} should bypass the default."""
    kwargs = {"name": "Test Space", "default_chunking_config": {"none": {}}}
    result = _apply(kwargs)
    assert result["default_chunking_config"] == {"none": {}}


def test_default_chunking_structure():
    """Verify the default chunking config structure."""
    assert "recursive" in DEFAULT_CHUNKING_CONFIG
    recursive = DEFAULT_CHUNKING_CONFIG["recursive"]
    assert recursive["chunk_size"] == 512
    assert recursive["chunk_overlap"] == 64
    assert recursive["keep_strategy"] == "KEEP_END"
    assert recursive["length_measurement"] == "CHARACTER_COUNT"


def test_create_sends_default_chunking(mock_client_factory):
    captured = {}

    def handler(request: httpx.Request) -> httpx.Response:
        captured["body"] = json.loads(request.content)
        return httpx.Response(200, json=SPACE_RESPONSE)

    client = mock_client_factory(handler)
    client.spaces.create(name="Test Space")

    body = captured["body"]
    assert "defaultChunkingConfig" in body
    assert "recursive" in body["defaultChunkingConfig"]


def test_create_with_explicit_chunking(mock_client_factory):
    captured = {}

    def handler(request: httpx.Request) -> httpx.Response:
        captured["body"] = json.loads(request.content)
        return httpx.Response(200, json=SPACE_RESPONSE)

    client = mock_client_factory(handler)
    client.spaces.create(
        name="Test Space",
        default_chunking_config={
            "recursive": {
                "chunk_size": 1024,
                "chunk_overlap": 128,
                "keep_strategy": "KEEP_END",
                "length_measurement": "CHARACTER_COUNT",
            }
        },
    )

    body = captured["body"]
    assert body["defaultChunkingConfig"]["recursive"]["chunkSize"] == 1024
