"""Update method for Index."""

from __future__ import annotations

from typing import TYPE_CHECKING, Any

import msgspec

from pinecone.models.index.update import UpdateResponse


_DECODER = msgspec.json.Decoder(UpdateResponse)


if TYPE_CHECKING:
    from pinecone.__interface__.index import Metadata, SparseValues


def update(
    self: Any,
    id: str,
    *,
    values: list[float] | None = None,
    sparse_values: SparseValues | None = None,
    set_metadata: Metadata | None = None,
    namespace: str = "",
) -> UpdateResponse:
    """Update a vector by ID.

    Args:
        id: Vector ID to update.
        values: New dense vector values.
        sparse_values: New sparse vector values.
        set_metadata: Metadata fields to set or overwrite.
        namespace: Target namespace.

    Returns:
        UpdateResponse with the number of matched records.

    Example:
        >>> response = index.update(
        ...     id="vec1",
        ...     set_metadata={"category": "updated"},
        ... )
        >>> print(f"Matched {response.matched_records} records")
    """
    body: dict[str, Any] = {"id": id}
    if values is not None:
        body["values"] = values
    if sparse_values is not None:
        body["sparseValues"] = sparse_values
    if set_metadata is not None:
        body["setMetadata"] = set_metadata
    if namespace:
        body["namespace"] = namespace

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