"""Spaces API namespace."""

from __future__ import annotations

from typing import Any

from goodmem._base import AsyncCRUDNamespace, CRUDNamespace
from goodmem._generated.models.list_spaces_response import ListSpacesResponse
from goodmem._generated.models.space import Space
from goodmem._generated.models.space_creation_request import SpaceCreationRequest
from goodmem._generated.models.update_space_request import UpdateSpaceRequest

# Default chunking config applied when none is provided
_DEFAULT_CHUNKING_CONFIG = {
    "recursive": {
        "chunk_size": 512,
        "chunk_overlap": 64,
        "keep_strategy": "KEEP_END",
        "length_measurement": "CHARACTER_COUNT",
    }
}


def _apply_space_defaults(kwargs: dict[str, Any]) -> dict[str, Any]:
    """Apply default chunking config when not provided."""
    if "default_chunking_config" not in kwargs and "chunking_config" not in kwargs:
        kwargs["default_chunking_config"] = _DEFAULT_CHUNKING_CONFIG
    return kwargs


class SpacesAPI(CRUDNamespace):
    _base_path = "/v1/spaces"
    _create_model = SpaceCreationRequest
    _update_model = UpdateSpaceRequest
    _response_model = Space
    _list_response_model = ListSpacesResponse
    _list_items_field = "spaces"

    def create(self, **kwargs: Any) -> Space:
        """Create a space. Default chunking config (recursive, 512 chars, 64 overlap) applied automatically."""
        kwargs = _apply_space_defaults(kwargs)
        return super().create(**kwargs)


class AsyncSpacesAPI(AsyncCRUDNamespace):
    _base_path = "/v1/spaces"
    _create_model = SpaceCreationRequest
    _update_model = UpdateSpaceRequest
    _response_model = Space
    _list_response_model = ListSpacesResponse
    _list_items_field = "spaces"

    async def create(self, **kwargs: Any) -> Space:
        kwargs = _apply_space_defaults(kwargs)
        return await super().create(**kwargs)
