"""Adapter for transforming Index management API responses to SDK models.

This adapter provides minimal transformation from raw API responses to typed SDK models.
All transformations are documented to explain why they're needed.
"""

from typing import Any

from pinecone.models.indexes_old import (
    ByocSpec,
    IndexList,
    IndexModel,
    IndexSpec,
    IndexStatus,
    PodSpec,
    ServerlessReadCapacity,
    ServerlessReadCapacityDedicated,
    ServerlessReadCapacityManual,
    ServerlessReadCapacityStatus,
    ServerlessSpec,
)


class IndexesAdapter:
    """Adapter for Index management API responses.

    This class transforms raw API responses into typed SDK models. Each transformation
    is kept minimal and documented.
    """

    @staticmethod
    def to_index_list(data: dict[str, Any]) -> IndexList:
        """Transform list indexes API response to IndexList model.

        Args:
            data: Raw API response dictionary with "indexes" key

        Returns:
            Typed IndexList model

        Transformations:
            - Wraps index data in IndexModel objects
            - Preserves all index metadata from API response
            - Handles optional fields (dimension, deletion_protection, tags)
            - Parses nested spec configuration (serverless or pod)
        """
        indexes = [IndexesAdapter.to_index_model(item) for item in data["indexes"]]
        return IndexList(indexes=indexes)

    @staticmethod
    def to_index_model(data: dict[str, Any]) -> IndexModel:
        """Transform single index data to IndexModel.

        Used for both create and describe responses.

        Args:
            data: Raw index data dictionary

        Returns:
            Typed IndexModel

        Transformations:
            - Wraps status data in IndexStatus object
            - Parses nested spec configuration (serverless, pod, or BYOC)
            - Handles optional fields (dimension, private_host, deletion_protection, tags, embed)
        """
        return IndexModel(
            name=data["name"],
            metric=data["metric"],
            vector_type=data["vector_type"],
            host=data["host"],
            private_host=data.get("private_host"),
            dimension=data.get("dimension"),
            deletion_protection=data.get("deletion_protection"),
            tags=data.get("tags"),
            embed=data.get("embed"),
            status_obj=IndexStatus(
                ready=data["status"]["ready"],
                state=data["status"]["state"],
            ),
            spec=IndexesAdapter._to_index_spec(data["spec"]),
        )

    @staticmethod
    def _to_index_spec(data: dict[str, Any]) -> IndexSpec:
        """Transform spec data to IndexSpec.

        Args:
            data: Raw spec data dictionary (contains "serverless", "pod", or "byoc")

        Returns:
            Typed IndexSpec
        """
        serverless = None
        pod = None
        byoc = None

        if "serverless" in data:
            serverless_data = data["serverless"]
            read_capacity_data = serverless_data["read_capacity"]

            # Parse read capacity status
            status_data = read_capacity_data["status"]
            read_capacity_status = ServerlessReadCapacityStatus(
                state=status_data["state"],
                current_shards=status_data.get("current_shards"),
                current_replicas=status_data.get("current_replicas"),
                error_message=status_data.get("error_message"),
            )

            # Parse dedicated configuration if present
            dedicated = None
            if "dedicated" in read_capacity_data:
                dedicated_data = read_capacity_data["dedicated"]
                manual = None
                if "manual" in dedicated_data:
                    manual_data = dedicated_data["manual"]
                    manual = ServerlessReadCapacityManual(
                        shards=manual_data["shards"],
                        replicas=manual_data["replicas"],
                    )

                dedicated = ServerlessReadCapacityDedicated(
                    node_type=dedicated_data["node_type"],
                    scaling=dedicated_data["scaling"],
                    manual=manual,
                )

            read_capacity = ServerlessReadCapacity(
                mode=read_capacity_data["mode"],
                status=read_capacity_status,
                dedicated=dedicated,
            )

            serverless = ServerlessSpec(
                cloud=serverless_data["cloud"],
                region=serverless_data["region"],
                read_capacity=read_capacity,
                source_collection=serverless_data.get("source_collection"),
                schema=serverless_data.get("schema"),
            )

        if "pod" in data:
            pod_data = data["pod"]
            pod = PodSpec(
                environment=pod_data["environment"],
                pod_type=pod_data["pod_type"],
                pods=pod_data["pods"],
                replicas=pod_data["replicas"],
                shards=pod_data["shards"],
                metadata_config=pod_data.get("metadata_config"),
                source_collection=pod_data.get("source_collection"),
            )

        if "byoc" in data:
            byoc_data = data["byoc"]
            read_capacity_data = byoc_data["read_capacity"]

            # Parse read capacity status (same structure as serverless)
            status_data = read_capacity_data["status"]
            read_capacity_status = ServerlessReadCapacityStatus(
                state=status_data["state"],
                current_shards=status_data.get("current_shards"),
                current_replicas=status_data.get("current_replicas"),
                error_message=status_data.get("error_message"),
            )

            # Parse dedicated configuration if present
            dedicated = None
            if "dedicated" in read_capacity_data:
                dedicated_data = read_capacity_data["dedicated"]
                manual = None
                if "manual" in dedicated_data:
                    manual_data = dedicated_data["manual"]
                    manual = ServerlessReadCapacityManual(
                        shards=manual_data["shards"],
                        replicas=manual_data["replicas"],
                    )

                dedicated = ServerlessReadCapacityDedicated(
                    node_type=dedicated_data["node_type"],
                    scaling=dedicated_data["scaling"],
                    manual=manual,
                )

            read_capacity = ServerlessReadCapacity(
                mode=read_capacity_data["mode"],
                status=read_capacity_status,
                dedicated=dedicated,
            )

            byoc = ByocSpec(
                environment=byoc_data["environment"],
                read_capacity=read_capacity,
            )

        return IndexSpec(serverless=serverless, pod=pod, byoc=byoc)
