"""List method for indexes namespace."""

from __future__ import annotations

from typing import TYPE_CHECKING, Any, cast

import orjson

from pinecone._internal.constants import INDEXES_API_VERSION
from pinecone._internal.logging import get_logger
from pinecone.models.pagination import Page, Paginator


if TYPE_CHECKING:
    import builtins

    from pinecone.__interface__.indexes import IndexInfoProtocol


logger = get_logger(__name__)


def list(  # noqa: A001
    self: Any,
    *,
    limit: int | None = None,
    pagination_token: str | None = None,
) -> Paginator[IndexInfoProtocol]:
    """List all indexes in the project.

    Args:
        limit: Maximum number of items to return (across all pages).
        pagination_token: Token to resume pagination from a previous call.

    Returns:
        Paginator over IndexInfo objects. Iterate directly for items,
        or use .pages() for page-level access.

    Raises:
        APIError: If the API returns an error response
        APIConnectionError: If the request fails to connect
        TimeoutError: If the request times out

    Example:
        >>> for index in pc.indexes.list():
        ...     print(f"{index.name}: {index.config.dimension}D, {index.config.metric}")
        ...     print(f"  Host: {index.host}")
        ...     print(f"  Status: {index.status}")

    Example with page-level access:
        >>> for page in pc.indexes.list().pages():
        ...     print(f"Got {len(page.items)} indexes")
    """

    def fetch_page(token: str | None) -> Page[IndexInfoProtocol]:
        """Fetch a page of indexes."""
        logger.info("Listing indexes", pagination_token=token)

        try:
            response = self._http.get(
                f"{self._base_url}/indexes",
                headers={
                    "X-Pinecone-Api-Version": INDEXES_API_VERSION,
                },
            )

            data = orjson.loads(response.content)
            result = self._adapter.to_index_list(data)

            logger.debug(
                "Successfully listed indexes",
                index_count=len(result.indexes),
            )

            # Cast to list[IndexInfoProtocol] for type checker
            # IndexModel structurally satisfies IndexInfoProtocol
            items: builtins.list[IndexInfoProtocol] = cast(
                "builtins.list[IndexInfoProtocol]", result.indexes
            )

            # API currently doesn't support pagination, so return all items in one page
            return Page(items=items, pagination_token=None)

        except Exception:
            logger.exception("Failed to list indexes")
            raise

    return Paginator(
        fetch_page=fetch_page,
        initial_token=pagination_token,
        limit=limit,
        item_type="IndexModel",
    )
