"""Shared response types used across products."""

from __future__ import annotations

from typing import Any, Callable, Generic, Iterator, TypeVar

from pydantic import BaseModel, PrivateAttr

T = TypeVar("T")


class PaginatedList(BaseModel, Generic[T]):
    """Paginated list response. Iterable — ``for msg in inbox:`` works directly.

    Supports automatic pagination::

        for msg in mb.inbox().auto_paging_iter():
            print(msg.subject)
    """

    items: list[T]
    cursor: str | None = None
    has_more: bool = False

    _fetch_fn: Callable[..., PaginatedList[T]] | None = PrivateAttr(default=None)
    _fetch_kwargs: dict[str, Any] = PrivateAttr(default_factory=dict)

    def __iter__(self) -> Iterator[T]:
        return iter(self.items)

    def __getitem__(self, index: int) -> T:
        return self.items[index]

    def __len__(self) -> int:
        return len(self.items)

    def __bool__(self) -> bool:
        return bool(self.items)

    def auto_paging_iter(self, *, max_pages: int = 1000) -> Iterator[T]:
        """Iterate through all pages automatically.

        Args:
            max_pages: Safety limit on total pages fetched (default 1000).
        """
        page = self
        for _ in range(max_pages):
            yield from page.items
            if not page.has_more or page.cursor is None or page._fetch_fn is None:
                break
            page = page._fetch_fn(**{**page._fetch_kwargs, "cursor": page.cursor})
