"""Adapter for create_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 CreateIndexRequest, IndexModel


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

    Uses msgspec for fast serialization. Fields with None values are omitted
    from the serialized JSON (the API expects fields to be absent, not null).

    Args:
        request: CreateIndexRequest model

    Returns:
        JSON bytes ready to send in HTTP request body

    Example:
        >>> from pinecone.models.indexes import CreateIndexRequest, Schema, DenseVectorField
        >>> request = CreateIndexRequest(
        ...     schema=Schema(fields={"embedding": DenseVectorField(...)}), name="my-index"
        ... )
        >>> json_bytes = to_request(request)
        >>> # Send json_bytes in HTTP POST body
    """
    # Encode to JSON first (msgspec handles nested structs)
    encoder = msgspec_json.Encoder()
    json_bytes = encoder.encode(request)

    # Decode back to dict, filter None values recursively, re-encode
    # The API expects fields to be absent, not null
    request_dict = orjson.loads(json_bytes)

    def filter_none_and_defaults(obj: Any) -> Any:
        """Recursively filter None values and False booleans from dicts.

        The API expects optional fields to be omitted entirely, not sent as null or false.
        """
        if isinstance(obj, dict):
            return {
                k: filter_none_and_defaults(v)
                for k, v in obj.items()
                if v is not None and v is not False
            }
        if isinstance(obj, list):
            return [filter_none_and_defaults(item) for item in obj]
        return obj

    filtered_dict = filter_none_and_defaults(request_dict)
    return orjson.dumps(filtered_dict)


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

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

    Example:
        >>> response = requests.post(...).json()
        >>> index = from_response(response)
        >>> print(f"Created: {index.name}")
    """
    # Convert dict back to JSON bytes then decode to model
    # This ensures proper type validation
    decoder = msgspec_json.Decoder(IndexModel)
    return decoder.decode(orjson.dumps(response_dict))


__all__ = ["from_response", "to_request"]
