"""Async collections namespace implementation for managing collection resources.

This module provides async collection management operations (CRUD) for Pinecone collections.
Collections are static copies of indexes useful for backups and cloning.
"""

from __future__ import annotations

from typing import TYPE_CHECKING

from pinecone._internal.adapters.collections_adapter import CollectionsAdapter
from pinecone._internal.constants import CONTROL_PLANE_API_VERSION
from pinecone._internal.introspection import InteractiveIntrospectionMixin


if TYPE_CHECKING:
    from pinecone._internal.http import AsyncHTTPClient
    from pinecone.async_collections import _create, _delete, _describe, _list


class AsyncCollections(InteractiveIntrospectionMixin):
    """Async implementation of collection management operations.

    This class provides async CRUD operations for managing Pinecone collections,
    enabling concurrent collection management operations. Collections are static,
    non-queryable copies of pod-based indexes that only consume storage (no
    compute costs). They are useful for backups, cloning, and temporarily
    shutting down indexes.

    Note:
        - Serverless indexes do not support collections. Only pod-based indexes
          can create collections.
        - Collections cannot be moved between projects once created.
        - Collection creation is asynchronous and may take time to complete
          (typically ~10 minutes for p1/s1 pods, potentially hours for p2 pods
          with millions of vectors).

    Args:
        http_client: Async HTTP client for making API requests
        base_url: Base URL for the Collections API

    Example:
        >>> from pinecone import AsyncPinecone
        >>> import asyncio
        >>>
        >>> async def main():
        ...     async with AsyncPinecone(api_key="...") as pc:
        ...         # List collections
        ...         async for coll in pc.collections.list():
        ...             print(f"{coll.name}: {coll.status}")
        ...
        ...         # Create collection from index
        ...         await pc.collections.create(name="my-backup", source="my-index")
        ...
        ...         # Poll until ready
        ...         while True:
        ...             info = await pc.collections.describe("my-backup")
        ...             if info.status == "Ready":
        ...                 break
        ...             await asyncio.sleep(10)
        ...
        ...         # Delete collection
        ...         await pc.collections.delete("my-backup")
        >>>
        >>> asyncio.run(main())

    Example with concurrent operations:
        >>> async def manage_collections(pc, collection_names):
        ...     tasks = [pc.collections.describe(name) for name in collection_names]
        ...     return await asyncio.gather(*tasks)
    """

    def __init__(
        self,
        http_client: AsyncHTTPClient,
        base_url: str = "https://api.pinecone.io",
    ):
        """Initialize async Collections namespace.

        Args:
            http_client: Async HTTP client for making API requests
            base_url: Base URL for the Collections API. Defaults to production endpoint.
        """
        self._http = http_client
        self._base_url = base_url
        self._adapter = CollectionsAdapter()
        self._headers = {"X-Pinecone-Api-Version": CONTROL_PLANE_API_VERSION}

        # Import and bind methods once at initialization (eager binding)
        from pinecone.async_collections import (  # noqa: PLC0415
            _create,
            _delete,
            _describe,
            _list,
        )

        self.list = _list.list.__get__(self, type(self))  # type: ignore[method-assign]
        self.create = _create.create.__get__(self, type(self))  # type: ignore[method-assign]
        self.delete = _delete.delete.__get__(self, type(self))  # type: ignore[method-assign]
        self.describe = _describe.describe.__get__(self, type(self))  # type: ignore[method-assign]

    # Protocol method stubs (overridden in __init__)
    async def list(self, *args, **kwargs):  # type: ignore[no-untyped-def]
        """Stub for list method (overridden in __init__)."""
        raise NotImplementedError  # pragma: no cover

    async def create(self, *args, **kwargs):  # type: ignore[no-untyped-def]
        """Stub for create method (overridden in __init__)."""
        raise NotImplementedError  # pragma: no cover

    async def delete(self, *args, **kwargs):  # type: ignore[no-untyped-def]
        """Stub for delete method (overridden in __init__)."""
        raise NotImplementedError  # pragma: no cover

    async def describe(self, *args, **kwargs):  # type: ignore[no-untyped-def]
        """Stub for describe method (overridden in __init__)."""
        raise NotImplementedError  # pragma: no cover

    def __repr__(self) -> str:
        """Return string representation of collections namespace."""
        return f"AsyncCollections(base_url='{self._base_url}')"
