"""Integration tests for Collections 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 TestCollectionsIntegration:
    """Integration tests for Collections (sync)."""

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

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

            # If collections exist, verify structure
            for coll in items:
                assert isinstance(coll.name, str)
                assert len(coll.name) > 0
                assert isinstance(coll.status, str)
                assert coll.status in ["Initializing", "Ready", "Terminating"]
                assert isinstance(coll.dimension, int)
                assert coll.dimension > 0
                assert isinstance(coll.vector_count, int)
                assert coll.vector_count >= 0
                assert isinstance(coll.size, int)
                assert coll.size >= 0
                assert isinstance(coll.environment, str)
                assert len(coll.environment) > 0

    def test_list_collections_with_limit(self, api_key):
        """Test listing collections with limit parameter."""
        with Pinecone(api_key=api_key) as pc:
            # List with limit
            collections_paginator = pc.collections.list(limit=2)
            items = list(collections_paginator)

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

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

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

    def test_list_collections_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.collections.list().pages():
                page_count += 1
                assert isinstance(page.items, list)
                # Current API returns all in one page
                assert page.pagination_token is None

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

    def test_list_collections_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.collections.list().to_list()
            assert isinstance(items, list)

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

        Note: This test is skipped because:
        1. Collections require a pod-based index (not serverless)
        2. Creating a pod-based index takes time and has quota limits
        3. Collection creation itself takes ~10 minutes

        To test manually:
        1. Create a pod-based index
        2. Create collection: pc.collections.create(name="test", source="index-name")
        3. Poll until ready: pc.collections.describe("test")
        4. Delete: pc.collections.delete("test")
        """


class TestAsyncCollectionsIntegration:
    """Integration tests for AsyncCollections."""

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

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

            # If collections exist, verify structure
            for coll in items:
                assert isinstance(coll.name, str)
                assert len(coll.name) > 0
                assert isinstance(coll.status, str)
                assert coll.status in ["Initializing", "Ready", "Terminating"]
                assert isinstance(coll.dimension, int)
                assert coll.dimension > 0
                assert isinstance(coll.vector_count, int)
                assert coll.vector_count >= 0
                assert isinstance(coll.size, int)
                assert coll.size >= 0
                assert isinstance(coll.environment, str)
                assert len(coll.environment) > 0

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

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

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

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

    @pytest.mark.asyncio()
    async def test_list_collections_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.collections.list().pages():
                page_count += 1
                assert isinstance(page.items, list)
                # Current API returns all in one page
                assert page.pagination_token is None

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

    @pytest.mark.asyncio()
    async def test_list_collections_to_list(self, api_key):
        """Test converting paginator to list (async)."""
        async with AsyncPinecone(api_key=api_key) as pc:
            # Should be able to convert to list
            items = await pc.collections.list().to_list()
            assert isinstance(items, list)
