"""Async backups namespace implementation for managing serverless index backups.

This module provides the async implementation for backup management operations,
enabling concurrent backup operations for async frameworks.
"""

from __future__ import annotations

from typing import TYPE_CHECKING

from pinecone._internal.adapters.backups_adapter import BackupsAdapter
from pinecone._internal.constants import CONTROL_PLANE_API_VERSION
from pinecone._internal.introspection import InteractiveIntrospectionMixin
from pinecone._internal.logging import get_logger


if TYPE_CHECKING:
    from pinecone.__interface__.backups import BackupInfoProtocol
    from pinecone._internal.http import AsyncHTTPClient
    from pinecone.async_backups import _create, _delete, _describe, _list
    from pinecone.models.pagination import AsyncPaginator


__all__ = ["AsyncBackups"]

logger = get_logger(__name__)


class AsyncBackups(InteractiveIntrospectionMixin):
    """Async implementation of backup management operations.

    This class enables concurrent API calls for backup management, making it
    ideal for async frameworks like FastAPI or when managing multiple backups
    in parallel.

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

    Example:
        >>> from pinecone import AsyncPinecone
        >>> import asyncio
        >>>
        >>> async def main():
        ...     async with AsyncPinecone(api_key="...") as pc:
        ...         # Create a backup
        ...         backup = await pc.backups.create(
        ...             index_name="my-index",
        ...             name="example-backup",
        ...             description="Monthly backup",
        ...         )
        ...         print(f"Backup ID: {backup.backup_id}")
        ...
        ...         # List all backups
        ...         async for backup in pc.backups.list():
        ...             print(f"{backup.backup_id}: {backup.status}")
        ...
        ...         # Describe a backup
        ...         info = await pc.backups.describe(backup.backup_id)
        ...         print(f"Records: {info.record_count}")
        ...
        ...         # Delete a backup
        ...         await pc.backups.delete(backup.backup_id)
        >>>
        >>> asyncio.run(main())

    Example with concurrent operations:
        >>> async def backup_multiple_indexes(pc, index_names):
        ...     tasks = [
        ...         pc.backups.create(index_name=name, name=f"{name}-backup")
        ...         for name in index_names
        ...     ]
        ...     return await asyncio.gather(*tasks)
    """

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

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

        # Import and bind methods once at initialization (eager binding)
        from pinecone.async_backups 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 create(self, *args, **kwargs):  # type: ignore[no-untyped-def]
        """Stub for create method (overridden in __init__)."""
        raise NotImplementedError  # pragma: no cover

    def list(self, *args, **kwargs):  # type: ignore[no-untyped-def]
        """Stub for list 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

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

    def __repr__(self) -> str:
        """Return developer-friendly representation."""
        return f"AsyncBackups(base_url='{self._base_url}')"
