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

from __future__ import annotations

import os
from pathlib import Path

import pytest
from dotenv import load_dotenv

# Load .env from the dotpromptz package root (where pyproject.toml lives)
_ENV_FILE = Path(__file__).resolve().parents[2] / '.env'
load_dotenv(_ENV_FILE, override=False)


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_api_key(request) -> None:
    """Automatically skip integration tests when no API key is available.

    For tests that use an anthropic_adapter fixture, check ANTHROPIC_API_KEY;
    otherwise check OPENAI_API_KEY.
    """
    fixture_names = getattr(request, 'fixturenames', [])
    if 'anthropic_adapter' in fixture_names:
        if not os.environ.get('ANTHROPIC_API_KEY'):
            pytest.skip('ANTHROPIC_API_KEY not set – skipping integration test')
    elif 'google_adapter' in fixture_names:
        if not os.environ.get('GOOGLE_API_KEY'):
            pytest.skip('GOOGLE_API_KEY not set – skipping integration test')
    else:
        if not os.environ.get('OPENAI_API_KEY'):
            pytest.skip('OPENAI_API_KEY not set – skipping integration test')


@pytest.fixture()
def openai_adapter():
    """Create an OpenAIAdapter configured for Azure via env vars."""
    from dotpromptz.adapters.openai import OpenAIAdapter

    return OpenAIAdapter(default_model='gpt-4.1')


@pytest.fixture()
def anthropic_adapter():
    """Create an AnthropicAdapter configured via env vars."""
    from dotpromptz.adapters.anthropic import AnthropicAdapter

    return AnthropicAdapter(default_model='claude-haiku-4-5-20251001')


@pytest.fixture()
def google_adapter():
    """Create a GoogleAdapter configured via env vars."""
    from dotpromptz.adapters.google import GoogleAdapter

    return GoogleAdapter(default_model='gemini-2.5-flash')


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

    return Dotprompt(default_model='gpt-4.1')
