"""Common test fixtures and configuration."""
import os
import pytest
from dotenv import load_dotenv
from typing import Generator, AsyncGenerator
import asyncio
import httpx
from unittest.mock import AsyncMock, patch
from pathlib import Path

# Load environment variables
load_dotenv()

@pytest.fixture(scope="session")
def event_loop():
    """Create an instance of the default event loop for each test case."""
    policy = asyncio.get_event_loop_policy()
    loop = policy.new_event_loop()
    asyncio.set_event_loop(loop)
    yield loop
    loop.close()

@pytest.fixture
def workspace_root(tmp_path):
    """Create a temporary workspace root directory."""
    return tmp_path

@pytest.fixture
def magic_assistant(workspace_root):
    """Create a MagicAssistant instance with a temporary workspace."""
    from tools.magic_assistant import MagicAssistant
    assistant = MagicAssistant(workspace_root=str(workspace_root))
    return assistant

@pytest.fixture
def mock_pattern():
    """Create a mock pattern for testing."""
    from datetime import datetime
    from tools.magic_assistant import Pattern
    return Pattern(
        id="test_pattern",
        type="code_style",
        description="Test pattern",
        code_snippet="def test(): pass",
        success_count=5,
        failure_count=1,
        last_used=datetime.now(),
        contexts=["test"],
        confidence=0.8
    )

@pytest.fixture
def mock_httpx_client() -> AsyncMock:
    """Create a mock HTTPX client."""
    mock = AsyncMock()
    mock.aclose = AsyncMock()
    return mock

@pytest.fixture
def sample_python_code() -> str:
    """Return a sample Python code for testing."""
    return """
def calculate_factorial(n: int) -> int:
    if n < 0:
        raise ValueError("Factorial is not defined for negative numbers")
    if n == 0:
        return 1
    result = 1
    for i in range(1, n + 1):
        result *= i
    return result
"""

@pytest.fixture
def sample_security_code() -> str:
    """Return a sample code with security implications for testing."""
    return """
@app.route('/user/<username>')
def user_profile(username):
    query = f"SELECT * FROM users WHERE username = '{username}'"
    return db.execute(query).fetchone()
"""

@pytest.fixture
def api_keys() -> dict:
    """Return a dictionary of API keys from environment variables."""
    return {
        "openai": os.getenv("OPENAI_API_KEY"),
        "anthropic": os.getenv("ANTHROPIC_API_KEY"),
        "perplexity": os.getenv("PERPLEXITY_API_KEY"),
    }

def pytest_collection_modifyitems(items):
    """Skip tests that require API keys if they're not available."""
    for item in items:
        if "api" in item.keywords:
            api_keys = {
                "openai": os.getenv("OPENAI_API_KEY"),
                "anthropic": os.getenv("ANTHROPIC_API_KEY"),
                "perplexity": os.getenv("PERPLEXITY_API_KEY"),
            }
            if not all(api_keys.values()):
                item.add_marker(pytest.mark.skip(reason="API keys not available")) 