"""Integration tests for Backups namespace.

These tests make real API calls to Pinecone and require PINECONE_API_KEY.
"""

import os

import pytest

from pinecone import AsyncPinecone, Pinecone


@pytest.fixture()
def api_key():
    """Get API key from environment."""
    key = os.getenv("PINECONE_API_KEY")
    if not key:
        pytest.skip("PINECONE_API_KEY not set")
    return key


class TestBackupsIntegration:
    """Integration tests for Backups (sync)."""

    def test_list_backups_real_api(self, api_key):
        """Test listing backups with real API."""
        with Pinecone(api_key=api_key) as pc:
            # Should not raise
            backups_paginator = pc.backups.list()
            items = list(backups_paginator)

            # Verify structure (backups may or may not exist)
            assert isinstance(items, list)

            # If backups exist, verify structure
            for backup in items:
                assert isinstance(backup.backup_id, str)
                assert len(backup.backup_id) > 0
                assert isinstance(backup.source_index_name, str)
                assert len(backup.source_index_name) > 0
                assert isinstance(backup.source_index_id, str)
                assert isinstance(backup.status, str)
                assert backup.status in ["Initializing", "Ready", "Failed"]
                assert isinstance(backup.cloud, str)
                assert isinstance(backup.region, str)
                assert isinstance(backup.created_at, str)

    def test_list_backups_with_limit(self, api_key):
        """Test listing backups with limit parameter."""
        with Pinecone(api_key=api_key) as pc:
            # List with limit
            backups_paginator = pc.backups.list(limit=2)
            items = list(backups_paginator)

            # Verify limit is respected (if backups exist)
            assert len(items) <= 2

    def test_list_backups_iteration(self, api_key):
        """Test iterating over backups."""
        with Pinecone(api_key=api_key) as pc:
            # Should be able to iterate
            count = 0
            for backup in pc.backups.list():
                count += 1
                # Verify we can access properties
                assert backup.backup_id
                assert backup.status

            # Count should match list length
            items = list(pc.backups.list())
            assert count == len(items)

    def test_list_backups_pages(self, api_key):
        """Test page-level iteration."""
        with Pinecone(api_key=api_key) as pc:
            # Should be able to iterate pages
            page_count = 0
            for page in pc.backups.list().pages():
                page_count += 1
                assert isinstance(page.items, list)

            # Should have at least one page (even if empty)
            assert page_count >= 1

    def test_list_backups_to_list(self, api_key):
        """Test converting paginator to list."""
        with Pinecone(api_key=api_key) as pc:
            # Should be able to convert to list
            items = pc.backups.list().to_list()
            assert isinstance(items, list)

    @pytest.mark.skip(reason="Requires serverless index for full CRUD lifecycle test")
    def test_create_describe_delete_lifecycle(self, api_key):
        """Test full backup lifecycle: create, describe, delete.

        Note: This test is skipped because:
        1. Backups require a serverless index
        2. Creating a serverless index requires specific quota
        3. Backup creation itself takes time (typically a few minutes)

        To test manually:
        1. Create a serverless index (e.g., "test-index")
        2. Create backup:
           backup = pc.backups.create(
               index_name="test-index",
               name="test-backup",
               description="Integration test backup"
           )
        3. Wait for backup to be ready:
           import time
           while True:
               info = pc.backups.describe(backup.backup_id)
               if info.status == "Ready":
                   break
               time.sleep(10)
        4. List backups to verify it appears:
           backups = list(pc.backups.list(index_name="test-index"))
        5. Delete:
           pc.backups.delete(backup.backup_id)
        """


class TestAsyncBackupsIntegration:
    """Integration tests for AsyncBackups."""

    @pytest.mark.asyncio()
    async def test_list_backups_real_api(self, api_key):
        """Test listing backups with real API (async)."""
        async with AsyncPinecone(api_key=api_key) as pc:
            # Should not raise
            backups_paginator = pc.backups.list()
            items = []
            async for backup in backups_paginator:
                items.append(backup)

            # Verify structure (backups may or may not exist)
            assert isinstance(items, list)

            # If backups exist, verify structure
            for backup in items:
                assert isinstance(backup.backup_id, str)
                assert len(backup.backup_id) > 0
                assert isinstance(backup.source_index_name, str)
                assert len(backup.source_index_name) > 0
                assert isinstance(backup.status, str)
                assert backup.status in ["Initializing", "Ready", "Failed"]
                assert isinstance(backup.cloud, str)
                assert isinstance(backup.region, str)

    @pytest.mark.asyncio()
    async def test_list_backups_with_limit(self, api_key):
        """Test listing backups with limit parameter (async)."""
        async with AsyncPinecone(api_key=api_key) as pc:
            # List with limit
            backups_paginator = pc.backups.list(limit=2)
            items = []
            async for backup in backups_paginator:
                items.append(backup)

            # Verify limit is respected (if backups exist)
            assert len(items) <= 2

    @pytest.mark.asyncio()
    async def test_list_backups_iteration(self, api_key):
        """Test iterating over backups (async)."""
        async with AsyncPinecone(api_key=api_key) as pc:
            # Should be able to iterate
            count = 0
            async for backup in pc.backups.list():
                count += 1
                # Verify we can access properties
                assert backup.backup_id
                assert backup.status

            # Count should match list length
            items = []
            async for backup in pc.backups.list():
                items.append(backup)
            assert count == len(items)

    @pytest.mark.asyncio()
    async def test_list_backups_pages(self, api_key):
        """Test page-level iteration (async)."""
        async with AsyncPinecone(api_key=api_key) as pc:
            # Should be able to iterate pages
            page_count = 0
            async for page in pc.backups.list().pages():
                page_count += 1
                assert isinstance(page.items, list)

            # Should have at least one page (even if empty)
            assert page_count >= 1
