"""
Comprehensive unit tests for StormMessageFormatter with 100% coverage
"""

import pytest
from unittest.mock import patch, MagicMock
import re

from storm_logger.core.formatters.message_formatter import StormMessageFormatter, storm_formatter


class TestStormMessageFormatter:
    """Test suite for StormMessageFormatter class"""

    @pytest.fixture
    def formatter(self):
        """Create a fresh formatter instance for each test"""
        return StormMessageFormatter()

    def test_init(self, formatter):
        """Test formatter initialization"""
        # Test technology map
        assert formatter.technology_map["django"] == "Django-Spellbook Framework"
        assert formatter.technology_map["midas"] == "MIDAS C-to-WebAssembly"
        
        # Test error patterns
        assert "TemplateDoesNotExist" in formatter.error_patterns
        assert formatter.error_patterns["TemplateDoesNotExist"]["type"] == "UI_COMPONENT"
        
        # Test success patterns
        assert "created" in formatter.success_patterns
        assert isinstance(formatter.success_patterns["created"], list)
        
        # Test metric patterns
        assert "response_time" in formatter.metric_patterns
        assert formatter.metric_patterns["response_time"]["target"] == "< 200ms"

    def test_format_none_message(self, formatter):
        """Test format with None message"""
        assert formatter.format(None) == ""

    def test_format_non_string_message(self, formatter):
        """Test format with non-string message"""
        assert formatter.format(123) == "123"
        assert formatter.format({"key": "value"}) == "{'key': 'value'}"

    def test_format_error_message_by_level(self, formatter):
        """Test format identifies error by level"""
        result = formatter.format("Something went wrong", level="error")
        assert "❌" in result
        assert "Storm Development" in result

    def test_format_error_message_by_pattern(self, formatter):
        """Test format identifies error by pattern"""
        # Test with exception pattern
        result = formatter.format("ValueError: Invalid input")
        assert "❌" in result
        
        # Test with error class name
        result = formatter.format("DoesNotExist: User not found")
        assert "❌" in result
        assert "Database record not found" in result

    def test_format_success_message_by_level(self, formatter):
        """Test format identifies success by level"""
        with patch('random.choice') as mock_choice:
            mock_choice.return_value = "✅ Operation completed: test"
            result = formatter.format("Operation done", level="success")
            assert "✅" in result

    def test_format_success_message_by_indicator(self, formatter):
        """Test format identifies success by indicator"""
        with patch('random.choice') as mock_choice:
            mock_choice.return_value = "Successfully provisioned new business entity"
            result = formatter.format("User created successfully")
            assert "Successfully provisioned" in result

    def test_format_performance_message(self, formatter):
        """Test format identifies and formats performance message"""
        result = formatter.format("Response time: 500ms")
        assert "Performance threshold notification" in result
        
        result = formatter.format("Memory usage high")
        assert "Optimizing resource utilization" in result

    def test_format_security_message(self, formatter):
        """Test format identifies and formats security message"""
        result = formatter.format("Auth token expired")
        assert "Security control notification" in result
        
        result = formatter.format("Unauthorized access attempt")
        assert "Security control notification" in result

    def test_format_business_critical_message(self, formatter):
        """Test format identifies and formats business critical message"""
        result = formatter.format("Payment transaction processing")
        assert "Business-critical event" in result
        assert "revenue operations affected" in result

    def test_format_ux_message(self, formatter):
        """Test format identifies and formats UX message"""
        result = formatter.format("Page load time exceeded")
        assert "User experience notification" in result
        assert "performance enhancements" in result

    def test_format_integration_message(self, formatter):
        """Test format identifies and formats integration message"""
        result = formatter.format("API endpoint integration issue")
        assert "Service integration notification" in result
        assert "external API connectivity" in result

    def test_format_with_stakeholder(self, formatter):
        """Test format with different stakeholders"""
        # Executive stakeholder
        result = formatter.format("System update", stakeholder="executive")
        assert "Strategic implications" in result
        
        # Technical stakeholder
        result = formatter.format("Django configuration", stakeholder="technical")
        assert "Django-Spellbook" in result
        
        # Support stakeholder
        result = formatter.format("User request", stakeholder="support")
        assert "Customer support alert" in result
        
        # Unknown stakeholder
        result = formatter.format("Test message", stakeholder="unknown")
        assert result == "Test message"

    def test_format_metric_message(self, formatter):
        """Test format identifies and formats metric message"""
        result = formatter.format("response_time: 150")
        assert "Response Time" in result
        assert "Client experience optimization" in result

    def test_format_with_technology_transformations(self, formatter):
        """Test technology keyword transformations"""
        result = formatter.format("Using Django for development")
        assert "Django-Spellbook Framework" in result
        
        result = formatter.format("MIDAS optimization complete")
        assert "MIDAS C-to-WebAssembly" in result

    def test_format_with_context(self, formatter):
        """Test format with context"""
        context = {"component": "database"}
        result = formatter.format("Operation complete", context=context)
        assert "Data integrity and storage optimization" in result

    def test_format_test_message_passed(self, formatter):
        """Test format_test_message for passed tests"""
        with patch('random.choice') as mock_choice:
            mock_choice.side_effect = [
                "Quality assurance verified for Test Feature",
                "Meets Storm Development production standards",
                "Ready for client deployment"
            ]
            result = formatter.format_test_message("test_feature", "passed")
            assert result["message"] == "Quality assurance verified for Test Feature"
            assert result["details"] == "Meets Storm Development production standards"
            assert result["recommendation"] == "Ready for client deployment"

    def test_format_test_message_failed(self, formatter):
        """Test format_test_message for failed tests"""
        with patch('random.choice') as mock_choice:
            mock_choice.side_effect = [
                "Quality issue detected in Test Feature",
                "Custom error details",
                "Apply Storm Development best practices for resolution"
            ]
            result = formatter.format_test_message("test_feature", "failed", "Custom error details")
            assert "Quality issue detected" in result["message"]
            assert result["details"] == "Custom error details"
            assert "Storm Development" in result["recommendation"]

    def test_format_test_message_skipped(self, formatter):
        """Test format_test_message for skipped tests"""
        with patch('random.choice') as mock_choice:
            mock_choice.side_effect = [
                "Test deferred for Test Feature",
                "Manual review may be required",
                "Consult Storm Development testing guidelines"
            ]
            result = formatter.format_test_message("test_feature", "skipped")
            assert "Test deferred" in result["message"]
            assert "Manual review" in result["details"]
            assert "testing guidelines" in result["recommendation"]

    def test_format_metric_message_known_metric(self, formatter):
        """Test format_metric_message with known metric"""
        result = formatter.format_metric_message("response_time", "150ms", "< 200ms")
        assert result["name"] == "Response Time"
        assert result["value"] == "150ms"
        assert result["target"] == "< 200ms"
        assert result["business_impact"] == "Client experience optimization"

    def test_format_metric_message_unknown_metric(self, formatter):
        """Test format_metric_message with unknown metric"""
        result = formatter.format_metric_message("custom_metric", "42")
        assert result["name"] == "Custom Metric"
        assert result["value"] == "42"
        assert result["status"] == "measured"

    def test_format_django_spellbook_tip(self, formatter):
        """Test format_django_spellbook_tip"""
        assert "enhanced model patterns" in formatter.format_django_spellbook_tip("model")
        assert "view decorators" in formatter.format_django_spellbook_tip("view")
        assert "markdown-to-magic" in formatter.format_django_spellbook_tip("template")
        assert "10+ years" in formatter.format_django_spellbook_tip("unknown")

    def test_format_midas_optimization(self, formatter):
        """Test format_midas_optimization"""
        assert "10x performance gains" in formatter.format_midas_optimization("performance")
        assert "reduces hosting costs" in formatter.format_midas_optimization("memory")
        assert "native speed" in formatter.format_midas_optimization("speed")
        assert "Revolutionary" in formatter.format_midas_optimization("unknown")

    def test_format_business_recommendation(self, formatter):
        """Test format_business_recommendation"""
        # Customer context
        recs = formatter.format_business_recommendation("customer data", "error")
        assert any("customer" in r for r in recs)
        
        # Invoice context
        recs = formatter.format_business_recommendation("invoice processing", "error")
        assert any("financial" in r.lower() for r in recs)
        
        # Performance issue
        recs = formatter.format_business_recommendation("system", "performance")
        assert any("MIDAS" in r for r in recs)
        
        # Default
        recs = formatter.format_business_recommendation("general", "general")
        assert any("Storm Development" in r for r in recs)

    def test_extract_business_context(self, formatter):
        """Test _extract_business_context"""
        assert formatter._extract_business_context("test_crud_operations") == "Data Management Operations"
        assert formatter._extract_business_context("test_api_endpoint") == "Service Interface Endpoint"
        assert formatter._extract_business_context("test_auth_system") == "Authentication System"

    def test_format_context(self, formatter):
        """Test _format_context"""
        context = {"user_id": 123, "request_id": "abc"}
        result = formatter._format_context(context)
        assert "User Id: 123" in result
        assert "Request Id: abc" in result

    def test_evaluate_metric_status(self, formatter):
        """Test _evaluate_metric_status"""
        assert formatter._evaluate_metric_status("150", "< 200") == "optimal"
        assert formatter._evaluate_metric_status("250", "< 200") == "attention_required"
        assert formatter._evaluate_metric_status("99.95", "> 99.9") == "optimal"
        assert formatter._evaluate_metric_status("99.8", "> 99.9") == "attention_required"
        assert formatter._evaluate_metric_status("100", "<= 100") == "optimal"
        assert formatter._evaluate_metric_status("100", ">= 100") == "optimal"
        assert formatter._evaluate_metric_status("invalid", "< 200") == "measured"
        assert formatter._evaluate_metric_status("100", "N/A") == "measured"

    def test_get_metric_recommendation(self, formatter):
        """Test _get_metric_recommendation"""
        assert "excellence standards" in formatter._get_metric_recommendation("any", "optimal")
        assert "MIDAS optimization" in formatter._get_metric_recommendation("response_time", "attention_required")
        assert "memory-efficient" in formatter._get_metric_recommendation("memory_usage", "attention_required")
        assert "error handling" in formatter._get_metric_recommendation("error_rate", "attention_required")
        assert "reliability standards" in formatter._get_metric_recommendation("uptime", "attention_required")
        assert "Monitor metric" in formatter._get_metric_recommendation("unknown", "attention_required")

    def test_is_error_message(self, formatter):
        """Test _is_error_message"""
        assert formatter._is_error_message("test", level="error")
        assert formatter._is_error_message("ValueError: test")
        assert formatter._is_error_message("CustomError: test")
        assert formatter._is_error_message("DoesNotExist: test")
        assert formatter._is_error_message("An error occurred")
        assert formatter._is_error_message("Operation failed")
        assert formatter._is_error_message("Exception traceback")
        assert not formatter._is_error_message("Success")

    def test_is_success_message(self, formatter):
        """Test _is_success_message"""
        assert formatter._is_success_message("test", level="success")
        assert formatter._is_success_message("Operation successful")
        assert formatter._is_success_message("Task completed")
        assert formatter._is_success_message("User created")
        assert not formatter._is_success_message("Failed")

    def test_is_performance_message(self, formatter):
        """Test _is_performance_message"""
        assert formatter._is_performance_message("Response: 100ms")
        assert formatter._is_performance_message("Took 5 seconds")
        assert formatter._is_performance_message("High latency detected")
        assert formatter._is_performance_message("CPU usage high")
        assert formatter._is_performance_message("Memory exhausted")
        assert formatter._is_performance_message("Connection pool full")

    def test_is_security_message(self, formatter):
        """Test _is_security_message"""
        assert formatter._is_security_message("Auth failed")
        assert formatter._is_security_message("Permission denied")
        assert formatter._is_security_message("Unauthorized access")
        assert formatter._is_security_message("Invalid token")
        assert formatter._is_security_message("CSRF violation")

    def test_is_business_critical_message(self, formatter):
        """Test _is_business_critical_message"""
        assert formatter._is_business_critical_message("Payment failed")
        assert formatter._is_business_critical_message("Revenue report")
        assert formatter._is_business_critical_message("Customer data")
        assert formatter._is_business_critical_message("Order processing")
        assert formatter._is_business_critical_message("Backup failed")
        assert formatter._is_business_critical_message("Data corruption detected")
        assert formatter._is_business_critical_message("Service unavailable")

    def test_is_ux_message(self, formatter):
        """Test _is_ux_message"""
        assert formatter._is_ux_message("Page load slow")
        assert formatter._is_ux_message("Render error")
        assert formatter._is_ux_message("UI broken")
        assert formatter._is_ux_message("Interface issue")
        assert formatter._is_ux_message("Form validation")
        assert formatter._is_ux_message("Mobile view")
        assert formatter._is_ux_message("Not responsive")
        assert formatter._is_ux_message("Accessibility issue")
        assert formatter._is_ux_message("Session expired")

    def test_is_integration_message(self, formatter):
        """Test _is_integration_message"""
        assert formatter._is_integration_message("API error")
        assert formatter._is_integration_message("Webhook failed")
        assert formatter._is_integration_message("Sync issue")
        assert formatter._is_integration_message("External service")
        assert formatter._is_integration_message("Third-party error")
        assert formatter._is_integration_message("Queue full")
        assert formatter._is_integration_message("Integration failed")

    def test_is_metric_message(self, formatter):
        """Test _is_metric_message"""
        assert formatter._is_metric_message("response_time: 150")
        assert formatter._is_metric_message("Usage: 85.5%")
        assert formatter._is_metric_message("Memory: 256MB")
        assert formatter._is_metric_message("Processed 1000ms")
        assert not formatter._is_metric_message("Simple message")

    def test_format_performance_message_slow(self, formatter):
        """Test _format_performance_message with slow/timeout"""
        result = formatter._format_performance_message("Operation slow")
        assert "Performance threshold notification" in result
        assert "MIDAS WebAssembly acceleration" in result

    def test_format_performance_message_memory(self, formatter):
        """Test _format_performance_message with memory"""
        result = formatter._format_performance_message("Memory usage high")
        assert "Optimizing resource utilization" in result

    def test_format_performance_message_cpu(self, formatter):
        """Test _format_performance_message with CPU"""
        result = formatter._format_performance_message("CPU usage spike")
        assert "performance optimization patterns" in result

    def test_format_security_message_permission(self, formatter):
        """Test _format_security_message with permission"""
        result = formatter._format_security_message("Permission check failed")
        assert "Security control notification" in result
        assert "Storm Dashboard access control" in result

    def test_format_security_message_auth(self, formatter):
        """Test _format_security_message with auth"""
        result = formatter._format_security_message("Auth token invalid")
        assert "authentication best practices" in result

    def test_format_business_critical_payment(self, formatter):
        """Test _format_business_critical_message with payment"""
        result = formatter._format_business_critical_message("Payment processing error")
        assert "Business-critical event" in result
        assert "revenue operations affected" in result

    def test_format_business_critical_customer(self, formatter):
        """Test _format_business_critical_message with customer"""
        result = formatter._format_business_critical_message("Customer data issue")
        assert "Customer experience impact" in result

    def test_format_business_critical_unavailable(self, formatter):
        """Test _format_business_critical_message with unavailable"""
        result = formatter._format_business_critical_message("Service unavailable")
        assert "business operations affected" in result

    def test_format_ux_message_render(self, formatter):
        """Test _format_ux_message with render/interface"""
        result = formatter._format_ux_message("Render error in interface")
        assert "User experience notification" in result
        assert "Storm Animation System" in result

    def test_format_ux_message_load(self, formatter):
        """Test _format_ux_message with load"""
        result = formatter._format_ux_message("Page load time high")
        assert "performance enhancements" in result

    def test_format_integration_message_api(self, formatter):
        """Test _format_integration_message with API"""
        result = formatter._format_integration_message("API connection failed")
        assert "Service integration notification" in result
        assert "external API connectivity" in result

    def test_format_integration_message_sync(self, formatter):
        """Test _format_integration_message with sync"""
        result = formatter._format_integration_message("Data sync error")
        assert "data synchronization" in result

    def test_format_for_stakeholder_executive(self, formatter):
        """Test _format_for_stakeholder with executive"""
        result = formatter._format_for_stakeholder("System issue", "executive")
        assert "Strategic implications" in result

    def test_format_for_stakeholder_technical_django(self, formatter):
        """Test _format_for_stakeholder with technical and django"""
        result = formatter._format_for_stakeholder("Django model error", "technical")
        assert "Django-Spellbook" in result

    def test_format_for_stakeholder_technical_other(self, formatter):
        """Test _format_for_stakeholder with technical non-django"""
        result = formatter._format_for_stakeholder("General error", "technical")
        assert "Technical optimization" in result

    def test_format_for_stakeholder_support(self, formatter):
        """Test _format_for_stakeholder with support"""
        result = formatter._format_for_stakeholder("User problem", "support")
        assert "Customer support alert" in result
        assert "rapid resolution" in result

    def test_format_metric_from_message_known(self, formatter):
        """Test _format_metric_from_message with known metric"""
        result = formatter._format_metric_from_message("response_time: 150")
        assert "Response Time: 150" in result
        assert "Client experience optimization" in result

    def test_format_metric_from_message_unknown(self, formatter):
        """Test _format_metric_from_message with unknown metric"""
        result = formatter._format_metric_from_message("custom_metric: 42")
        assert "Business metric custom_metric: 42" in result
        assert "performance optimization" in result

    def test_format_metric_from_message_no_match(self, formatter):
        """Test _format_metric_from_message with no metric"""
        result = formatter._format_metric_from_message("No metrics here")
        assert result == "No metrics here"

    def test_apply_technology_transformations(self, formatter):
        """Test _apply_technology_transformations"""
        result = formatter._apply_technology_transformations("Using django and midas")
        assert "Django-Spellbook Framework" in result
        assert "MIDAS C-to-WebAssembly" in result

    def test_apply_technology_transformations_case_insensitive(self, formatter):
        """Test _apply_technology_transformations is case insensitive"""
        result = formatter._apply_technology_transformations("DJANGO and MiDaS")
        assert "Django-Spellbook Framework" in result
        assert "MIDAS C-to-WebAssembly" in result

    def test_apply_context_formatting_database(self, formatter):
        """Test _apply_context_formatting with database component"""
        result = formatter._apply_context_formatting("Test", {"component": "database"})
        assert "Data integrity and storage optimization" in result

    def test_apply_context_formatting_api(self, formatter):
        """Test _apply_context_formatting with api component"""
        result = formatter._apply_context_formatting("Test", {"component": "api"})
        assert "Service endpoint integration" in result

    def test_apply_context_formatting_auth(self, formatter):
        """Test _apply_context_formatting with auth component"""
        result = formatter._apply_context_formatting("Test", {"component": "auth"})
        assert "Security and access control" in result

    def test_apply_context_formatting_payment(self, formatter):
        """Test _apply_context_formatting with payment component"""
        result = formatter._apply_context_formatting("Test", {"component": "payment"})
        assert "Financial transaction processing" in result

    def test_apply_context_formatting_unknown(self, formatter):
        """Test _apply_context_formatting with unknown component"""
        result = formatter._apply_context_formatting("Test message", {"component": "unknown"})
        assert result == "Test message"

    def test_add_business_impact_downtime(self, formatter):
        """Test _add_business_impact with downtime"""
        result = formatter._add_business_impact("System downtime detected")
        assert "Business operations disruption" in result

    def test_add_business_impact_revenue(self, formatter):
        """Test _add_business_impact with revenue"""
        result = formatter._add_business_impact("Revenue loss: $1000")
        assert "Financial impact detected" in result

    def test_add_business_impact_customer(self, formatter):
        """Test _add_business_impact with customer"""
        result = formatter._add_business_impact("Customer complaint received")
        assert "Customer satisfaction impact" in result

    def test_add_business_impact_performance(self, formatter):
        """Test _add_business_impact with performance"""
        result = formatter._add_business_impact("Performance degradation")
        assert "Operational efficiency concern" in result

    def test_add_business_impact_default(self, formatter):
        """Test _add_business_impact default"""
        result = formatter._add_business_impact("Generic message")
        assert "Business event" in result

    def test_apply_custom_patterns(self, formatter):
        """Test _apply_custom_patterns"""
        # Add custom pattern
        formatter.custom_patterns = [(re.compile(r"foo"), "bar")]
        result = formatter._apply_custom_patterns("Replace foo with something")
        assert result == "Replace bar with something"

    def test_apply_custom_patterns_no_patterns(self, formatter):
        """Test _apply_custom_patterns without patterns"""
        result = formatter._apply_custom_patterns("No patterns to apply")
        assert result == "No patterns to apply"

    def test_add_pattern_simple(self, formatter):
        """Test add_pattern with simple replacement"""
        formatter.add_pattern(r"test", "replaced")
        assert hasattr(formatter, 'custom_patterns')
        assert len(formatter.custom_patterns) == 1

    def test_add_pattern_error_type(self, formatter):
        """Test add_pattern with error type"""
        formatter.add_pattern("CustomError", None, "error", {"message": "Custom error occurred"})
        assert "CustomError" in formatter.error_patterns

    def test_add_pattern_success_type(self, formatter):
        """Test add_pattern with success type"""
        formatter.add_pattern("custom_action", None, "success", ["Custom success"])
        assert "custom_action" in formatter.success_patterns

    def test_add_pattern_metric_type(self, formatter):
        """Test add_pattern with metric type"""
        formatter.add_pattern("custom_metric", None, "metric", {"name": "Custom Metric"})
        assert "custom_metric" in formatter.metric_patterns

    def test_add_pattern_invalid_type(self, formatter):
        """Test add_pattern with invalid type"""
        with pytest.raises(ValueError, match="Unknown pattern type"):
            formatter.add_pattern("pattern", None, "invalid_type")

    def test_add_pattern_no_params(self, formatter):
        """Test add_pattern with no valid params"""
        with pytest.raises(ValueError, match="Either replacement or pattern_type"):
            formatter.add_pattern("pattern")

    def test_format_success_message_with_action(self, formatter):
        """Test format_success_message with known action"""
        with patch('random.choice') as mock_choice:
            mock_choice.return_value = "✅ Business entity created: Test Item"
            result = formatter.format_success_message("created", {"item": "Test Item"})
            assert "Business entity created" in result

    def test_format_success_message_with_context(self, formatter):
        """Test format_success_message with context"""
        with patch('random.choice') as mock_choice:
            mock_choice.return_value = "Test message"
            result = formatter.format_success_message("created", {"key1": "value1", "key2": "value2"})
            assert "Key1: value1" in result
            assert "Key2: value2" in result

    def test_format_success_message_unknown_action(self, formatter):
        """Test format_success_message with unknown action"""
        result = formatter.format_success_message("unknown_action")
        assert "Operation completed" in result

    def test_format_error_message_known_type(self, formatter):
        """Test format_error_message with known error type"""
        result = formatter.format_error_message("DoesNotExist", "User not found", {"model": "User"})
        assert "Resource not found" in result

    def test_format_error_message_unknown_type(self, formatter):
        """Test format_error_message with unknown error type"""
        result = formatter.format_error_message("UnknownError", "Something wrong")
        assert "Error: Something wrong" in result

    def test_format_error_message_non_string(self, formatter):
        """Test format_error_message with non-string message"""
        result = formatter.format_error_message("Error", 123)
        assert "123" in result

    def test_format_message(self, formatter):
        """Test format_message delegates to format"""
        with patch.object(formatter, 'format') as mock_format:
            mock_format.return_value = "Formatted"
            result = formatter.format_message("Test", level="info")
            mock_format.assert_called_once_with("Test", level="info")
            assert result == "Formatted"

    def test_format_error_with_exception_object(self, formatter):
        """Test format_error with Exception object"""
        exc = ValueError("Test error")
        result = formatter.format_error(exc)
        assert "❌" in result
        assert "System exception detected in ValueError" in result

    def test_format_error_with_known_pattern(self, formatter):
        """Test format_error with known error pattern"""
        result = formatter.format_error("DoesNotExist: Record not found")
        assert "Database record not found" in result
        assert "Django-Spellbook best practices" in result

    def test_format_error_with_string(self, formatter):
        """Test format_error with string message"""
        result = formatter.format_error("Generic error message")
        assert "Business process exception" in result
        assert "error resolution protocols" in result

    def test_format_success_with_action_keyword(self, formatter):
        """Test format_success with action keyword"""
        with patch('random.choice') as mock_choice:
            mock_choice.return_value = "Successfully provisioned new business entity"
            result = formatter.format_success("Entity created successfully")
            assert "Successfully provisioned" in result

    def test_format_success_default(self, formatter):
        """Test format_success with default message"""
        with patch('random.choice') as mock_choice:
            mock_choice.return_value = "✅ Operation completed: Test operation"
            result = formatter.format_success("Test operation")
            assert "✅ Operation completed" in result

    def test_storm_formatter_singleton(self):
        """Test storm_formatter singleton instance"""
        assert isinstance(storm_formatter, StormMessageFormatter)
        assert storm_formatter.technology_map["django"] == "Django-Spellbook Framework"

    def test_evaluate_metric_status_edge_cases(self, formatter):
        """Test _evaluate_metric_status with edge cases"""
        # Test with <= operator boundary
        assert formatter._evaluate_metric_status("101", "<= 100") == "attention_required"
        
        # Test with >= operator boundary  
        assert formatter._evaluate_metric_status("99", ">= 100") == "attention_required"

    def test_format_error_with_custom_exception(self, formatter):
        """Test format_error with custom exception type"""
        class CustomException(Exception):
            pass
        
        exc = CustomException("Custom error")
        result = formatter.format_error(exc)
        assert "Business process exception" in result

    def test_format_success_edge_cases(self, formatter):
        """Test format_success edge cases"""
        # Test with action not in patterns
        with patch('random.choice') as mock_choice:
            mock_choice.return_value = "✅ Operation completed: test"
            result = formatter.format_success("Some other message")
            assert "✅ Operation completed" in result


    def test_format_test_message_no_details(self, formatter):
        """Test format_test_message failed without details"""
        with patch('random.choice') as mock_choice:
            mock_choice.side_effect = [
                "Quality issue detected in Test",
                "Review required before production deployment",
                "Apply Storm Development best practices"
            ]
            result = formatter.format_test_message("test", "failed", None)
            assert result["details"] == "Review required before production deployment"

    def test_format_django_spellbook_tip_coverage(self, formatter):
        """Test all django spellbook tips"""
        assert "form wizardry" in formatter.format_django_spellbook_tip("form")
        assert "admin enhancements" in formatter.format_django_spellbook_tip("admin")

    def test_format_midas_optimization_coverage(self, formatter):
        """Test all midas optimizations"""
        assert "complex calculations" in formatter.format_midas_optimization("calculation")
        assert "60fps" in formatter.format_midas_optimization("animation")

    def test_format_business_recommendation_no_match(self, formatter):
        """Test format_business_recommendation with no specific match"""
        recs = formatter.format_business_recommendation("unknown", "unknown")
        assert len(recs) > 0
        assert any("Storm Development" in r for r in recs)