# DO NOT EDIT — generated by _client_gen/convenience_emitter.py from convenience.json.
# Regenerate with: cd clients/v2 && python -c "from _client_gen.convenience_emitter import generate_convenience; generate_convenience()"

"""Spaces API namespace — generated from convenience.json."""

from __future__ import annotations

from typing import Any

from goodmem._api_base.spaces import SpacesAPIBase, AsyncSpacesAPIBase


# --- Convenience imports ---
from goodmem._transforms import apply_convenience_transforms
from goodmem._transforms import _transform_list_kwargs
from goodmem.models.chunking_configuration import ChunkingConfiguration
from goodmem.models.sort_order import SortOrder
from goodmem.models.space import Space
from goodmem.models.space_embedder_config import SpaceEmbedderConfig
from goodmem.pagination import AsyncPage, Page


class SpacesAPI(SpacesAPIBase):
    def create(self, *, name: str, space_embedders: list[SpaceEmbedderConfig], default_chunking_config: ChunkingConfiguration | None = {'recursive': {'chunkSize': 512, 'chunkOverlap': 64, 'keepStrategy': 'KEEP_END', 'lengthMeasurement': 'CHARACTER_COUNT'}}, labels: dict[str, str] | None = None, owner_id: str | None = None, public_read: bool | None = None, space_id: str | None = None) -> Space:
        """Create a new Space

        Creates a new space with the provided name, labels, and embedder configuration. A space is a container for organizing related memories. OWNER DEFAULTS: Owner defaults to authenticated user unless owner_id is provided (requires CREATE_SPACE_ANY if differs). EMBEDDER REQUIREMENTS: At least one embedder configuration must be specified. DUPLICATE DETECTION: Returns ALREADY_EXISTS if another space exists with identical {owner_id, name} (case-sensitive). Requires CREATE_SPACE_OWN permission (or CREATE_SPACE_ANY for admin users). This operation is NOT idempotent.

        Args:
            name (str): The desired name for the space. Must be unique within the user's scope.
            space_embedders (list[SpaceEmbedderConfig]): List of embedder configurations to associate with this space. At least one embedder configuration is required. Each specifies an embedder ID and a relative default retrieval weight used when no per-request overrides are provided.
            default_chunking_config (ChunkingConfiguration, optional, SDK default={"recursive":{"chunkSize":512,"chunkOverlap":64,"keepStrategy":"KEEP_END","lengthMeasurement":"CHARACTER_COUNT"}}): Default strategy to chunk any memory ingested into this space. Can be overriden by per-memory chunking strategy.
            labels (dict[str, str], optional): A set of key-value pairs to categorize or tag the space. Used for filtering and organizational purposes.
            owner_id (str, optional): Optional owner ID. If not provided, derived from the authentication context. Requires CREATE_SPACE_ANY permission if specified.
            public_read (bool, optional, server default=False): Indicates if the space and its memories can be read by unauthenticated users or users other than the owner. Defaults to false.
            space_id (str, optional): Optional client-provided UUID for idempotent creation. If not provided, server generates a new UUID. Returns ALREADY_EXISTS if ID is already in use.

        Returns:
            Space
        """
        _kw: dict[str, Any] = {"name": name, "space_embedders": space_embedders}
        if default_chunking_config is not None: _kw["default_chunking_config"] = default_chunking_config
        if labels is not None: _kw["labels"] = labels
        if owner_id is not None: _kw["owner_id"] = owner_id
        if public_read is not None: _kw["public_read"] = public_read
        if space_id is not None: _kw["space_id"] = space_id
        apply_convenience_transforms(("spaces", "create"), _kw)
        return super().create(**_kw)

    def list(self, *, label: dict[str, str] | None = None, name_filter: str | None = None, owner_id: str | None = None, sort_by: str | None = None, sort_order: SortOrder | None = None, page_size: int | None = None, max_items: int | None = None, next_token: str | None = None) -> Page[Space]:
        """List spaces

        Retrieves a list of spaces accessible to the caller, with optional filtering by owner, labels, and name. Results are paginated with a maximum number of spaces per response. LABEL FILTERS: Label filters accept either label.<key>=<value> or label[key]=value (for example, label.environment=production or label[environment]=production). PERMISSION-BASED FILTERING: With LIST_SPACE_ANY and owner_id omitted, returns all visible spaces; otherwise returns caller-owned spaces only. DEFAULT SORT: Results ordered by created_at DESCENDING unless specified otherwise. MAX_RESULTS CLAMPING: max_results defaults to 50 and is clamped to [1, 1000] range. Requires LIST_SPACE_OWN or LIST_SPACE_ANY permission.

        Args:
            label (dict[str, str], optional): Filter by label key-value pairs. Label filters accept either label.<key>=<value> or label[key]=value (for example, label.environment=production or label[environment]=production).
            name_filter (str, optional): Filter spaces by name using glob pattern matching.
            owner_id (str, optional): Filter spaces by owner ID. With LIST_SPACE_ANY permission and owner_id omitted, returns all visible spaces. Otherwise returns caller-owned spaces only. Specifying owner_id without LIST_SPACE_ANY returns PERMISSION_DENIED.
            sort_by (str, optional, server default='created_time'): Field to sort by: `'created_time'`, `'updated_time'`, or `'name'` (default: `'created_time'`). Unsupported values return INVALID_ARGUMENT.
            sort_order (SortOrder, optional, server default='DESCENDING'): Sort order (`ASCENDING` or `DESCENDING`, default: `DESCENDING`).
            page_size (int, optional): Number of results per page (defaults to 50, clamped to [1, 1000] by the server).
            max_items (int, optional): Maximum total number of items to return across all pages.
            next_token (str, optional): Opaque pagination token for the next page.

        Returns:
            Page[Space]
        """
        _kw: dict[str, Any] = {}
        if label is not None: _kw["label"] = label
        if name_filter is not None: _kw["name_filter"] = name_filter
        if owner_id is not None: _kw["owner_id"] = owner_id
        if sort_by is not None: _kw["sort_by"] = sort_by
        if sort_order is not None: _kw["sort_order"] = sort_order
        if page_size is not None: _kw["page_size"] = page_size
        if max_items is not None: _kw["max_items"] = max_items
        if next_token is not None: _kw["next_token"] = next_token
        max_items_val = _transform_list_kwargs(_kw)
        page = super().list(**_kw)
        if max_items_val is not None:
            page._max_items = max_items_val
            page.data = page.data[:max_items_val]
        return page



class AsyncSpacesAPI(AsyncSpacesAPIBase):
    async def create(self, *, name: str, space_embedders: list[SpaceEmbedderConfig], default_chunking_config: ChunkingConfiguration | None = {'recursive': {'chunkSize': 512, 'chunkOverlap': 64, 'keepStrategy': 'KEEP_END', 'lengthMeasurement': 'CHARACTER_COUNT'}}, labels: dict[str, str] | None = None, owner_id: str | None = None, public_read: bool | None = None, space_id: str | None = None) -> Space:
        """Create a new Space

        Creates a new space with the provided name, labels, and embedder configuration. A space is a container for organizing related memories. OWNER DEFAULTS: Owner defaults to authenticated user unless owner_id is provided (requires CREATE_SPACE_ANY if differs). EMBEDDER REQUIREMENTS: At least one embedder configuration must be specified. DUPLICATE DETECTION: Returns ALREADY_EXISTS if another space exists with identical {owner_id, name} (case-sensitive). Requires CREATE_SPACE_OWN permission (or CREATE_SPACE_ANY for admin users). This operation is NOT idempotent.

        Args:
            name (str): The desired name for the space. Must be unique within the user's scope.
            space_embedders (list[SpaceEmbedderConfig]): List of embedder configurations to associate with this space. At least one embedder configuration is required. Each specifies an embedder ID and a relative default retrieval weight used when no per-request overrides are provided.
            default_chunking_config (ChunkingConfiguration, optional, SDK default={"recursive":{"chunkSize":512,"chunkOverlap":64,"keepStrategy":"KEEP_END","lengthMeasurement":"CHARACTER_COUNT"}}): Default strategy to chunk any memory ingested into this space. Can be overriden by per-memory chunking strategy.
            labels (dict[str, str], optional): A set of key-value pairs to categorize or tag the space. Used for filtering and organizational purposes.
            owner_id (str, optional): Optional owner ID. If not provided, derived from the authentication context. Requires CREATE_SPACE_ANY permission if specified.
            public_read (bool, optional, server default=False): Indicates if the space and its memories can be read by unauthenticated users or users other than the owner. Defaults to false.
            space_id (str, optional): Optional client-provided UUID for idempotent creation. If not provided, server generates a new UUID. Returns ALREADY_EXISTS if ID is already in use.

        Returns:
            Space
        """
        _kw: dict[str, Any] = {"name": name, "space_embedders": space_embedders}
        if default_chunking_config is not None: _kw["default_chunking_config"] = default_chunking_config
        if labels is not None: _kw["labels"] = labels
        if owner_id is not None: _kw["owner_id"] = owner_id
        if public_read is not None: _kw["public_read"] = public_read
        if space_id is not None: _kw["space_id"] = space_id
        apply_convenience_transforms(("spaces", "create"), _kw)
        return await super().create(**_kw)

    async def list(self, *, label: dict[str, str] | None = None, name_filter: str | None = None, owner_id: str | None = None, sort_by: str | None = None, sort_order: SortOrder | None = None, page_size: int | None = None, max_items: int | None = None, next_token: str | None = None) -> AsyncPage[Space]:
        """List spaces

        Retrieves a list of spaces accessible to the caller, with optional filtering by owner, labels, and name. Results are paginated with a maximum number of spaces per response. LABEL FILTERS: Label filters accept either label.<key>=<value> or label[key]=value (for example, label.environment=production or label[environment]=production). PERMISSION-BASED FILTERING: With LIST_SPACE_ANY and owner_id omitted, returns all visible spaces; otherwise returns caller-owned spaces only. DEFAULT SORT: Results ordered by created_at DESCENDING unless specified otherwise. MAX_RESULTS CLAMPING: max_results defaults to 50 and is clamped to [1, 1000] range. Requires LIST_SPACE_OWN or LIST_SPACE_ANY permission.

        Args:
            label (dict[str, str], optional): Filter by label key-value pairs. Label filters accept either label.<key>=<value> or label[key]=value (for example, label.environment=production or label[environment]=production).
            name_filter (str, optional): Filter spaces by name using glob pattern matching.
            owner_id (str, optional): Filter spaces by owner ID. With LIST_SPACE_ANY permission and owner_id omitted, returns all visible spaces. Otherwise returns caller-owned spaces only. Specifying owner_id without LIST_SPACE_ANY returns PERMISSION_DENIED.
            sort_by (str, optional, server default='created_time'): Field to sort by: `'created_time'`, `'updated_time'`, or `'name'` (default: `'created_time'`). Unsupported values return INVALID_ARGUMENT.
            sort_order (SortOrder, optional, server default='DESCENDING'): Sort order (`ASCENDING` or `DESCENDING`, default: `DESCENDING`).
            page_size (int, optional): Number of results per page (defaults to 50, clamped to [1, 1000] by the server).
            max_items (int, optional): Maximum total number of items to return across all pages.
            next_token (str, optional): Opaque pagination token for the next page.

        Returns:
            AsyncPage[Space]
        """
        _kw: dict[str, Any] = {}
        if label is not None: _kw["label"] = label
        if name_filter is not None: _kw["name_filter"] = name_filter
        if owner_id is not None: _kw["owner_id"] = owner_id
        if sort_by is not None: _kw["sort_by"] = sort_by
        if sort_order is not None: _kw["sort_order"] = sort_order
        if page_size is not None: _kw["page_size"] = page_size
        if max_items is not None: _kw["max_items"] = max_items
        if next_token is not None: _kw["next_token"] = next_token
        max_items_val = _transform_list_kwargs(_kw)
        page = await super().list(**_kw)
        if max_items_val is not None:
            page._max_items = max_items_val
            page.data = page.data[:max_items_val]
        return page

