# DO NOT EDIT — generated by _sdk_gen/ from the OpenAPI spec.
# Regenerate with: ./generate.sh
from __future__ import annotations

from typing import Any

from goodmem._base import AsyncCRUDNamespace, CRUDNamespace
from goodmem._base import _op_meta, _expand_label_filters
from goodmem._base import _op_meta, _prepare_create_payload
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
from goodmem.errors import raise_for_status
from goodmem.pagination import AsyncPaginator, Paginator


class SpacesAPIBase(CRUDNamespace):
    """Spaces API — auto-generated structural base.

    Auto-generated structural base. Do not edit.
    Override in goodmem/api/spaces.py to add domain-specific logic.
    """

    _base_path = "/v1/spaces"
    _create_model = SpaceCreationRequest
    _update_model = UpdateSpaceRequest
    _response_model = Space
    _list_response_model = ListSpacesResponse
    _list_items_field = "spaces"
    _rest_metadata: dict = {'create': {'http_method': 'POST', 'path': '/v1/spaces', 'response': 'Space', 'body_model': 'SpaceCreationRequest', 'body_expr': 'SpaceCreationRequest(**kwargs)', 'body_kind': 'json', 'body_kinds': ['application/json']}, 'get': {'http_method': 'GET', 'path': '/v1/spaces/{id}', 'response': 'Space', 'query_params': ['id']}, 'list': {'http_method': 'GET', 'path': '/v1/spaces', 'response': 'ListSpacesResponse', 'query_params': ['owner_id', 'name_filter', 'max_results', 'next_token', 'sort_by', 'sort_order', 'label.*'], 'auto_next_token': True, 'supports_label_wildcard': True}, 'update': {'http_method': 'PUT', 'path': '/v1/spaces/{id}', 'response': 'Space', 'query_params': ['id'], 'body_model': 'UpdateSpaceRequest', 'body_expr': 'UpdateSpaceRequest(**kwargs)', 'body_kind': 'json', 'body_kinds': ['application/json']}, 'delete': {'http_method': 'DELETE', 'path': '/v1/spaces/{id}', 'response': 'None', 'query_params': ['id']}}

    def create(self, **kwargs: Any) -> Any:
        """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 DEFAULTS: If no embedders are specified, a system-default embedder is attached. 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 (string): The desired name for the space. Must be unique within the user's scope.
            labels (object, optional): A set of key-value pairs to categorize or tag the space. Used for filtering and organizational purposes.
            space_embedders (array, optional): List of embedder configurations to associate with this space. Each specifies an embedder ID and a relative default retrieval weight used when no per-request overrides are provided.
            public_read (boolean, optional): Indicates if the space and its memories can be read by unauthenticated users or users other than the owner. Defaults to false.
            owner_id (string, optional): Optional owner ID. If not provided, derived from the authentication context. Requires CREATE_SPACE_ANY permission if specified.
            default_chunking_config (ChunkingConfiguration): Default chunking strategy for memories in this space
            space_id (string, 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
        """
        op = _op_meta(self, 'create')
        json_payload, data_payload, files_payload = _prepare_create_payload(
            create_model=self._create_model, op=op, kwargs=dict(kwargs),
        )
        resp = self._http.post(
            self._base_path,
            json=json_payload,
            data=data_payload,
            files=files_payload,
            headers=self._headers,
        )
        return self._handle_response(resp, self._create_response_model or self._response_model)

    def list(self, *, labels: dict[str, str] | None = None, **kwargs: Any) -> Any:
        """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. 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:
            owner_id (string, 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.
            name_filter (string, optional): Filter spaces by name using glob pattern matching
            max_results (integer, optional): Maximum number of results to return in a single page (defaults to 50, clamped to [1, 1000])
            next_token (string, optional): Pagination token for retrieving the next set of results
            sort_by (string, optional): Field to sort by: 'created_at' or 'name' (default: 'created_at'). Unsupported values return INVALID_ARGUMENT.
            sort_order (SortOrder, optional): Sort order (ASCENDING or DESCENDING, default: DESCENDING)
            label.* (string, optional): Filter by label value. Multiple label filters can be specified (e.g., ?label.project=AI&label.team=NLP)

        Returns:
            ListSpacesResponse
        """
        op = _op_meta(self, 'list')
        params = _expand_label_filters(op=op, labels=labels, params=dict(kwargs))
        return Paginator(
            fetch_fn=lambda token: self._http.get(
                self._base_path,
                params={**params, 'nextToken': token} if token else params or None,
                headers=self._headers,
            ),
            response_model=self._list_response_model,
            items_field=self._list_items_field,
        )

    def get(self, *, id: str) -> Any:
        """Get a space by ID

        Retrieves a specific space by its unique identifier. Returns the complete space information, including name, labels, embedder configuration, and metadata. PUBLIC SPACE ACCESS: When public_read=true, any authenticated user can retrieve the space metadata, bypassing ownership checks. Otherwise, requires ownership or DISPLAY_SPACE_ANY permission. Requires DISPLAY_SPACE_OWN permission for owned spaces (or DISPLAY_SPACE_ANY for admin users to view any space). This is a read-only operation safe to retry.

        Args:
            id (string): The unique identifier of the space to retrieve

        Returns:
            Space
        """
        resp = self._http.get(f"{self._base_path}/{id}", headers=self._headers)
        return self._handle_response(resp, self._response_model)

    def update(self, *, id: str, request: UpdateSpaceRequest | dict) -> Any:
        """Update a space

        Updates an existing space with new values for the specified fields. Only name, public_read, and labels can be updated. Fields not included in the request remain unchanged. IMMUTABLE FIELDS: space_embedders, default_chunking_config, and owner_id cannot be modified after creation. NAME UNIQUENESS: Name must be unique per owner - returns ALREADY_EXISTS if name conflicts with existing space. Requires UPDATE_SPACE_OWN permission for spaces you own (or UPDATE_SPACE_ANY for admin users). This operation is idempotent.

        Args:
            id (str): The unique identifier of the resource to update.
            request (UpdateSpaceRequest | dict): The update payload. Accepts a UpdateSpaceRequest instance or a plain dict with the same fields. Only specified fields will be modified.

        Returns:
            Space
        """
        if isinstance(request, dict):
            request = UpdateSpaceRequest.model_validate(request)
        resp = self._http.put(
            f"{self._base_path}/{id}",
            json=request.model_dump(by_alias=True, exclude_unset=True),
            headers=self._headers,
        )
        return self._handle_response(resp, self._response_model)

    def delete(self, *, id: str) -> None:
        """Delete a space

        Permanently deletes a space and all associated content. This operation cannot be undone. CASCADE DELETION: Removes the space record and cascades deletion to associated memories, chunks, and embedder associations. Requires DELETE_SPACE_OWN permission for spaces you own (or DELETE_SPACE_ANY for admin users). This operation is safe to retry - may return NOT_FOUND if already deleted.

        Args:
            id (string): The unique identifier of the space to delete
        """
        resp = self._http.delete(f"{self._base_path}/{id}", headers=self._headers)
        raise_for_status(resp)


class AsyncSpacesAPIBase(AsyncCRUDNamespace):
    """Async Spaces API — auto-generated structural base.

    Auto-generated structural base. Do not edit.
    Override in goodmem/api/spaces.py to add domain-specific logic.
    """

    _base_path = "/v1/spaces"
    _create_model = SpaceCreationRequest
    _update_model = UpdateSpaceRequest
    _response_model = Space
    _list_response_model = ListSpacesResponse
    _list_items_field = "spaces"
    _rest_metadata: dict = {'create': {'http_method': 'POST', 'path': '/v1/spaces', 'response': 'Space', 'body_model': 'SpaceCreationRequest', 'body_expr': 'SpaceCreationRequest(**kwargs)', 'body_kind': 'json', 'body_kinds': ['application/json']}, 'get': {'http_method': 'GET', 'path': '/v1/spaces/{id}', 'response': 'Space', 'query_params': ['id']}, 'list': {'http_method': 'GET', 'path': '/v1/spaces', 'response': 'ListSpacesResponse', 'query_params': ['owner_id', 'name_filter', 'max_results', 'next_token', 'sort_by', 'sort_order', 'label.*'], 'auto_next_token': True, 'supports_label_wildcard': True}, 'update': {'http_method': 'PUT', 'path': '/v1/spaces/{id}', 'response': 'Space', 'query_params': ['id'], 'body_model': 'UpdateSpaceRequest', 'body_expr': 'UpdateSpaceRequest(**kwargs)', 'body_kind': 'json', 'body_kinds': ['application/json']}, 'delete': {'http_method': 'DELETE', 'path': '/v1/spaces/{id}', 'response': 'None', 'query_params': ['id']}}

    async def create(self, **kwargs: Any) -> Any:
        """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 DEFAULTS: If no embedders are specified, a system-default embedder is attached. 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 (string): The desired name for the space. Must be unique within the user's scope.
            labels (object, optional): A set of key-value pairs to categorize or tag the space. Used for filtering and organizational purposes.
            space_embedders (array, optional): List of embedder configurations to associate with this space. Each specifies an embedder ID and a relative default retrieval weight used when no per-request overrides are provided.
            public_read (boolean, optional): Indicates if the space and its memories can be read by unauthenticated users or users other than the owner. Defaults to false.
            owner_id (string, optional): Optional owner ID. If not provided, derived from the authentication context. Requires CREATE_SPACE_ANY permission if specified.
            default_chunking_config (ChunkingConfiguration): Default chunking strategy for memories in this space
            space_id (string, 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
        """
        op = _op_meta(self, 'create')
        json_payload, data_payload, files_payload = _prepare_create_payload(
            create_model=self._create_model, op=op, kwargs=dict(kwargs),
        )
        resp = await self._http.post(
            self._base_path,
            json=json_payload,
            data=data_payload,
            files=files_payload,
            headers=self._headers,
        )
        return self._handle_response(resp, self._create_response_model or self._response_model)

    async def list(self, *, labels: dict[str, str] | None = None, **kwargs: Any) -> Any:
        """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. 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:
            owner_id (string, 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.
            name_filter (string, optional): Filter spaces by name using glob pattern matching
            max_results (integer, optional): Maximum number of results to return in a single page (defaults to 50, clamped to [1, 1000])
            next_token (string, optional): Pagination token for retrieving the next set of results
            sort_by (string, optional): Field to sort by: 'created_at' or 'name' (default: 'created_at'). Unsupported values return INVALID_ARGUMENT.
            sort_order (SortOrder, optional): Sort order (ASCENDING or DESCENDING, default: DESCENDING)
            label.* (string, optional): Filter by label value. Multiple label filters can be specified (e.g., ?label.project=AI&label.team=NLP)

        Returns:
            ListSpacesResponse
        """
        op = _op_meta(self, 'list')
        params = _expand_label_filters(op=op, labels=labels, params=dict(kwargs))
        return AsyncPaginator(
            fetch_fn=lambda token: self._http.get(
                self._base_path,
                params={**params, 'nextToken': token} if token else params or None,
                headers=self._headers,
            ),
            response_model=self._list_response_model,
            items_field=self._list_items_field,
        )

    async def get(self, *, id: str) -> Any:
        """Get a space by ID

        Retrieves a specific space by its unique identifier. Returns the complete space information, including name, labels, embedder configuration, and metadata. PUBLIC SPACE ACCESS: When public_read=true, any authenticated user can retrieve the space metadata, bypassing ownership checks. Otherwise, requires ownership or DISPLAY_SPACE_ANY permission. Requires DISPLAY_SPACE_OWN permission for owned spaces (or DISPLAY_SPACE_ANY for admin users to view any space). This is a read-only operation safe to retry.

        Args:
            id (string): The unique identifier of the space to retrieve

        Returns:
            Space
        """
        resp = await self._http.get(f"{self._base_path}/{id}", headers=self._headers)
        return self._handle_response(resp, self._response_model)

    async def update(self, *, id: str, request: UpdateSpaceRequest | dict) -> Any:
        """Update a space

        Updates an existing space with new values for the specified fields. Only name, public_read, and labels can be updated. Fields not included in the request remain unchanged. IMMUTABLE FIELDS: space_embedders, default_chunking_config, and owner_id cannot be modified after creation. NAME UNIQUENESS: Name must be unique per owner - returns ALREADY_EXISTS if name conflicts with existing space. Requires UPDATE_SPACE_OWN permission for spaces you own (or UPDATE_SPACE_ANY for admin users). This operation is idempotent.

        Args:
            id (str): The unique identifier of the resource to update.
            request (UpdateSpaceRequest | dict): The update payload. Accepts a UpdateSpaceRequest instance or a plain dict with the same fields. Only specified fields will be modified.

        Returns:
            Space
        """
        if isinstance(request, dict):
            request = UpdateSpaceRequest.model_validate(request)
        resp = await self._http.put(
            f"{self._base_path}/{id}",
            json=request.model_dump(by_alias=True, exclude_unset=True),
            headers=self._headers,
        )
        return self._handle_response(resp, self._response_model)

    async def delete(self, *, id: str) -> None:
        """Delete a space

        Permanently deletes a space and all associated content. This operation cannot be undone. CASCADE DELETION: Removes the space record and cascades deletion to associated memories, chunks, and embedder associations. Requires DELETE_SPACE_OWN permission for spaces you own (or DELETE_SPACE_ANY for admin users). This operation is safe to retry - may return NOT_FOUND if already deleted.

        Args:
            id (string): The unique identifier of the space to delete
        """
        resp = await self._http.delete(f"{self._base_path}/{id}", headers=self._headers)
        raise_for_status(resp)

