"""
Pytest fixtures for Voice Agent tests.

Provides mocked components for:
- LiveKit Room and Participants
- LiveKit AgentSession
- Supabase client
- Agent configuration

Part of Issue #144 - Stream C: Testing & Validation
"""

import asyncio
from datetime import datetime
from typing import Any

import pytest


class MockParticipant:
    """Mock LiveKit Participant for testing"""

    def __init__(
        self,
        identity: str = "test_user",
        sid: str = "test_sid",
        name: str | None = None,
    ):
        self.identity = identity
        self.sid = sid
        self.name = name or identity
        self.metadata = ""
        self.kind = "standard"  # Mock participant kind

    def __repr__(self):
        return f"MockParticipant(identity={self.identity}, sid={self.sid})"


class MockRoom:
    """Mock LiveKit Room for testing"""

    def __init__(self, name: str = "test_room"):
        self.name = name
        self.sid = f"room_{name}"
        self.metadata = ""
        self.remote_participants: dict[str, MockParticipant] = {}
        self.local_participant = MockParticipant(identity="agent", sid="agent_sid")
        self._event_handlers: dict[str, list] = {}

    def on(self, event: str, handler):
        """Register event handler"""
        if event not in self._event_handlers:
            self._event_handlers[event] = []
        self._event_handlers[event].append(handler)

    async def emit(self, event: str, *args, **kwargs):
        """Emit an event to registered handlers"""
        if event in self._event_handlers:
            for handler in self._event_handlers[event]:
                if asyncio.iscoroutinefunction(handler):
                    await handler(*args, **kwargs)
                else:
                    handler(*args, **kwargs)

    def add_participant(self, participant: MockParticipant):
        """Add a remote participant to the room"""
        self.remote_participants[participant.sid] = participant

    def remove_participant(self, sid: str):
        """Remove a remote participant from the room"""
        if sid in self.remote_participants:
            del self.remote_participants[sid]


class MockJobContext:
    """Mock LiveKit JobContext for testing"""

    def __init__(self, room: MockRoom | None = None):
        self.room = room or MockRoom()
        self.agent = None
        self.job_id = "test_job_id"


class MockAgentSession:
    """Mock LiveKit AgentSession for testing"""

    def __init__(self):
        self.started = False
        self.room: MockRoom | None = None
        self.agent = None
        self.messages: list[str] = []

    async def start(self, room: MockRoom, agent: Any):
        """Mock session start"""
        self.started = True
        self.room = room
        self.agent = agent

    async def generate_reply(self, instructions: str):
        """Mock reply generation"""
        self.messages.append(instructions)

    async def stop(self):
        """Mock session stop"""
        self.started = False


class MockSupabaseClient:
    """Mock Supabase client for testing"""

    def __init__(self):
        self.commands: list[dict[str, Any]] = []
        self.decks: dict[str, dict[str, Any]] = {
            "default": {
                "id": "default",
                "current_slide": 1,
                "total_slides": 10,
                "title": "Test Deck",
            }
        }
        self.slide_generations: list[dict[str, Any]] = []
        self.inserted_data: list[dict[str, Any]] = []  # Track all table inserts
        self._table_client: MockSupabaseTable | None = None

    async def publish_slide_command(
        self, deck_id: str, command: str, slide_number: int | None = None
    ) -> dict[str, Any]:
        """Mock command publishing"""
        cmd = {
            "id": f"cmd-{len(self.commands) + 1}",
            "deck_id": deck_id,
            "command": command,
            "slide_number": slide_number,
            "created_at": datetime.now().isoformat(),
        }
        self.commands.append(cmd)
        return cmd

    async def get_current_slide_number(self, deck_id: str) -> int | None:
        """Mock getting current slide number"""
        deck = self.decks.get(deck_id)
        if deck:
            return deck["current_slide"]
        return None

    async def get_slide_deck(self, deck_id: str) -> dict[str, Any] | None:
        """Mock getting slide deck"""
        return self.decks.get(deck_id)

    async def update_current_slide(self, deck_id: str, slide_number: int) -> bool:
        """Mock updating current slide"""
        if deck_id in self.decks:
            self.decks[deck_id]["current_slide"] = slide_number
            return True
        return False

    @property
    def client(self):
        """Mock the underlying client property"""
        if self._table_client is None:
            self._table_client = MockSupabaseTable(self)
        return self._table_client


class MockSupabaseTable:
    """Mock Supabase table operations"""

    def __init__(self, parent_client: MockSupabaseClient):
        self.parent = parent_client
        self.current_table: str | None = None

    def table(self, table_name: str):
        """Return self for chaining"""
        self.current_table = table_name
        return self

    def insert(self, data: dict[str, Any]):
        """Mock insert operation"""
        # Track in parent's inserted_data
        self.parent.inserted_data.append({"table": self.current_table, "data": data})
        return self

    def execute(self):
        """Mock execute"""

        class Result:
            def __init__(self, data):
                self.data = data

        # Get the last inserted data
        last_insert = self.parent.inserted_data[-1] if self.parent.inserted_data else None

        if last_insert and last_insert["table"] == "slide_generation_requests":
            gen_id = len(self.parent.slide_generations) + 1
            record = {
                "id": f"gen-{gen_id}",
                **last_insert["data"],
                "created_at": datetime.now().isoformat(),
            }
            self.parent.slide_generations.append(record)
            return Result([record])

        if last_insert:
            return Result([{"id": "test-id", **last_insert["data"]}])

        return Result([{"id": "test-id"}])


class MockTTS:
    """Mock TTS model for testing"""

    def __init__(self, model: str = "test-tts"):
        self.model = model


class MockLLM:
    """Mock LLM model for testing"""

    def __init__(self, model: str = "test-llm"):
        self.model = model


@pytest.fixture
def mock_participant():
    """Fixture providing a mock LiveKit participant"""
    return MockParticipant()


@pytest.fixture
def mock_room():
    """Fixture providing a mock LiveKit room"""
    return MockRoom()


@pytest.fixture
def mock_job_context(mock_room):
    """Fixture providing a mock LiveKit JobContext"""
    return MockJobContext(room=mock_room)


@pytest.fixture
def mock_agent_session():
    """Fixture providing a mock LiveKit AgentSession"""
    return MockAgentSession()


@pytest.fixture
def mock_supabase_client():
    """Fixture providing a mock Supabase client"""
    return MockSupabaseClient()


@pytest.fixture
def mock_config():
    """Fixture providing a mock AgentConfig"""
    from voice_agent_livekit.config import AgentConfig

    return AgentConfig(
        livekit_url="wss://test.livekit.cloud",
        livekit_api_key="test_api_key",
        livekit_api_secret="test_api_secret",
        deepgram_api_key="test_deepgram_key",
        openai_api_key="test_openai_key",
        initial_greeting="Hello from test!",
        tts_model="test-tts",
        stt_model="test-stt",
        llm_model="test-llm",
        log_level="DEBUG",
    )


@pytest.fixture
def initialized_tools(mock_supabase_client):
    """Fixture that initializes tools with mock client"""
    from voice_agent_livekit.tools import (
        initialize_slide_control,
        initialize_slide_generation,
    )

    initialize_slide_control(mock_supabase_client)
    initialize_slide_generation(mock_supabase_client)
    return mock_supabase_client


@pytest.fixture(autouse=True)
def reset_tool_state():
    """Auto-reset tool global state between tests"""
    yield
    # Reset global clients after each test
    import voice_agent_livekit.tools.slide_control as sc
    import voice_agent_livekit.tools.slide_generation as sg

    sc._supabase_client = None
    sg._supabase_client = None


@pytest.fixture
def event_loop():
    """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()
