"""
Tests for Voice Agent Tool Functions

Tests the slide control and slide generation tools to ensure they work
correctly with mocked Supabase client.

Part of Issue #144 - Stream B: Tool Functions & Slide Control
"""

import pytest

from voice_agent_livekit.tools import (
    add_bullet_point,
    generate_slide,
    get_current_slide,
    goto_slide,
    initialize_slide_control,
    initialize_slide_generation,
    navigate_slide,
    reload_slide,
    update_slide_content,
)


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

    def __init__(self):
        self.commands = []
        self.current_slide = 1
        self.decks = {
            "default": {
                "id": "default",
                "current_slide": 1,
                "total_slides": 10
            }
        }

    async def publish_slide_command(self, deck_id: str, command: str, slide_number=None):
        """Mock command publishing"""
        self.commands.append({
            "deck_id": deck_id,
            "command": command,
            "slide_number": slide_number
        })
        return {
            "id": f"cmd-{len(self.commands)}",
            "deck_id": deck_id,
            "command": command,
            "slide_number": slide_number
        }

    async def get_current_slide_number(self, deck_id: str):
        """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):
        """Mock getting slide deck"""
        return self.decks.get(deck_id)

    async def update_current_slide(self, deck_id: str, slide_number: int):
        """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"""
        return MockSupabaseTable()


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

    def __init__(self):
        self.inserted_data = []

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

    def insert(self, data):
        """Mock insert operation"""
        self.inserted_data.append({
            "table": self.current_table,
            "data": data
        })
        return self

    def execute(self):
        """Mock execute"""
        class Result:
            data = [{"id": f"gen-{len(self.inserted_data)}", **self.inserted_data[-1]["data"]}]
        return Result()


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


@pytest.fixture
def initialized_tools(mock_client):
    """Fixture that initializes tools with mock client"""
    initialize_slide_control(mock_client)
    initialize_slide_generation(mock_client)
    return mock_client


@pytest.mark.asyncio
async def test_navigate_slide_next(initialized_tools):
    """Test navigating to next slide"""
    result = await navigate_slide(direction="next", deck_id="default")
    assert "next" in result.lower()
    assert len(initialized_tools.commands) == 1
    assert initialized_tools.commands[0]["command"] == "next"


@pytest.mark.asyncio
async def test_navigate_slide_prev(initialized_tools):
    """Test navigating to previous slide"""
    result = await navigate_slide(direction="prev", deck_id="default")
    assert "prev" in result.lower()
    assert len(initialized_tools.commands) == 1
    assert initialized_tools.commands[0]["command"] == "prev"


@pytest.mark.asyncio
async def test_navigate_slide_goto(initialized_tools):
    """Test navigating to specific slide"""
    result = await navigate_slide(direction="next", slide_number=5, deck_id="default")
    assert "5" in result
    assert len(initialized_tools.commands) == 1
    assert initialized_tools.commands[0]["command"] == "goto"
    assert initialized_tools.commands[0]["slide_number"] == 5


@pytest.mark.asyncio
async def test_goto_slide(initialized_tools):
    """Test goto_slide convenience function"""
    result = await goto_slide(slide_number=3, deck_id="default")
    assert "3" in result
    assert len(initialized_tools.commands) == 1
    assert initialized_tools.commands[0]["command"] == "goto"
    assert initialized_tools.commands[0]["slide_number"] == 3


@pytest.mark.asyncio
async def test_get_current_slide(initialized_tools):
    """Test getting current slide number"""
    result = await get_current_slide(deck_id="default")
    assert "1" in result  # Mock returns slide 1
    assert "currently" in result.lower() or "slide" in result.lower()


@pytest.mark.asyncio
async def test_reload_slide(initialized_tools):
    """Test reloading current slide"""
    result = await reload_slide(deck_id="default")
    assert "reload" in result.lower()
    assert len(initialized_tools.commands) == 1
    assert initialized_tools.commands[0]["command"] == "reload"


@pytest.mark.asyncio
async def test_generate_slide(initialized_tools):
    """Test generating a new slide"""
    result = await generate_slide(topic="Test Topic", content="Test content", deck_id="default")
    assert "Test Topic" in result
    assert "creating" in result.lower() or "create" in result.lower()


@pytest.mark.asyncio
async def test_generate_slide_no_content(initialized_tools):
    """Test generating a slide without content"""
    result = await generate_slide(topic="AI Basics", deck_id="default")
    assert "AI Basics" in result
    assert "creating" in result.lower() or "create" in result.lower()


@pytest.mark.asyncio
async def test_add_bullet_point_current_slide(initialized_tools):
    """Test adding bullet point to current slide"""
    result = await add_bullet_point(text="Important point", deck_id="default")
    assert "Important point" in result
    assert "adding" in result.lower() or "add" in result.lower()


@pytest.mark.asyncio
async def test_add_bullet_point_specific_slide(initialized_tools):
    """Test adding bullet point to specific slide"""
    result = await add_bullet_point(text="Key insight", slide_number=5, deck_id="default")
    assert "Key insight" in result
    assert "5" in result


@pytest.mark.asyncio
async def test_update_slide_content(initialized_tools):
    """Test updating slide content"""
    result = await update_slide_content(content="New content", deck_id="default")
    assert "updating" in result.lower() or "update" in result.lower()


@pytest.mark.asyncio
async def test_invalid_slide_number(initialized_tools):
    """Test error handling for invalid slide number"""
    result = await goto_slide(slide_number=0, deck_id="default")
    assert "positive integer" in result.lower()


@pytest.mark.asyncio
async def test_tools_not_initialized():
    """Test that tools raise error when not initialized"""
    # Reset the global client (this is a bit hacky but necessary for testing)
    import voice_agent_livekit.tools.slide_control as sc
    import voice_agent_livekit.tools.slide_generation as sg

    original_sc_client = sc._supabase_client
    original_sg_client = sg._supabase_client

    sc._supabase_client = None
    sg._supabase_client = None

    try:
        result = await navigate_slide(direction="next")
        assert "error" in result.lower() or "sorry" in result.lower()

        result = await generate_slide(topic="Test")
        assert "error" in result.lower() or "sorry" in result.lower()
    finally:
        # Restore
        sc._supabase_client = original_sc_client
        sg._supabase_client = original_sg_client


# Integration Scenarios (Extended for Issue #144 Stream C)


@pytest.mark.asyncio
async def test_sequential_navigation_workflow(initialized_tools):
    """Test sequential navigation through slides"""
    # Start at slide 1
    result = await get_current_slide(deck_id="default")
    assert "1" in result

    # Navigate to next slide
    await navigate_slide(direction="next", deck_id="default")
    assert len(initialized_tools.commands) == 1

    # Navigate to another specific slide
    await goto_slide(slide_number=5, deck_id="default")
    assert len(initialized_tools.commands) == 2
    assert initialized_tools.commands[1]["slide_number"] == 5

    # Navigate back
    await navigate_slide(direction="prev", deck_id="default")
    assert len(initialized_tools.commands) == 3


@pytest.mark.asyncio
async def test_slide_generation_workflow(initialized_tools):
    """Test complete slide generation workflow"""
    # Generate a new slide with topic and content
    result = await generate_slide(
        topic="Machine Learning Basics",
        content="Introduction to ML concepts",
        deck_id="default"
    )
    assert "Machine Learning Basics" in result

    # Add bullet points to the generated slide
    result = await add_bullet_point(
        text="Supervised learning",
        deck_id="default"
    )
    assert "Supervised learning" in result

    result = await add_bullet_point(
        text="Unsupervised learning",
        deck_id="default"
    )
    assert "Unsupervised learning" in result

    # Update slide content
    result = await update_slide_content(
        content="Updated ML introduction",
        deck_id="default"
    )
    assert "updating" in result.lower() or "update" in result.lower()


@pytest.mark.asyncio
async def test_multiple_deck_management(initialized_tools):
    """Test managing multiple decks simultaneously"""
    # Add another deck
    initialized_tools.decks["deck2"] = {
        "id": "deck2",
        "current_slide": 1,
        "total_slides": 5
    }

    # Navigate in deck1
    await navigate_slide(direction="next", deck_id="default")
    assert initialized_tools.commands[-1]["deck_id"] == "default"

    # Navigate in deck2
    await navigate_slide(direction="next", deck_id="deck2")
    assert initialized_tools.commands[-1]["deck_id"] == "deck2"

    # Generate slide in deck2
    await generate_slide(topic="Deck 2 Topic", deck_id="deck2")


@pytest.mark.asyncio
async def test_error_recovery_scenario(initialized_tools):
    """Test error handling and recovery"""
    # Try to navigate with invalid slide number
    result = await goto_slide(slide_number=-1, deck_id="default")
    assert "positive integer" in result.lower()

    # System should still work after error
    result = await navigate_slide(direction="next", deck_id="default")
    assert "next" in result.lower()


@pytest.mark.asyncio
async def test_slide_reload_after_generation(initialized_tools):
    """Test reloading slide after generating content"""
    # Generate a slide
    await generate_slide(topic="New Topic", content="New content", deck_id="default")

    # Reload the slide
    result = await reload_slide(deck_id="default")
    assert "reload" in result.lower()

    # Verify command was published
    reload_commands = [cmd for cmd in initialized_tools.commands if cmd["command"] == "reload"]
    assert len(reload_commands) > 0


@pytest.mark.asyncio
async def test_complex_presentation_workflow(initialized_tools):
    """Integration test simulating a complete presentation workflow"""
    # 1. Start presentation
    current = await get_current_slide(deck_id="default")
    assert "1" in current

    # 2. Navigate through first few slides
    await navigate_slide(direction="next", deck_id="default")
    await navigate_slide(direction="next", deck_id="default")

    # 3. Generate a new slide on the fly
    await generate_slide(
        topic="Additional Context",
        content="This slide was generated during the presentation",
        deck_id="default"
    )

    # 4. Add bullet points to the new slide
    await add_bullet_point(text="Point 1", deck_id="default")
    await add_bullet_point(text="Point 2", deck_id="default")
    await add_bullet_point(text="Point 3", deck_id="default")

    # 5. Update the content
    await update_slide_content(
        content="Finalized content with all points",
        deck_id="default"
    )

    # 6. Jump to specific slide
    await goto_slide(slide_number=7, deck_id="default")

    # 7. Navigate back
    await navigate_slide(direction="prev", deck_id="default")

    # 8. Reload current slide
    await reload_slide(deck_id="default")

    # Verify slide control commands were issued (navigate, goto, reload)
    # Note: generate_slide, add_bullet_point, and update_slide_content use table inserts, not commands
    assert len(initialized_tools.commands) >= 5  # next, next, goto, prev, reload


@pytest.mark.asyncio
async def test_concurrent_tool_calls(initialized_tools):
    """Test that tools handle rapid successive calls"""
    import asyncio

    # Make multiple rapid calls
    tasks = [
        navigate_slide(direction="next", deck_id="default"),
        get_current_slide(deck_id="default"),
        reload_slide(deck_id="default"),
    ]

    results = await asyncio.gather(*tasks)

    # All calls should complete successfully
    assert len(results) == 3
    assert all(isinstance(result, str) for result in results)


@pytest.mark.asyncio
async def test_deck_state_tracking(initialized_tools):
    """Test that deck state is properly tracked during navigation"""
    # Initial state
    current = await get_current_slide(deck_id="default")
    assert "1" in current

    # Update current slide via tool
    await initialized_tools.update_current_slide(deck_id="default", slide_number=3)

    # Verify state is tracked
    current_num = await initialized_tools.get_current_slide_number(deck_id="default")
    assert current_num == 3


@pytest.mark.asyncio
async def test_slide_generation_with_metadata(initialized_tools):
    """Test slide generation preserves all metadata"""
    result = await generate_slide(
        topic="Advanced Topic",
        content="Detailed content with examples",
        deck_id="default"
    )

    # Verify the result message confirms generation
    assert "Advanced Topic" in result
    assert "creating" in result.lower() or "create" in result.lower()


@pytest.mark.asyncio
async def test_nonexistent_deck_handling(initialized_tools):
    """Test handling of operations on non-existent deck"""
    # Try to get current slide from non-existent deck
    result = await initialized_tools.get_current_slide_number(deck_id="nonexistent")
    assert result is None

    # Try to get deck info
    deck = await initialized_tools.get_slide_deck(deck_id="nonexistent")
    assert deck is None


@pytest.mark.asyncio
async def test_bullet_point_ordering(initialized_tools):
    """Test that bullet points can be added successfully"""
    points = [
        "First point",
        "Second point",
        "Third point",
        "Fourth point"
    ]

    # Add each bullet point and verify the result message
    for point in points:
        result = await add_bullet_point(text=point, deck_id="default")
        assert point in result
        assert "adding" in result.lower() or "add" in result.lower()
