"""Pytest configuration and fixtures."""

import os
from pathlib import Path

import pytest

# Try to load .env file if python-dotenv is available
try:
    from dotenv import load_dotenv

    # Load .env file from project root
    env_path = Path(__file__).parent.parent / ".env"
    if env_path.exists():
        load_dotenv(env_path, override=True)
        # Debug: print if API key was loaded (only if not empty)
        api_key = os.getenv("LEGNEXT_API_KEY")
        if api_key and api_key != "your_api_key_here":
            print(f"✅ Loaded API key from .env file (length: {len(api_key)})")
except ImportError:
    # python-dotenv not installed, skip loading .env file
    print("⚠️  python-dotenv not installed. Install with: uv pip install python-dotenv")
except Exception as e:
    print(f"⚠️  Error loading .env file: {e}")


@pytest.fixture
def api_key():
    """Test API key fixture.

    For unit tests: returns a mock API key.
    For integration tests: can be overridden with LEGNEXT_API_KEY environment variable.
    """
    # Check if real API key is provided via environment variable
    real_api_key = os.getenv("LEGNEXT_API_KEY")
    if real_api_key:
        return real_api_key
    # Default to mock API key for unit tests
    return "test_api_key_12345"


@pytest.fixture
def real_api_key():
    """Real API key fixture for integration tests.

    Returns None if LEGNEXT_API_KEY is not set, allowing tests to skip.
    """
    api_key = os.getenv("LEGNEXT_API_KEY")
    # Check if API key is valid (not empty and not placeholder)
    if not api_key or api_key.strip() == "" or api_key == "your_api_key_here":
        pytest.skip(
            "LEGNEXT_API_KEY not set in environment or .env file. Please set it in .env file."
        )
    return api_key


@pytest.fixture
def mock_job_id():
    """Mock job ID fixture."""
    return "550e8400-e29b-41d4-a716-446655440000"


@pytest.fixture
def mock_task_response():
    """Mock task response fixture."""
    return {
        "job_id": "550e8400-e29b-41d4-a716-446655440000",
        "model": "midjourney",
        "task_type": "diffusion",
        "status": "completed",
        "output": {
            "image_urls": [
                "https://example.com/image1.jpg",
                "https://example.com/image2.jpg",
                "https://example.com/image3.jpg",
                "https://example.com/image4.jpg",
            ],
            "seed": "123456",
        },
        "meta": {
            "created_at": "2025-01-20T10:00:00Z",
            "started_at": "2025-01-20T10:00:05Z",
            "ended_at": "2025-01-20T10:01:30Z",
        },
    }
