"""Create namespace method for AsyncNamespaces."""

from __future__ import annotations

from typing import Any

import msgspec

from pinecone._internal.validation import require_non_empty
from pinecone.models.namespaces.namespace import FieldConfig, NamespaceDescription


_DECODER = msgspec.json.Decoder(NamespaceDescription)


async def create(
    self: Any,
    *,
    name: str,
    schema: dict[str, dict[str, bool]] | dict[str, FieldConfig] | None = None,
) -> NamespaceDescription:
    """Create a new namespace in the index.

    Args:
        name (str): The name of the namespace to create.
        schema (dict[str, dict[str, bool]] | dict[str, FieldConfig] | None): Optional
            schema definition mapping field names to their configuration.
            Each field maps to a dict with configuration options such as
            ``{"filterable": True}`` or a ``FieldConfig`` object.

    Returns:
        NamespaceDescription for the newly created namespace.

    Raises:
        ValueError: If required parameters are empty.
        PineconeApiException: If the API request fails.

    Examples:
        >>> ns = await index.namespaces.create(name="my-namespace")
        >>> ns = await index.namespaces.create(
        ...     name="my-namespace",
        ...     schema={"category": {"filterable": True}},
        ... )
    """
    require_non_empty("name", name)
    body: dict[str, Any] = {"name": name}
    if schema is not None:
        fields: dict[str, Any] = {}
        for field_name, config in schema.items():
            if isinstance(config, FieldConfig):
                fields[field_name] = {"filterable": config.filterable}
            else:
                fields[field_name] = config
        body["schema"] = {"fields": fields}

    data = await self._make_data_plane_request("POST", "/namespaces", body=body)
    return _DECODER.decode(data)
