"""Integration tests for SchemaBuilder with real API calls."""

import contextlib

import pytest

from pinecone import AsyncPinecone, Pinecone, SchemaBuilder
from pinecone.models.indexes import DenseVectorField, IntegerField, StringField


@pytest.fixture()
def test_index_name():
    """Generate unique test index name."""
    import uuid

    return f"test-schema-builder-{uuid.uuid4().hex[:8]}"


def test_schema_builder_with_sync_client(test_index_name):
    """Test SchemaBuilder with sync Pinecone client."""
    pc = Pinecone()

    # Build schema using SchemaBuilder
    schema = (
        SchemaBuilder()
        .add_dense_vector_field(
            "embedding", dimension=384, metric="cosine", description="Test embeddings"
        )
        .add_string_field("title", filterable=True, description="Document title")
        .add_integer_field("year", filterable=True, description="Publication year")
        .build()
    )

    try:
        # Create index with built schema
        index = pc.indexes.create(name=test_index_name, schema=schema)

        # Verify index was created with correct schema
        assert index.name == test_index_name
        assert "embedding" in index.schema.fields
        assert "title" in index.schema.fields
        assert "year" in index.schema.fields

        # Verify field types
        embedding_field = index.schema.fields["embedding"]
        assert isinstance(embedding_field, DenseVectorField)
        assert embedding_field.dimension == 384
        assert embedding_field.metric == "cosine"

        title_field = index.schema.fields["title"]
        assert isinstance(title_field, StringField)
        assert title_field.filterable is True

        year_field = index.schema.fields["year"]
        assert isinstance(year_field, IntegerField)
        assert year_field.filterable is True

    finally:
        # Cleanup
        with contextlib.suppress(Exception):
            pc.indexes.delete(test_index_name)


@pytest.mark.asyncio()
async def test_schema_builder_with_async_client(test_index_name):
    """Test SchemaBuilder with async Pinecone client."""
    async with AsyncPinecone() as pc:
        # Build schema using SchemaBuilder
        schema = (
            SchemaBuilder()
            .add_dense_vector_field(
                "embedding", dimension=384, metric="cosine", description="Test embeddings"
            )
            .add_string_field("category", filterable=True)
            .build()
        )

        try:
            # Create index with built schema
            index = await pc.indexes.create(name=test_index_name, schema=schema)

            # Verify index was created with correct schema
            assert index.name == test_index_name
            assert "embedding" in index.schema.fields
            assert "category" in index.schema.fields

            # Verify field types
            embedding_field = index.schema.fields["embedding"]
            assert isinstance(embedding_field, DenseVectorField)
            assert embedding_field.dimension == 384

            category_field = index.schema.fields["category"]
            assert isinstance(category_field, StringField)
            assert category_field.filterable is True

        finally:
            # Cleanup
            with contextlib.suppress(Exception):
                await pc.indexes.delete(test_index_name)


def test_schema_builder_post_build_mutation(test_index_name):
    """Test that schemas can be mutated after building."""
    pc = Pinecone()

    # Build schema
    schema = (
        SchemaBuilder().add_dense_vector_field("embedding", dimension=384, metric="cosine").build()
    )

    # Mutate before using
    schema["fields"]["embedding"]["description"] = "Added after build"

    try:
        # Create index with mutated schema
        index = pc.indexes.create(name=test_index_name, schema=schema)

        # Verify mutation was applied
        embedding_field = index.schema.fields["embedding"]
        assert isinstance(embedding_field, DenseVectorField)
        assert embedding_field.description == "Added after build"

    finally:
        # Cleanup
        with contextlib.suppress(Exception):
            pc.indexes.delete(test_index_name)


@pytest.mark.skip(
    reason="Test demonstrates future API parameter support - will work when API adds this parameter"
)
def test_schema_builder_with_future_parameters(test_index_name):
    """Test SchemaBuilder with hypothetical future API parameters."""
    pc = Pinecone()

    # Build schema with future parameter
    schema = (
        SchemaBuilder()
        .add_string_field(
            "title",
            full_text_searchable=True,
            language="en",
            case_sensitive=True,  # Hypothetical future parameter
        )
        .build()
    )

    try:
        # Create index - should not fail validation due to unknown field
        # (Will fail at API level if parameter truly doesn't exist yet)
        index = pc.indexes.create(name=test_index_name, schema=schema)
        assert index.name == test_index_name

    finally:
        with contextlib.suppress(Exception):
            pc.indexes.delete(test_index_name)
