"""Async upsert method for AsyncRecords."""

from __future__ import annotations

from typing import Any

from pinecone._internal.validation import require_non_empty


async def upsert(
    self: Any,
    *,
    namespace: str,
    records: list[dict[str, Any]],
) -> None:
    """Upsert records into a namespace.

    Sends records as newline-delimited JSON to the records upsert endpoint.
    Each record must contain an ``_id`` (or ``id``) field. Additional fields
    matching the index's ``field_map`` configuration are used for embedding;
    all other fields are stored as metadata.

    Args:
        namespace (str): Target namespace for the upsert.
        records (list[dict[str, Any]]): Records to upsert. Each must include
            an ``_id`` field.

    Returns:
        None

    Raises:
        ValueError: If namespace or records is empty.
        PineconeApiException: If the API request fails.

    Examples:
        >>> await index.records.upsert(
        ...     namespace="my-ns",
        ...     records=[
        ...         {"_id": "rec1", "text": "hello world", "category": "greeting"},
        ...         {"_id": "rec2", "text": "goodbye", "category": "farewell"},
        ...     ],
        ... )
    """
    require_non_empty("namespace", namespace)
    require_non_empty("records", records)

    await self._make_ndjson_request(
        f"/records/namespaces/{namespace}/upsert",
        records=records,
    )
