"""
Integration tests for Tavus Tool Call Forwarder Bot

Tests end-to-end flow:
1. Bot joins Daily.co room
2. Receives Tavus tool call event
3. Parses arguments with ToolCallParser
4. Forwards to Railway API via RailwayClient
5. Updates Supabase state
6. Sends response back to Tavus

Part of Issue #122 - Stream C: Testing Infrastructure
"""

import pytest
import asyncio
import json
from unittest.mock import Mock, AsyncMock, patch, MagicMock
from tests.mocks import (
    MOCK_TOOL_CALL_FULL,
    MOCK_TOOL_CALL_MINIMAL,
    MOCK_TOOL_CALL_CONTROL_SLIDE,
    MOCK_RAILWAY_RESPONSE_SUCCESS,
    MOCK_RAILWAY_RESPONSE_REAL_DECK,
    create_mock_tool_call,
    create_mock_railway_response
)


class TestBotInitialization:
    """Tests for bot initialization and configuration"""

    def test_bot_initialization_with_required_params(self, env_vars):
        """Test bot can be initialized with required parameters"""
        from bot import TavusToolForwarderBot

        bot = TavusToolForwarderBot(
            room_url='https://test.daily.co/test-room',
            bot_id='test-bot-123'
        )

        assert bot.room_url == 'https://test.daily.co/test-room'
        assert bot.bot_id == 'test-bot-123'
        assert bot.session_id == 'test-bot-123'  # Defaults to bot_id
        assert bot.parser is not None
        assert bot.railway_client is not None

    def test_bot_initialization_with_session_id(self, env_vars):
        """Test bot initialization with explicit session_id"""
        from bot import TavusToolForwarderBot

        bot = TavusToolForwarderBot(
            room_url='https://test.daily.co/test-room',
            bot_id='bot-123',
            session_id='session-456'
        )

        assert bot.bot_id == 'bot-123'
        assert bot.session_id == 'session-456'

    def test_bot_requires_daily_api_key(self, monkeypatch):
        """Test that bot initialization fails without DAILY_API_KEY"""
        from bot import TavusToolForwarderBot

        monkeypatch.delenv('DAILY_API_KEY', raising=False)

        with pytest.raises(ValueError, match="DAILY_API_KEY"):
            TavusToolForwarderBot(
                room_url='https://test.daily.co/test',
                bot_id='test-bot'
            )

    def test_bot_loads_environment_variables(self, env_vars):
        """Test that bot loads configuration from environment"""
        from bot import TavusToolForwarderBot

        bot = TavusToolForwarderBot(
            room_url='https://test.daily.co/test',
            bot_id='test-bot'
        )

        assert bot.daily_api_key == 'test-daily-key-12345'
        assert bot.api_base_url == 'https://test.railway.app'  # From env_vars fixture
        assert bot.supabase_url == 'https://test.supabase.co'
        assert bot.supabase_key == 'test-supabase-key'


class TestToolCallParsing:
    """Tests for parsing tool call events"""

    def test_parse_full_generate_deck_call(self, env_vars):
        """Test parsing complete generate_custom_deck tool call"""
        from bot import TavusToolForwarderBot

        bot = TavusToolForwarderBot(
            room_url='https://test.daily.co/test',
            bot_id='test-bot'
        )

        event = MOCK_TOOL_CALL_FULL

        # Test is_tool_call
        assert bot.parser.is_tool_call(event) is True

        # Test get_tool_name
        tool_name = bot.parser.get_tool_name(event)
        assert tool_name == 'generate_custom_deck'

        # Test parse_generate_deck
        args = bot.parser.parse_generate_deck(event)
        assert args is not None
        assert args.company_name == 'Innovative Tech Co'
        assert len(args.pain_points) == 3
        assert len(args.interested_features) == 3

    def test_parse_minimal_generate_deck_call(self, env_vars):
        """Test parsing minimal generate_custom_deck tool call"""
        from bot import TavusToolForwarderBot

        bot = TavusToolForwarderBot(
            room_url='https://test.daily.co/test',
            bot_id='test-bot'
        )

        event = MOCK_TOOL_CALL_MINIMAL

        args = bot.parser.parse_generate_deck(event)
        assert args is not None
        assert args.company_name == 'Minimal Corp'
        assert args.pain_points == []
        assert args.interested_features == []

    def test_parse_control_slide_call(self, env_vars):
        """Test parsing control_slide tool call"""
        from bot import TavusToolForwarderBot

        bot = TavusToolForwarderBot(
            room_url='https://test.daily.co/test',
            bot_id='test-bot'
        )

        event = MOCK_TOOL_CALL_CONTROL_SLIDE

        tool_name = bot.parser.get_tool_name(event)
        assert tool_name == 'control_slide'

        args = bot.parser.parse_control_slide(event)
        assert args is not None
        assert args.command == 'next'

    def test_parser_stats_tracking(self, env_vars):
        """Test that parser tracks statistics"""
        from bot import TavusToolForwarderBot

        bot = TavusToolForwarderBot(
            room_url='https://test.daily.co/test',
            bot_id='test-bot'
        )

        # Parse a few events
        bot.parser.parse_generate_deck(MOCK_TOOL_CALL_FULL)
        bot.parser.parse_generate_deck(MOCK_TOOL_CALL_MINIMAL)

        stats = bot.parser.stats
        assert stats['parse_count'] == 2
        assert stats['error_count'] == 0
        assert stats['success_rate'] == 1.0


class TestRailwayAPIIntegration:
    """Tests for Railway API client integration"""

    @pytest.mark.asyncio
    async def test_generate_deck_success(self, env_vars):
        """Test successful deck generation via Railway API"""
        from bot import TavusToolForwarderBot
        from railway_client import DeckGenerationResponse

        bot = TavusToolForwarderBot(
            room_url='https://test.daily.co/test',
            bot_id='test-bot'
        )

        # Mock the Railway client's _post_with_retry method
        mock_response = {
            'deckId': 'test-deck-123',
            'deckUrl': 'https://buzztrail.github.io/buzztrail-presentations/test-deck-123/',
            'sessionId': 'session-123'
        }

        with patch.object(
            bot.railway_client,
            '_post_with_retry',
            new_callable=AsyncMock,
            return_value=mock_response
        ):
            response = await bot.railway_client.generate_deck(
                company_name='Test Co',
                pain_points=['Issue 1', 'Issue 2'],
                interested_features=['Feature A'],
                conversation_id='conv-test'
            )

            assert isinstance(response, DeckGenerationResponse)
            assert response.deck_id == 'test-deck-123'
            assert response.deck_url == 'https://buzztrail.github.io/buzztrail-presentations/test-deck-123/'
            assert response.session_id == 'session-123'

    @pytest.mark.asyncio
    async def test_spawn_screenshare_bot_success(self, env_vars):
        """Test successful screenshare bot spawning"""
        from bot import TavusToolForwarderBot
        from railway_client import BotSpawnResponse

        bot = TavusToolForwarderBot(
            room_url='https://test.daily.co/test',
            bot_id='test-bot'
        )

        # Mock the Railway client's _post_with_retry method
        mock_response = {
            'bot_id': 'screenshare-bot-456',
            'status': 'spawned',
            'pid': 12345
        }

        with patch.object(
            bot.railway_client,
            '_post_with_retry',
            new_callable=AsyncMock,
            return_value=mock_response
        ):
            response = await bot.railway_client.spawn_screenshare_bot(
                room_url='https://test.daily.co/test',
                deck_url='https://buzztrail.github.io/buzztrail-presentations/test-deck/',
                session_id='session-test'
            )

            assert isinstance(response, BotSpawnResponse)
            assert response.bot_id == 'screenshare-bot-456'
            assert response.status == 'spawned'
            assert response.pid == 12345


class TestEndToEndFlow:
    """Tests for complete end-to-end workflow"""

    @pytest.mark.asyncio
    async def test_complete_generate_deck_flow(self, env_vars, mock_daily_client):
        """Test complete flow from tool call to response"""
        from bot import TavusToolForwarderBot

        bot = TavusToolForwarderBot(
            room_url='https://test.daily.co/test',
            bot_id='test-bot'
        )
        bot.client = mock_daily_client
        bot.loop = asyncio.get_event_loop()

        # Mock Railway API responses
        deck_response = {
            'deckId': 't8on-0e7p-3dou',
            'deckUrl': 'https://buzztrail.github.io/buzztrail-presentations/t8on-0e7p-3dou/',
            'sessionId': 'session-123'
        }

        bot_spawn_response = {
            'bot_id': 'screenshare-bot-789',
            'status': 'spawned',
            'pid': 99999
        }

        with patch.object(
            bot.railway_client,
            '_post_with_retry',
            new_callable=AsyncMock,
            side_effect=[deck_response, bot_spawn_response]
        ):
            # Simulate tool call event
            event = MOCK_TOOL_CALL_FULL

            # Process the tool call
            await bot._handle_generate_deck(event)

            # Verify deck generation occurred
            assert bot.current_deck_id == 't8on-0e7p-3dou'
            assert bot.current_deck_url == 'https://buzztrail.github.io/buzztrail-presentations/t8on-0e7p-3dou/'

            # Verify screenshare bot was spawned
            assert bot.screenshare_bot_id == 'screenshare-bot-789'

            # Verify response was sent back to Tavus
            mock_daily_client.send_app_message.assert_called_once()
            call_args = mock_daily_client.send_app_message.call_args[0][0]
            assert call_args['event_type'] == 'conversation.echo'
            assert 't8on-0e7p-3dou' in call_args['properties']['text']

    @pytest.mark.asyncio
    async def test_on_app_message_routing(self, env_vars, mock_daily_client):
        """Test that on_app_message correctly routes tool calls"""
        from bot import TavusToolForwarderBot

        bot = TavusToolForwarderBot(
            room_url='https://test.daily.co/test',
            bot_id='test-bot'
        )
        bot.client = mock_daily_client
        bot.loop = asyncio.get_event_loop()

        # Mock the async handler
        with patch.object(bot, '_handle_generate_deck', new_callable=AsyncMock) as mock_handler:
            # Simulate receiving tool call
            event = MOCK_TOOL_CALL_FULL

            # Call synchronous handler (which schedules async work)
            bot.on_app_message(event, 'sender-123')

            # Wait for async task to complete
            await asyncio.sleep(0.1)

            # Verify handler was called
            # Note: asyncio.run_coroutine_threadsafe makes this tricky to test
            # In real usage, the handler would be called

    @pytest.mark.asyncio
    async def test_control_slide_flow(self, env_vars):
        """Test control_slide tool call flow"""
        from bot import TavusToolForwarderBot

        bot = TavusToolForwarderBot(
            room_url='https://test.daily.co/test',
            bot_id='test-bot',
            session_id='session-123'
        )

        # Mock Supabase client
        mock_supabase = Mock()
        mock_table = Mock()
        mock_insert = Mock()
        mock_execute = Mock(return_value=Mock(data=[]))

        mock_supabase.table.return_value = mock_table
        mock_table.insert.return_value = mock_insert
        mock_insert.execute = mock_execute

        bot.supabase = mock_supabase

        # Create control_slide event
        event = create_mock_tool_call(
            company_name='ignored'
        )
        event['properties']['name'] = 'control_slide'
        event['properties']['arguments'] = '{"command": "next"}'

        # Process control_slide
        await bot._handle_control_slide(event)

        # Verify Supabase was called
        mock_supabase.table.assert_called_with('slide_control_commands')
        mock_table.insert.assert_called_once()


class TestErrorHandling:
    """Tests for error handling and edge cases"""

    @pytest.mark.asyncio
    async def test_handle_railway_api_error(self, env_vars, mock_daily_client):
        """Test handling Railway API errors"""
        from bot import TavusToolForwarderBot
        from railway_client import RailwayAPIError

        bot = TavusToolForwarderBot(
            room_url='https://test.daily.co/test',
            bot_id='test-bot'
        )
        bot.client = mock_daily_client
        bot.loop = asyncio.get_event_loop()

        # Mock Railway API to raise error
        with patch.object(
            bot.railway_client,
            '_post_with_retry',
            new_callable=AsyncMock,
            side_effect=RailwayAPIError('/api/test', 500, 'Server error')
        ):
            event = MOCK_TOOL_CALL_FULL

            # Should not raise exception (error is logged)
            await bot._handle_generate_deck(event)

            # Verify deck was not set
            assert bot.current_deck_id is None
            assert bot.current_deck_url is None

    @pytest.mark.asyncio
    async def test_handle_invalid_json_arguments(self, env_vars):
        """Test handling tool call with invalid JSON arguments"""
        from bot import TavusToolForwarderBot

        bot = TavusToolForwarderBot(
            room_url='https://test.daily.co/test',
            bot_id='test-bot'
        )

        event = {
            'event_type': 'conversation.tool_call',
            'conversation_id': 'conv-test',
            'properties': {
                'name': 'generate_custom_deck',
                'arguments': '{invalid json}'
            }
        }

        # Should return None (not raise)
        args = bot.parser.parse_generate_deck(event)
        assert args is None

        # Error count should increment
        assert bot.parser.stats['error_count'] > 0

    @pytest.mark.asyncio
    async def test_handle_missing_company_name(self, env_vars):
        """Test handling tool call without required company_name"""
        from bot import TavusToolForwarderBot

        bot = TavusToolForwarderBot(
            room_url='https://test.daily.co/test',
            bot_id='test-bot'
        )

        event = create_mock_tool_call(
            company_name=None
        )

        # Should parse but company_name is None
        args = bot.parser.parse_generate_deck(event)
        assert args is not None
        assert args.company_name is None


class TestSupabaseIntegration:
    """Tests for Supabase state management"""

    @pytest.mark.asyncio
    async def test_update_bot_status(self, env_vars):
        """Test updating bot status in Supabase"""
        from bot import TavusToolForwarderBot

        bot = TavusToolForwarderBot(
            room_url='https://test.daily.co/test',
            bot_id='test-bot'
        )

        # Mock Supabase client
        mock_supabase = Mock()
        mock_table = Mock()
        mock_update = Mock()
        mock_eq = Mock()
        mock_execute = Mock(return_value=Mock(data=[]))

        mock_supabase.table.return_value = mock_table
        mock_table.update.return_value = mock_update
        mock_update.eq.return_value = mock_eq
        mock_eq.execute = mock_execute

        bot.supabase = mock_supabase

        # Update status
        await bot.update_bot_status('running', {'test': 'data'})

        # Verify Supabase was called
        mock_supabase.table.assert_called_with('active_bots')
        mock_table.update.assert_called_once()
        update_call = mock_table.update.call_args[0][0]
        assert update_call['status'] == 'running'
        assert update_call['metadata'] == {'test': 'data'}

    @pytest.mark.asyncio
    async def test_create_conversation_session(self, env_vars):
        """Test creating conversation session record"""
        from bot import TavusToolForwarderBot

        bot = TavusToolForwarderBot(
            room_url='https://test.daily.co/test',
            bot_id='test-bot',
            session_id='session-123'
        )

        # Mock Supabase client
        mock_supabase = Mock()
        mock_table = Mock()
        mock_insert = Mock()
        mock_execute = Mock(return_value=Mock(data=[]))

        mock_supabase.table.return_value = mock_table
        mock_table.insert.return_value = mock_insert
        mock_insert.execute = mock_execute

        bot.supabase = mock_supabase

        # Create session
        await bot.create_conversation_session(
            conversation_id='conv-test',
            deck_id='deck-123',
            deck_url='https://test.url/'
        )

        # Verify Supabase was called
        mock_supabase.table.assert_called_with('conversation_sessions')
        mock_table.insert.assert_called_once()
        insert_call = mock_table.insert.call_args[0][0]
        assert insert_call['conversation_id'] == 'conv-test'
        assert insert_call['deck_id'] == 'deck-123'

    @pytest.mark.asyncio
    async def test_supabase_optional(self, env_vars, monkeypatch):
        """Test bot works without Supabase configured"""
        from bot import TavusToolForwarderBot

        # Remove Supabase env vars
        monkeypatch.delenv('SUPABASE_URL', raising=False)
        monkeypatch.delenv('SUPABASE_SERVICE_KEY', raising=False)

        bot = TavusToolForwarderBot(
            room_url='https://test.daily.co/test',
            bot_id='test-bot'
        )

        # Start Supabase (should log warning)
        await bot.start_supabase()

        # Should be None
        assert bot.supabase is None

        # Update status should not fail
        await bot.update_bot_status('running')


class TestStatisticsTracking:
    """Tests for statistics and metrics tracking"""

    @pytest.mark.asyncio
    async def test_parser_statistics(self, env_vars):
        """Test parser tracks parse attempts and errors"""
        from bot import TavusToolForwarderBot

        bot = TavusToolForwarderBot(
            room_url='https://test.daily.co/test',
            bot_id='test-bot'
        )

        # Parse some events
        bot.parser.parse_generate_deck(MOCK_TOOL_CALL_FULL)
        bot.parser.parse_generate_deck(MOCK_TOOL_CALL_MINIMAL)

        # Parse invalid event
        invalid_event = {
            'event_type': 'conversation.tool_call',
            'conversation_id': 'conv-test',
            'properties': {
                'name': 'generate_custom_deck',
                'arguments': '{invalid}'
            }
        }
        bot.parser.parse_generate_deck(invalid_event)

        stats = bot.parser.stats
        assert stats['parse_count'] == 2
        assert stats['error_count'] == 1
        assert 0 < stats['success_rate'] < 1

    @pytest.mark.asyncio
    async def test_railway_client_statistics(self, env_vars):
        """Test Railway client tracks requests and errors"""
        from bot import TavusToolForwarderBot

        bot = TavusToolForwarderBot(
            room_url='https://test.daily.co/test',
            bot_id='test-bot'
        )

        # Mock successful request with side_effect to track stats
        mock_response = {
            'deckId': 'test-deck',
            'deckUrl': 'https://test.url/'
        }

        async def mock_post_with_stats(*args, **kwargs):
            # Manually increment stats like the real method does
            bot.railway_client.request_count += 1
            return mock_response

        with patch.object(
            bot.railway_client,
            '_post_with_retry',
            new_callable=AsyncMock,
            side_effect=mock_post_with_stats
        ):
            await bot.railway_client.generate_deck(
                company_name='Test Co',
                conversation_id='conv-test'
            )

        stats = bot.railway_client.stats
        assert stats['request_count'] >= 1


class TestLifecycleManagement:
    """Tests for bot lifecycle (startup, shutdown, cleanup)"""

    @pytest.mark.asyncio
    async def test_cleanup_releases_daily_client(self, env_vars, mock_daily_client):
        """Test cleanup properly releases Daily client"""
        from bot import TavusToolForwarderBot

        bot = TavusToolForwarderBot(
            room_url='https://test.daily.co/test',
            bot_id='test-bot'
        )
        bot.client = mock_daily_client

        # Cleanup
        await bot.cleanup()

        # Verify Daily client was cleaned up
        mock_daily_client.leave.assert_called_once()
        mock_daily_client.release.assert_called_once()
        assert bot.is_running is False

    @pytest.mark.asyncio
    async def test_cleanup_updates_supabase_status(self, env_vars, mock_daily_client):
        """Test cleanup updates bot status to 'stopped'"""
        from bot import TavusToolForwarderBot

        bot = TavusToolForwarderBot(
            room_url='https://test.daily.co/test',
            bot_id='test-bot'
        )
        bot.client = mock_daily_client

        # Mock Supabase
        mock_supabase = Mock()
        mock_table = Mock()
        mock_update = Mock()
        mock_eq = Mock()
        mock_execute = Mock(return_value=Mock(data=[]))

        mock_supabase.table.return_value = mock_table
        mock_table.update.return_value = mock_update
        mock_update.eq.return_value = mock_eq
        mock_eq.execute = mock_execute

        bot.supabase = mock_supabase

        # Cleanup
        await bot.cleanup()

        # Verify status was updated to 'stopped'
        mock_table.update.assert_called()
        update_call = mock_table.update.call_args[0][0]
        assert update_call['status'] == 'stopped'
