"""Adapter for configure_index operation (2026-01.alpha API)."""

from __future__ import annotations

from typing import Any

import orjson

from msgspec import json as msgspec_json

from pinecone.models.indexes import ConfigureIndexRequest, IndexModel


def to_request(request: ConfigureIndexRequest) -> bytes:
    """Convert ConfigureIndexRequest to API JSON bytes.

    Uses orjson for fast serialization. The request model is converted
    to a dictionary and then serialized to JSON bytes.

    Args:
        request: ConfigureIndexRequest model

    Returns:
        JSON bytes ready to send in HTTP request body

    Example:
        >>> from pinecone.models.indexes import ConfigureIndexRequest
        >>> request = ConfigureIndexRequest(deletion_protection="enabled")
        >>> json_bytes = to_request(request)
        >>> # Send json_bytes in HTTP PATCH body
    """
    encoder = msgspec_json.Encoder()
    return encoder.encode(request)


def from_response(response_dict: dict[str, Any]) -> IndexModel:
    """Parse API response JSON to IndexModel.

    Uses msgspec for fast deserialization with automatic type validation.

    Args:
        response_dict: Dictionary from response.json()

    Returns:
        IndexModel instance with updated configuration

    Raises:
        msgspec.ValidationError: If response doesn't match IndexModel schema

    Example:
        >>> response = requests.patch(...).json()
        >>> index = from_response(response)
        >>> print(f"Updated: {index.name}")
    """
    decoder = msgspec_json.Decoder(IndexModel)
    return decoder.decode(orjson.dumps(response_dict))


__all__ = ["from_response", "to_request"]
