"""Upsert method for Index."""

from __future__ import annotations

from typing import Any

import msgspec

from pinecone.models.index.upsert import UpsertResponse


_DECODER = msgspec.json.Decoder(UpsertResponse)


def upsert(
    self: Any,
    vectors: list[dict[str, Any]],
    *,
    namespace: str = "",
) -> UpsertResponse:
    """Insert or update vectors.

    Args:
        vectors: List of vectors to upsert. Each vector should be a dict
            with 'id', 'values', and optionally 'sparseValues' and 'metadata'.
        namespace: Target namespace.

    Returns:
        UpsertResponse with the count of upserted vectors.

    Example:
        >>> response = index.upsert(
        ...     vectors=[
        ...         {"id": "v1", "values": [0.1, 0.2], "metadata": {"key": "val"}},
        ...         {"id": "v2", "values": [0.3, 0.4]},
        ...     ],
        ... )
        >>> print(f"Upserted {response.upserted_count} vectors")
    """
    body: dict[str, Any] = {"vectors": vectors}
    if namespace:
        body["namespace"] = namespace

    data = self._make_data_plane_request("POST", "/vectors/upsert", body=body)
    return _DECODER.decode(data)
