"""List method for collections namespace."""

from __future__ import annotations

from typing import TYPE_CHECKING, Any

import orjson

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


if TYPE_CHECKING:
    from pinecone.__interface__.collections import CollectionInfoProtocol


logger = get_logger(__name__)


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

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

    Returns:
        Paginator[CollectionInfoProtocol]: Iterator over CollectionInfo objects.
        Iterate directly for items, or use .pages() for page-level access.

    Example:
        >>> for coll in pc.collections.list():
        ...     print(f"{coll.name}: {coll.vector_count} vectors")

    Example with page-level access:
        >>> for page in pc.collections.list().pages():
        ...     print(f"Got {len(page.items)} collections")
    """
    # Validate inputs
    if limit is not None and limit <= 0:
        raise ValueError("limit must be a positive integer")

    logger.info(
        "Listing collections",
        limit=limit,
        has_pagination_token=pagination_token is not None,
    )

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

        try:
            # Build query params including pagination token
            params = {}
            if token:
                params["pagination_token"] = token

            response = self._http.get(
                f"{self._base_url}/collections",
                headers=self._headers,
                params=params,
            )

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

            logger.debug(
                "Successfully fetched collections",
                collection_count=len(result.collections),
            )

            # Extract next token from response (API may not support pagination yet)
            pagination = data.get("pagination")
            next_token = pagination.get("next") if pagination else None
            return Page(items=result.collections, pagination_token=next_token)

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

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