"""Shared fixtures for integration tests that call real LLM APIs."""

import pytest
import pytest_asyncio

from dotpromptz.credentials import load_credentials


def pytest_configure(config: pytest.Config) -> None:
    """Register the ``integration`` marker."""
    config.addinivalue_line(
        'markers',
        'integration: tests that call real LLM APIs (require API keys)',
    )


@pytest.fixture(autouse=True)
def _skip_without_credentials(request) -> None:
    """Automatically skip integration tests when no matching credentials are available.

    Checks the API_CREDENTIALS pool for credentials matching the adapter
    required by each test's fixture.
    """
    pool = load_credentials()
    fixture_names = getattr(request, 'fixturenames', [])
    if 'anthropic_adapter' in fixture_names:
        if not pool.filter('anthropic'):
            pytest.skip('No anthropic credentials in API_CREDENTIALS')
    elif 'google_adapter' in fixture_names:
        if not pool.filter('google'):
            pytest.skip('No google credentials in API_CREDENTIALS')
    else:
        if not pool.filter('openai'):
            pytest.skip('No openai credentials in API_CREDENTIALS')


@pytest_asyncio.fixture()
async def openai_adapter():
    """Create an OpenAIAdapter with credentials from the pool."""
    from dotpromptz.adapters.openai import OpenAIAdapter

    pool = load_credentials()
    cred = pool.next('openai')
    adapter = OpenAIAdapter(credential=cred, default_model='gpt-4.1')
    yield adapter
    await adapter.aclose()


@pytest_asyncio.fixture()
async def anthropic_adapter():
    """Create an AnthropicAdapter with credentials from the pool."""
    from dotpromptz.adapters.anthropic import AnthropicAdapter

    pool = load_credentials()
    cred = pool.next('anthropic')
    adapter = AnthropicAdapter(credential=cred, default_model='claude-haiku-4-5-20251001')
    yield adapter
    await adapter.aclose()


@pytest_asyncio.fixture()
async def google_adapter():
    """Create a GoogleAdapter with credentials from the pool."""
    from dotpromptz.adapters.google import GoogleAdapter

    pool = load_credentials()
    cred = pool.next('google')
    adapter = GoogleAdapter(credential=cred, default_model='gemini-2.5-flash')
    yield adapter
    await adapter.aclose()


@pytest.fixture()
def dotprompt_instance():
    """Create a vanilla Dotprompt instance."""
    from dotpromptz import Dotprompt

    return Dotprompt(default_model='gpt-4.1')
