"""
Pytest configuration and fixtures for AI Feedback FastAPI tests.
"""

import asyncio
from collections.abc import AsyncGenerator, Generator
from unittest.mock import AsyncMock, MagicMock

import pytest
from fastapi import FastAPI
from fastapi.testclient import TestClient
from httpx import AsyncClient
from tortoise.contrib.test import finalizer, initializer

from app.main import app


@pytest.fixture(scope="session")
def event_loop() -> Generator[asyncio.AbstractEventLoop, None, None]:
    """Create an instance of the default event loop for the test session."""
    loop = asyncio.get_event_loop_policy().new_event_loop()
    yield loop
    loop.close()


@pytest.fixture(scope="session")
async def test_db():
    """Initialize test database."""
    # Use in-memory SQLite for testing
    db_url = "sqlite://:memory:"

    await initializer(
        db_url,
        modules={
            "models": [
                "app.models.queue",
                "app.models.interview",
                "app.models.feedback",
            ]
        },
        app_label="test",
    )

    yield

    await finalizer()


@pytest.fixture
def app_with_db() -> FastAPI:
    """FastAPI app with test database."""
    return app


@pytest.fixture
def client() -> TestClient:
    """Test client for FastAPI app."""
    return TestClient(app)


@pytest.fixture
async def async_client(app_with_db) -> AsyncGenerator[AsyncClient, None]:
    """Async test client for FastAPI app."""
    async with AsyncClient(app=app_with_db, base_url="http://test") as ac:
        yield ac


@pytest.fixture
def mock_aws_service():
    """Mock AWS service."""
    mock = MagicMock()
    mock.upload_file = AsyncMock(return_value="s3://bucket/test-file.mp4")
    mock.download_file = AsyncMock(return_value="/tmp/test-file.mp4")
    mock.delete_file = AsyncMock(return_value=True)
    return mock


@pytest.fixture
def mock_health_service():
    """Mock health service."""
    mock = MagicMock()
    mock.check_all = AsyncMock(
        return_value={
            "status": "healthy",
            "timestamp": "2024-01-01T00:00:00",
            "checks": {
                "database": {
                    "healthy": True,
                    "message": "Database connection successful",
                },
                "aws": {"healthy": True, "message": "AWS connection successful"},
                "queue": {
                    "healthy": True,
                    "message": "Queue status check successful",
                    "stats": {"0": 0, "1": 0, "2": 0, "3": 0},
                },
            },
        }
    )
    mock.is_ready = AsyncMock(return_value=True)
    return mock


@pytest.fixture
def mock_queue_processor():
    """Mock queue processor service."""
    mock = MagicMock()
    mock.process_queue = AsyncMock(return_value=True)
    mock.add_job = AsyncMock(return_value={"id": "test-job-id", "status": "0"})
    return mock


@pytest.fixture
def sample_queue_data():
    """Sample queue data for testing."""
    return {
        "video_name": "test-video.mp4",
        "user_id": 123,
        "interview_id": 456,
        "question_id": 789,
        "interview_type": "1",
    }


@pytest.fixture
def sample_health_response():
    """Sample health check response."""
    return {
        "status": "healthy",
        "timestamp": "2024-01-01T00:00:00",
        "checks": {
            "database": {
                "healthy": True,
                "message": "Database connection successful",
                "timestamp": "2024-01-01T00:00:00",
            },
            "aws": {
                "healthy": True,
                "message": "AWS connection successful",
                "timestamp": "2024-01-01T00:00:00",
            },
            "queue": {
                "healthy": True,
                "message": "Queue status check successful",
                "stats": {"0": 0, "1": 0, "2": 0, "3": 0},
                "timestamp": "2024-01-01T00:00:00",
            },
        },
    }
