"""
Unit tests for tool call parsing and validation

Tests the bot's ability to:
- Parse Tavus tool call events
- Extract arguments from JSON strings
- Validate required fields
- Handle malformed input
- Filter irrelevant events

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

import pytest
import json
from unittest.mock import Mock, patch, AsyncMock
from tests.mocks import (
    MOCK_TOOL_CALL_FULL,
    MOCK_TOOL_CALL_MINIMAL,
    MOCK_TOOL_CALL_INVALID_JSON,
    MOCK_TOOL_CALL_CONTROL_SLIDE,
    MOCK_EVENT_CONVERSATION_MESSAGE,
    MOCK_TOOL_CALL_EMPTY_ARGS,
    create_mock_tool_call
)


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

    def test_parse_full_tool_call(self):
        """Test parsing a complete tool call with all fields"""
        event = MOCK_TOOL_CALL_FULL

        # Extract fields
        event_type = event.get('event_type')
        conversation_id = event.get('conversation_id')
        properties = event.get('properties', {})
        tool_name = properties.get('name')
        arguments_str = properties.get('arguments', '{}')

        # Validate
        assert event_type == 'conversation.tool_call'
        assert conversation_id == 'conv-full-test-12345'
        assert tool_name == 'generate_custom_deck'

        # Parse arguments
        arguments = json.loads(arguments_str)
        assert arguments['company_name'] == 'Innovative Tech Co'
        assert len(arguments['pain_points']) == 3
        assert len(arguments['interested_features']) == 3
        assert arguments['industry'] == 'Enterprise Software'
        assert arguments['team_size'] == '100-500'
        assert arguments['budget_range'] == '$50k-$100k'

    def test_parse_minimal_tool_call(self):
        """Test parsing a tool call with only required fields"""
        event = MOCK_TOOL_CALL_MINIMAL

        event_type = event.get('event_type')
        properties = event.get('properties', {})
        arguments_str = properties.get('arguments', '{}')

        assert event_type == 'conversation.tool_call'

        arguments = json.loads(arguments_str)
        assert arguments['company_name'] == 'Minimal Corp'

        # Optional fields may not exist
        assert 'pain_points' not in arguments or arguments['pain_points'] is None

    def test_parse_empty_arguments(self):
        """Test parsing a tool call with empty arguments object"""
        event = MOCK_TOOL_CALL_EMPTY_ARGS

        properties = event.get('properties', {})
        arguments_str = properties.get('arguments', '{}')

        arguments = json.loads(arguments_str)
        assert isinstance(arguments, dict)
        assert len(arguments) == 0

    def test_invalid_json_raises_error(self):
        """Test that malformed JSON arguments raise JSONDecodeError"""
        event = MOCK_TOOL_CALL_INVALID_JSON

        properties = event.get('properties', {})
        arguments_str = properties.get('arguments', '{}')

        with pytest.raises(json.JSONDecodeError):
            json.loads(arguments_str)

    def test_missing_properties_field(self):
        """Test handling of event without properties field"""
        event = {
            'event_type': 'conversation.tool_call',
            'conversation_id': 'conv-test'
            # Missing 'properties' field
        }

        properties = event.get('properties', {})
        assert properties == {}

        tool_name = properties.get('name')
        assert tool_name is None

    def test_missing_arguments_field(self):
        """Test handling of tool call without arguments field"""
        event = {
            'event_type': 'conversation.tool_call',
            'conversation_id': 'conv-test',
            'properties': {
                'name': 'generate_custom_deck'
                # Missing 'arguments' field
            }
        }

        properties = event.get('properties', {})
        arguments_str = properties.get('arguments', '{}')

        # Should default to empty object
        arguments = json.loads(arguments_str)
        assert arguments == {}

    def test_extract_company_name(self):
        """Test extracting company_name from arguments"""
        event = create_mock_tool_call(
            company_name="Acme Corporation",
            conversation_id="conv-test"
        )

        properties = event.get('properties', {})
        arguments = json.loads(properties.get('arguments', '{}'))

        company_name = arguments.get('company_name')
        assert company_name == "Acme Corporation"

    def test_extract_pain_points_list(self):
        """Test extracting pain_points as a list"""
        event = create_mock_tool_call(
            company_name="Test Co",
            pain_points=["Issue 1", "Issue 2", "Issue 3"],
            conversation_id="conv-test"
        )

        properties = event.get('properties', {})
        arguments = json.loads(properties.get('arguments', '{}'))

        pain_points = arguments.get('pain_points', [])
        assert isinstance(pain_points, list)
        assert len(pain_points) == 3
        assert "Issue 1" in pain_points

    def test_extract_interested_features_list(self):
        """Test extracting interested_features as a list"""
        event = create_mock_tool_call(
            company_name="Test Co",
            interested_features=["Feature A", "Feature B"],
            conversation_id="conv-test"
        )

        properties = event.get('properties', {})
        arguments = json.loads(properties.get('arguments', '{}'))

        features = arguments.get('interested_features', [])
        assert isinstance(features, list)
        assert len(features) == 2
        assert "Feature A" in features

    def test_extract_optional_fields(self):
        """Test extracting optional fields (industry, team_size, budget_range)"""
        event = create_mock_tool_call(
            company_name="Test Co",
            industry="FinTech",
            team_size="50-100",
            budget_range="$10k-$50k",
            conversation_id="conv-test"
        )

        properties = event.get('properties', {})
        arguments = json.loads(properties.get('arguments', '{}'))

        assert arguments.get('industry') == "FinTech"
        assert arguments.get('team_size') == "50-100"
        assert arguments.get('budget_range') == "$10k-$50k"


class TestEventFiltering:
    """Tests for filtering relevant tool call events"""

    def test_filter_correct_event_type(self):
        """Test that conversation.tool_call events pass filter"""
        event = MOCK_TOOL_CALL_FULL

        event_type = event.get('event_type')
        assert event_type == 'conversation.tool_call'

    def test_filter_ignore_message_events(self):
        """Test that conversation.message events are filtered out"""
        event = MOCK_EVENT_CONVERSATION_MESSAGE

        event_type = event.get('event_type')
        assert event_type != 'conversation.tool_call'
        assert event_type == 'conversation.message'

    def test_filter_correct_tool_name(self):
        """Test that generate_custom_deck tool calls pass filter"""
        event = MOCK_TOOL_CALL_FULL

        properties = event.get('properties', {})
        tool_name = properties.get('name')

        assert tool_name == 'generate_custom_deck'

    def test_filter_ignore_other_tools(self):
        """Test that other tool calls are filtered out"""
        event = MOCK_TOOL_CALL_CONTROL_SLIDE

        properties = event.get('properties', {})
        tool_name = properties.get('name')

        assert tool_name != 'generate_custom_deck'
        assert tool_name == 'control_slide'

    def test_filter_missing_tool_name(self):
        """Test handling of tool call without tool name"""
        event = {
            'event_type': 'conversation.tool_call',
            'conversation_id': 'conv-test',
            'properties': {
                'arguments': '{"test": "data"}'
                # Missing 'name' field
            }
        }

        properties = event.get('properties', {})
        tool_name = properties.get('name')

        assert tool_name is None

    def test_combined_filter_logic(self):
        """Test combined filter: event_type AND tool_name"""
        # Should pass: correct event type AND tool name
        valid_event = MOCK_TOOL_CALL_FULL
        assert valid_event.get('event_type') == 'conversation.tool_call'
        assert valid_event.get('properties', {}).get('name') == 'generate_custom_deck'

        # Should fail: wrong event type
        wrong_type = MOCK_EVENT_CONVERSATION_MESSAGE
        assert wrong_type.get('event_type') != 'conversation.tool_call'

        # Should fail: wrong tool name
        wrong_tool = MOCK_TOOL_CALL_CONTROL_SLIDE
        assert wrong_tool.get('properties', {}).get('name') != 'generate_custom_deck'


class TestArgumentValidation:
    """Tests for validating tool call arguments"""

    def test_validate_required_company_name(self):
        """Test that company_name is present and not empty"""
        event = create_mock_tool_call(
            company_name="Valid Company",
            conversation_id="conv-test"
        )

        properties = event.get('properties', {})
        arguments = json.loads(properties.get('arguments', '{}'))

        company_name = arguments.get('company_name')
        assert company_name is not None
        assert len(company_name) > 0

    def test_validate_missing_company_name(self):
        """Test handling when company_name is missing"""
        event = {
            'event_type': 'conversation.tool_call',
            'conversation_id': 'conv-test',
            'properties': {
                'name': 'generate_custom_deck',
                'arguments': '{"pain_points": ["Issue 1"]}'
            }
        }

        properties = event.get('properties', {})
        arguments = json.loads(properties.get('arguments', '{}'))

        company_name = arguments.get('company_name')
        assert company_name is None

    def test_validate_empty_company_name(self):
        """Test handling when company_name is empty string"""
        event = create_mock_tool_call(
            company_name="",
            conversation_id="conv-test"
        )

        properties = event.get('properties', {})
        arguments = json.loads(properties.get('arguments', '{}'))

        company_name = arguments.get('company_name')
        assert company_name == ""
        assert len(company_name) == 0

    def test_validate_lists_are_lists(self):
        """Test that list fields are actually lists"""
        event = create_mock_tool_call(
            company_name="Test Co",
            pain_points=["Issue 1", "Issue 2"],
            interested_features=["Feature A"],
            conversation_id="conv-test"
        )

        properties = event.get('properties', {})
        arguments = json.loads(properties.get('arguments', '{}'))

        pain_points = arguments.get('pain_points', [])
        features = arguments.get('interested_features', [])

        assert isinstance(pain_points, list)
        assert isinstance(features, list)

    def test_validate_optional_fields_can_be_none(self):
        """Test that optional fields can be None or missing"""
        event = create_mock_tool_call(
            company_name="Test Co",
            conversation_id="conv-test"
        )

        properties = event.get('properties', {})
        arguments = json.loads(properties.get('arguments', '{}'))

        # These should be None or missing
        industry = arguments.get('industry')
        team_size = arguments.get('team_size')
        budget_range = arguments.get('budget_range')

        # All should be None (not present in mock)
        assert industry is None
        assert team_size is None
        assert budget_range is None


class TestConversationIdExtraction:
    """Tests for extracting conversation_id from events"""

    def test_extract_conversation_id(self):
        """Test extracting conversation_id from event"""
        event = MOCK_TOOL_CALL_FULL

        conversation_id = event.get('conversation_id')
        assert conversation_id == 'conv-full-test-12345'
        assert len(conversation_id) > 0

    def test_missing_conversation_id(self):
        """Test handling when conversation_id is missing"""
        event = {
            'event_type': 'conversation.tool_call',
            'properties': {
                'name': 'generate_custom_deck',
                'arguments': '{"company_name": "Test"}'
            }
        }

        conversation_id = event.get('conversation_id')
        assert conversation_id is None

    def test_empty_conversation_id(self):
        """Test handling when conversation_id is empty string"""
        event = {
            'event_type': 'conversation.tool_call',
            'conversation_id': '',
            'properties': {
                'name': 'generate_custom_deck',
                'arguments': '{"company_name": "Test"}'
            }
        }

        conversation_id = event.get('conversation_id')
        assert conversation_id == ''
        assert len(conversation_id) == 0


class TestEdgeCases:
    """Tests for edge cases and unusual input"""

    def test_unicode_in_company_name(self):
        """Test handling Unicode characters in company name"""
        event = create_mock_tool_call(
            company_name="Café René & Associates Ltd.",
            conversation_id="conv-test"
        )

        properties = event.get('properties', {})
        arguments = json.loads(properties.get('arguments', '{}'))

        company_name = arguments.get('company_name')
        assert 'Café' in company_name
        assert '&' in company_name

    def test_very_long_company_name(self):
        """Test handling very long company name"""
        long_name = "A" * 1000

        event = create_mock_tool_call(
            company_name=long_name,
            conversation_id="conv-test"
        )

        properties = event.get('properties', {})
        arguments = json.loads(properties.get('arguments', '{}'))

        company_name = arguments.get('company_name')
        assert len(company_name) == 1000

    def test_many_pain_points(self):
        """Test handling many pain points"""
        many_pain_points = [f"Pain point {i}" for i in range(50)]

        event = create_mock_tool_call(
            company_name="Test Co",
            pain_points=many_pain_points,
            conversation_id="conv-test"
        )

        properties = event.get('properties', {})
        arguments = json.loads(properties.get('arguments', '{}'))

        pain_points = arguments.get('pain_points', [])
        assert len(pain_points) == 50

    def test_special_characters_in_arguments(self):
        """Test handling special characters in arguments"""
        event = create_mock_tool_call(
            company_name='Test "Company" <Inc>',
            pain_points=["Issue with 'quotes'", "Issue with <brackets>"],
            conversation_id="conv-test"
        )

        properties = event.get('properties', {})
        arguments = json.loads(properties.get('arguments', '{}'))

        company_name = arguments.get('company_name')
        pain_points = arguments.get('pain_points', [])

        assert '"' in company_name
        assert '<' in company_name
        assert "'" in pain_points[0]

    def test_nested_json_in_arguments(self):
        """Test that arguments are not double-encoded"""
        # This tests that arguments is a JSON string, not nested JSON
        event = MOCK_TOOL_CALL_FULL

        properties = event.get('properties', {})
        arguments_str = properties.get('arguments', '{}')

        # Should be able to parse once
        arguments = json.loads(arguments_str)
        assert isinstance(arguments, dict)

        # company_name should be a string, not JSON
        company_name = arguments.get('company_name')
        assert isinstance(company_name, str)
        assert not company_name.startswith('{')
