"""
Storm Development Professional Message Formatter
Business-oriented messaging for Storm Development systems
"""

import re
from typing import Any

from storm_logger.interfaces import FormatterInterface


class StormMessageFormatter(FormatterInterface):
    """
    Professional message formatter for Storm Development
    Transforms technical messages into business-oriented language
    """

    def __init__(self) -> None:
        # Storm Development technology references
        self.technology_map = {
            "django": "Django-Spellbook Framework",
            "midas": "MIDAS C-to-WebAssembly",
            "animation": "Storm Animation System",
            "dashboard": "Storm Development Dashboard",
            "hosting": "Storm Hosting Infrastructure",
        }

        # Business-oriented error patterns
        self.error_patterns = {
            # UI/UX issues (prioritized for specific matching)
            r"TemplateDoesNotExist": {
                "type": "UI_COMPONENT",
                "message": "UI component not found in template hierarchy",
                "guidance": "Reviewing Storm Animation System component architecture",
                "technology": "animation",
            },
            r"NoReverseMatch": {
                "type": "NAVIGATION_ROUTING",
                "message": "Navigation routing configuration issue",
                "guidance": "Implementing Storm Development URL patterns",
                "technology": "django",
            },
            # Django/Model errors
            r"DoesNotExist": {
                "type": "DATA_INTEGRITY",
                "message": "Database record not found - reviewing data architecture",
                "guidance": "Implementing Django-Spellbook best practices for data consistency",
                "technology": "django",
            },
            r"IntegrityError": {
                "type": "DATABASE_CONSTRAINT",
                "message": "Database constraint violation detected",
                "guidance": "Ensuring data integrity for $50 website quality standards",
                "technology": "django",
            },
            r"ValidationError": {
                "type": "BUSINESS_VALIDATION",
                "message": "Business rule validation failure",
                "guidance": "Applying Storm Development validation patterns",
                "technology": "business",
            },
            # Performance issues
            r"TimeoutError|timeout|timed out": {
                "type": "PERFORMANCE_THRESHOLD",
                "message": "Performance threshold exceeded",
                "guidance": "Optimizing with MIDAS WebAssembly acceleration",
                "technology": "midas",
            },
            r"MemoryError": {
                "type": "RESOURCE_OPTIMIZATION",
                "message": "Resource optimization required for memory management",
                "guidance": "Implementing MIDAS memory-efficient patterns",
                "technology": "midas",
            },
            # Business logic
            r"PermissionDenied": {
                "type": "ACCESS_CONTROL",
                "message": "Business access control restriction",
                "guidance": "Reviewing Storm Dashboard permission hierarchy",
                "technology": "dashboard",
            },
            r"Http404": {
                "type": "RESOURCE_LOCATION",
                "message": "Business resource not accessible",
                "guidance": "Verifying Storm Development resource mapping",
                "technology": "django",
            },
        }

        # Professional success patterns with variety
        self.success_patterns = {
            "created": [
                "Successfully provisioned new business entity",
                "Excellent! Business resource created with Storm Development standards",
                "Outstanding! New entity established in production environment",
                "Resource initialization completed successfully",
            ],
            "updated": [
                "Business data synchronized successfully",
                "Resource updated successfully with enhanced functionality",
                "Excellent! Data synchronization completed with Storm standards",
                "Business logic updated successfully to current specifications",
            ],
            "deleted": [
                "Resource decommissioned per business rules",
                "Entity removed following Storm Development protocols",
                "Resource cleanup completed successfully",
                "Business data archived according to retention policy",
            ],
            "saved": [
                "Data persisted to Storm Development infrastructure",
                "Information securely stored in production database",
                "Business data committed to persistent storage",
                "Resource state synchronized with data layer",
            ],
            "validated": [
                "Business validation completed - all checks passed",
                "Data integrity verified against Storm Development standards",
                "Quality assurance validation successful",
                "Business rules compliance confirmed",
            ],
            "deployed": [
                "Successfully deployed to Storm Hosting platform",
                "Production deployment completed with zero downtime",
                "Resource activation completed on Storm infrastructure",
                "Business service launched successfully",
            ],
            "optimized": [
                "Performance optimized with MIDAS acceleration",
                "System efficiency enhanced through Storm Development patterns",
                "Resource utilization improved for optimal performance",
                "Performance tuning completed with measurable improvements",
            ],
        }

        # Business metric patterns
        self.metric_patterns = {
            "response_time": {
                "name": "Response Time",
                "target": "< 200ms",
                "business_impact": "Client experience optimization",
            },
            "memory_usage": {
                "name": "Memory Utilization",
                "target": "< 100MB",
                "business_impact": "Hosting efficiency for $10/month service",
            },
            "error_rate": {
                "name": "Error Rate",
                "target": "< 0.1%",
                "business_impact": "$50 website quality assurance",
            },
            "uptime": {
                "name": "System Uptime",
                "target": "> 99.9%",
                "business_impact": "Storm Hosting reliability guarantee",
            },
        }

    def format(
        self,
        message: str,
        level: str | None = None,
        context: dict[str, Any] | None = None,
        **kwargs: Any,
    ) -> str:
        """
        General purpose formatting method that intelligently transforms messages
        into business-oriented language based on content and context.

        Args:
            message: The original message string.
            level: Optional string indicating the log level (e.g., "info", "error", "success").
            context: Optional dictionary for additional context (e.g., component, user_id).
            **kwargs: Additional keyword arguments.

        Returns:
            A professionally formatted, business-oriented message.
        """
        if message is None:
            message = ""  # type: ignore[unreachable]
        elif not isinstance(message, str):
            message = str(message)  # type: ignore[unreachable]

        # Extract stakeholder if provided
        stakeholder = kwargs.get("stakeholder")

        # Define message type handlers in priority order
        from collections.abc import Callable

        formatters: list[tuple[Callable[[], bool], Callable[[], str]]] = [
            (
                lambda: self._is_error_message(message, level),
                lambda: self.format_error(message, **kwargs),
            ),
            (
                lambda: self._is_success_message(message, level),
                lambda: self.format_success(message, **kwargs),
            ),
            (
                lambda: self._is_performance_message(message),
                lambda: self._format_performance_message(message, context),
            ),
            (
                lambda: self._is_security_message(message),
                lambda: self._format_security_message(message, context),
            ),
            (
                lambda: self._is_business_critical_message(message),
                lambda: self._format_business_critical_message(message, context),
            ),
            (
                lambda: self._is_ux_message(message),
                lambda: self._format_ux_message(message, context),
            ),
            (
                lambda: self._is_integration_message(message),
                lambda: self._format_integration_message(message, context),
            ),
            (
                lambda: stakeholder is not None,
                lambda: self._format_for_stakeholder(message, str(stakeholder), context),
            ),
            (
                lambda: self._is_metric_message(message),
                lambda: self._format_metric_from_message(message),
            ),
        ]

        # Try formatters in order
        for condition, formatter in formatters:
            if condition():
                return formatter()

        # Default: Apply technology transformations and context
        formatted_message = self._apply_technology_transformations(message)
        formatted_message = self._apply_custom_patterns(formatted_message)

        if context:
            formatted_message = self._apply_context_formatting(formatted_message, context)

        return formatted_message

    def format_test_message(
        self, test_name: str, status: str, details: str | None = None
    ) -> dict[str, str]:
        """
        Format test message in professional business language with variety

        Args:
            test_name: Name of the test
            status: Test status (passed/failed/skipped)
            details: Optional test details

        Returns:
            Dictionary with formatted test details
        """
        import random

        # Extract business context from test name
        business_context = self._extract_business_context(test_name)

        if status == "passed":
            passed_messages = [
                f"Quality assurance verified for {business_context}",
                f"Business validation successful for {business_context}",
                f"Storm Development standards met for {business_context}",
                f"Professional quality confirmed for {business_context}",
            ]
            passed_details = [
                "Meets Storm Development production standards",
                "Passes all quality assurance criteria",
                "Complies with business requirements",
                "Ready for Storm Development deployment",
            ]
            passed_recommendations = [
                "Ready for client deployment",
                "Approved for production release",
                "Meets $50 website quality standards",
                "Suitable for Storm Hosting platform",
            ]
            return {
                "message": random.choice(passed_messages),
                "details": random.choice(passed_details),
                "recommendation": random.choice(passed_recommendations),
            }
        elif status == "failed":
            failed_messages = [
                f"Quality issue detected in {business_context}",
                f"Business validation failed for {business_context}",
                f"Storm Development standards not met in {business_context}",
                f"Professional quality issue identified in {business_context}",
            ]
            failed_details = [
                details or "Review required before production deployment",
                details or "Quality standards not met - investigation needed",
                details or "Business requirements validation failed",
                details or "Storm Development protocols require attention",
            ]
            failed_recommendations = [
                "Apply Storm Development best practices for resolution",
                "Consult Django-Spellbook documentation for guidance",
                "Review business requirements and test expectations",
                "Collaborate with senior engineers for quality improvement",
            ]
            return {
                "message": random.choice(failed_messages),
                "details": random.choice(failed_details),
                "recommendation": random.choice(failed_recommendations),
            }
        else:
            skipped_messages = [
                f"Test deferred for {business_context}",
                f"Quality validation postponed for {business_context}",
                f"Business validation skipped for {business_context}",
                f"Storm Development review pending for {business_context}",
            ]
            skipped_details = [
                details or "Manual review may be required",
                details or "Business requirements under evaluation",
                details or "Quality assessment deferred",
                details or "Storm Development review scheduled",
            ]
            skipped_recommendations = [
                "Consult Storm Development testing guidelines",
                "Review business requirements documentation",
                "Schedule manual quality verification",
                "Coordinate with product management for clarification",
            ]
            return {
                "message": random.choice(skipped_messages),
                "details": random.choice(skipped_details),
                "recommendation": random.choice(skipped_recommendations),
            }

    def format_metric_message(
        self, metric_name: str, value: Any, threshold: Any | None = None
    ) -> dict[str, Any]:
        """
        Format metric message in professional business language

        Args:
            metric_name: Name of the metric
            value: Metric value
            threshold: Optional threshold value

        Returns:
            Dictionary with formatted metric details
        """
        if metric_name in self.metric_patterns:
            metric_info = self.metric_patterns[metric_name]

            # Determine if metric meets business standards
            status = self._evaluate_metric_status(value, metric_info.get("target", "N/A"))

            return {
                "name": metric_info["name"],
                "value": value,
                "target": metric_info["target"],
                "status": status,
                "business_impact": metric_info["business_impact"],
                "recommendation": self._get_metric_recommendation(metric_name, status),
            }

        # Default metric format
        return {
            "name": metric_name.replace("_", " ").title(),
            "value": value,
            "target": threshold or "N/A",
            "status": "measured",
            "business_impact": "Performance tracking for Storm Development standards",
        }

    def format_django_spellbook_tip(self, context: str) -> str:
        """Format Django-Spellbook specific tips"""
        tips_map = {
            "model": "Use Django-Spellbook's enhanced model patterns for 10x development speed",
            "view": "Implement Django-Spellbook view decorators for magical simplicity",
            "template": "Leverage Django-Spellbook's markdown-to-magic transformation",
            "form": "Apply Django-Spellbook form wizardry for intuitive user experiences",
            "admin": "Utilize Django-Spellbook's admin enhancements for powerful management",
        }

        for key, tip in tips_map.items():
            if key in context.lower():
                return tip

        return "Django-Spellbook: 10+ years of Django mastery at your service"

    def format_midas_optimization(self, context: str) -> str:
        """Format MIDAS optimization suggestions"""
        optimizations_map = {
            "performance": "MIDAS WebAssembly compilation can achieve 10x performance gains",
            "memory": "MIDAS memory optimization reduces hosting costs for $10/month service",
            "speed": "MIDAS C-to-WebAssembly delivers native speed in browsers",
            "calculation": "MIDAS accelerates complex calculations for real-time dashboards",
            "animation": "MIDAS powers 60fps Storm Animation System performance",
        }

        for key, optimization in optimizations_map.items():
            if key in context.lower():
                return optimization

        return "MIDAS: Revolutionary C-to-WebAssembly performance optimization"

    def format_business_recommendation(self, context: str, issue_type: str) -> list[str]:
        """Generate business recommendations based on context"""
        recommendations = []

        if "customer" in context.lower():
            recommendations.extend(
                [
                    "Ensure data integrity for Storm Dashboard customer management",
                    "Apply Django-Spellbook validation patterns for data quality",
                    "Implement Storm Development's customer-first approach",
                ]
            )
        elif "invoice" in context.lower():
            recommendations.extend(
                [
                    "Maintain financial accuracy for $30/month dashboard service",
                    "Use Storm Development's proven billing patterns",
                    "Ensure compliance with business financial standards",
                ]
            )
        elif "performance" in issue_type.lower():
            recommendations.extend(
                [
                    "Optimize with MIDAS WebAssembly acceleration",
                    "Apply Storm Animation System performance patterns",
                    "Meet $50 website speed guarantees",
                ]
            )
        else:
            recommendations.extend(
                [
                    "Follow Storm Development's best practices",
                    "Leverage Django-Spellbook framework capabilities",
                    "Maintain production quality standards",
                ]
            )

        return recommendations

    def _extract_business_context(self, test_name: str) -> str:
        """Extract business context from test name"""
        # Remove test prefixes
        context = re.sub(r"^test_", "", test_name)

        # Convert to business language
        context = context.replace("_", " ").title()

        # Map technical terms to business terms
        business_terms = {
            "Crud": "Data Management",
            "Api": "Service Interface",
            "Db": "Database",
            "Ui": "User Interface",
            "Ux": "User Experience",
            "Auth": "Authentication",
            "Perms": "Permissions",
        }

        for tech_term, business_term in business_terms.items():
            context = context.replace(tech_term, business_term)

        return context

    def _format_context(self, context: dict[str, Any]) -> str:
        """Format context dictionary into business language"""
        formatted_parts = []

        for key, value in context.items():
            business_key = key.replace("_", " ").title()
            formatted_parts.append(f"{business_key}: {value}")

        return ", ".join(formatted_parts)

    def _evaluate_metric_status(self, value: Any, target: str) -> str:
        """Evaluate metric status against business target"""
        if not target or target == "N/A":
            return "measured"

        # Parse target (e.g., "< 200ms", "> 99.9%")
        match = re.match(r"([<>]=?)\s*([\d.]+)", target)
        if match:
            operator, target_value = match.groups()
            try:
                value_num = float(re.findall(r"[\d.]+", str(value))[0])
                target_num = float(target_value)

                operator_checks = {
                    "<": value_num < target_num,
                    ">": value_num > target_num,
                    "<=": value_num <= target_num,
                    ">=": value_num >= target_num,
                }

                if operator in operator_checks:
                    return "optimal" if operator_checks[operator] else "attention_required"
            except (ValueError, IndexError):
                pass

        return "measured"

    def _get_metric_recommendation(self, metric_name: str, status: str) -> str:
        """Get metric-specific recommendation"""
        if status == "optimal":
            return "Performance meets Storm Development excellence standards"
        elif status == "attention_required":
            recommendations = {
                "response_time": "Apply MIDAS optimization for improved response times",
                "memory_usage": "Implement memory-efficient patterns for $10/month hosting",
                "error_rate": "Review error handling for $50 website quality",
                "uptime": "Ensure Storm Hosting reliability standards",
            }

            return recommendations.get(
                metric_name, "Monitor metric for Storm Development quality assurance"
            )

        return "Monitor metric for Storm Development quality assurance"

    def _is_error_message(self, message: str, level: str | None = None) -> bool:
        """Check if message is an error."""
        if level and level.lower() == "error":
            return True

        # Check for exception patterns (ClassName: message)
        if re.match(r"^\w+Error:", message) or re.match(r"^\w+Exception:", message):
            return True

        # Check for known error class names
        error_classes = [
            "DoesNotExist",
            "IntegrityError",
            "ValidationError",
            "TimeoutError",
            "MemoryError",
            "TemplateDoesNotExist",
            "PermissionDenied",
            "Http404",
        ]
        for error_class in error_classes:
            if message.startswith(error_class + ":"):
                return True

        # Check for error indicators in the message
        error_indicators = [
            "error",
            "fail",
            "exception",
            "traceback",
            "denied",
            "refused",
            "timeout",
        ]
        message_lower = message.lower()
        return any(indicator in message_lower for indicator in error_indicators)

    def _is_success_message(self, message: str, level: str | None = None) -> bool:
        """Check if message is a success."""
        if level and level.lower() == "success":
            return True
        success_indicators = [
            "success",
            "successful",
            "completed",
            "passed",
            "created",
            "updated",
            "deployed",
            "saved",
        ]
        message_lower = message.lower()
        return any(indicator in message_lower for indicator in success_indicators)

    def _is_performance_message(self, message: str) -> bool:
        """Check if message is performance-related."""
        perf_indicators = [
            "ms",
            "seconds",
            "latency",
            "slow",
            "performance",
            "cpu",
            "memory",
            "usage",
            "exhausted",
            "pool",
        ]
        message_lower = message.lower()
        return any(indicator in message_lower for indicator in perf_indicators)

    def _is_security_message(self, message: str) -> bool:
        """Check if message is security-related."""
        security_indicators = [
            "auth",
            "permission",
            "denied",
            "unauthorized",
            "token",
            "csrf",
            "security",
            "violation",
        ]
        message_lower = message.lower()
        return any(indicator in message_lower for indicator in security_indicators)

    def _is_business_critical_message(self, message: str) -> bool:
        """Check if message is business-critical."""
        critical_indicators = [
            "payment",
            "revenue",
            "customer",
            "order",
            "backup",
            "data corruption",
            "unavailable",
        ]
        message_lower = message.lower()
        return any(indicator in message_lower for indicator in critical_indicators)

    def _is_ux_message(self, message: str) -> bool:
        """Check if message is UX-related."""
        ux_indicators = [
            "page load",
            "render",
            "ui",
            "interface",
            "form",
            "mobile",
            "responsive",
            "accessibility",
            "session",
        ]
        message_lower = message.lower()
        return any(indicator in message_lower for indicator in ux_indicators)

    def _is_integration_message(self, message: str) -> bool:
        """Check if message is integration-related."""
        integration_indicators = [
            "api",
            "webhook",
            "sync",
            "external",
            "third-party",
            "queue",
            "integration",
        ]
        message_lower = message.lower()
        return any(indicator in message_lower for indicator in integration_indicators)

    def _is_metric_message(self, message: str) -> bool:
        """Check if message contains metrics."""
        # Look for patterns like "metric_name: value" or numbers with units
        return bool(re.search(r"\b\w+:\s*[\d.]+|\d+(\.\d+)?\s*(ms|s|%|MB|GB)", message))

    def _format_performance_message(
        self, message: str, _context: dict[str, Any] | None = None
    ) -> str:
        """Format performance-related messages."""
        # Add performance context
        formatted = f"Performance threshold notification: {message}"

        # Add optimization suggestions
        if "slow" in message.lower() or "timeout" in message.lower():
            formatted += ". Implementing MIDAS WebAssembly acceleration for optimal performance"
        elif "memory" in message.lower():
            formatted += ". Optimizing resource utilization for efficient Storm Hosting deployment"
        elif "cpu" in message.lower():
            formatted += ". Applying Storm Development performance optimization patterns"

        return formatted

    def _format_security_message(self, message: str, _context: dict[str, Any] | None = None) -> str:
        """Format security-related messages."""
        # Add security context
        formatted = f"Security control notification: {message}"

        # Add Storm Dashboard reference for access control
        if "permission" in message.lower() or "denied" in message.lower():
            formatted += ". Reviewing Storm Dashboard access control policies"
        elif "auth" in message.lower():
            formatted += ". Implementing Storm Development authentication best practices"

        return formatted

    def _format_business_critical_message(
        self, message: str, _context: dict[str, Any] | None = None
    ) -> str:
        """Format business-critical messages."""
        # Emphasize business impact
        formatted = f"Business-critical event: {message}"

        # Add urgency and impact
        if "payment" in message.lower() or "revenue" in message.lower():
            formatted += ". Immediate business impact - revenue operations affected"
        elif "customer" in message.lower():
            formatted += ". Customer experience impact - urgent attention required"
        elif "unavailable" in message.lower():
            formatted += ". Service availability impact - business operations affected"

        return formatted

    def _format_ux_message(self, message: str, _context: dict[str, Any] | None = None) -> str:
        """Format UX-related messages."""
        # Add user experience context
        formatted = f"User experience notification: {message}"

        # Add Storm Animation System reference for UI issues
        if "render" in message.lower() or "interface" in message.lower():
            formatted += ". Optimizing with Storm Animation System for enhanced user interaction"
        elif "load" in message.lower():
            formatted += ". Implementing performance enhancements for optimal user satisfaction"

        return formatted

    def _format_integration_message(
        self, message: str, _context: dict[str, Any] | None = None
    ) -> str:
        """Format integration-related messages."""
        # Add integration context
        formatted = f"Service integration notification: {message}"

        # Add connectivity guidance
        if "api" in message.lower():
            formatted += ". Managing external API connectivity for seamless service integration"
        elif "sync" in message.lower():
            formatted += ". Ensuring data synchronization across integrated services"

        return formatted

    def _format_for_stakeholder(
        self, message: str, stakeholder: str, _context: dict[str, Any] | None = None
    ) -> str:
        """Format message for specific stakeholder."""
        if stakeholder == "executive":
            # Focus on business impact
            formatted = self._add_business_impact(message)
            formatted += ". Strategic implications for business operations and revenue"
        elif stakeholder == "technical":
            # Add technical context with business relevance
            formatted = message
            if "django" in message.lower():
                formatted += ". Leveraging Django-Spellbook for optimal implementation"
            else:
                formatted += ". Technical optimization for business value delivery"
        elif stakeholder == "support":
            # Focus on customer impact and resolution
            formatted = f"Customer support alert: {message}"
            formatted += ". Focus on rapid resolution for optimal customer experience"
        else:
            formatted = message

        return formatted

    def _format_metric_from_message(self, message: str) -> str:
        """Extract and format metrics from message."""
        # Look for metric patterns
        metric_match = re.search(r"(\w+):\s*([\d.]+)", message)
        if metric_match:
            metric_name, value = metric_match.groups()
            # Check if it's a known metric
            if metric_name in self.metric_patterns:
                metric_info = self.metric_patterns[metric_name]
                return f"{metric_info['name']}: {value} - {metric_info['business_impact']}"
            else:
                # Generic metric formatting
                return f"Business metric {metric_name}: {value} - Tracking for performance optimization"

        return message

    def _apply_technology_transformations(self, message: str) -> str:
        """Apply technology keyword transformations."""
        formatted = message
        for tech_keyword, tech_name in self.technology_map.items():
            # Case-insensitive replacement while preserving original case style
            pattern = re.compile(re.escape(tech_keyword), re.IGNORECASE)
            formatted = pattern.sub(tech_name, formatted)
        return formatted

    def _apply_context_formatting(self, message: str, context: dict[str, Any]) -> str:
        """Apply context-based formatting."""
        # Add component-specific context
        if "component" in context:
            component = context["component"]
            component_contexts = {
                "database": "Data integrity and storage optimization",
                "api": "Service endpoint integration",
                "auth": "Security and access control",
                "payment": "Financial transaction processing",
            }

            if component in component_contexts:
                message += f" - {component_contexts[component]}"

        return message

    def _add_business_impact(self, message: str) -> str:
        """Add business impact context to message."""
        # Check for impact indicators
        if "downtime" in message.lower():
            return f"Business operations disruption: {message}"
        elif "revenue" in message.lower() or "$" in message:
            return f"Financial impact detected: {message}"
        elif "customer" in message.lower():
            return f"Customer satisfaction impact: {message}"
        elif "performance" in message.lower():
            return f"Operational efficiency concern: {message}"
        else:
            return f"Business event: {message}"

    def _apply_custom_patterns(self, message: str) -> str:
        """Apply custom patterns added via add_pattern."""
        if hasattr(self, "custom_patterns"):
            for pattern, replacement in self.custom_patterns:
                message = pattern.sub(replacement, message)
        return message

    def add_pattern(
        self,
        pattern: str,
        replacement: str | None = None,
        pattern_type: str | None = None,
        pattern_details: dict[str, Any] | None = None,
    ) -> None:
        """
        Adds a new pattern to the formatter. Supports multiple call signatures for flexibility.

        Args:
            pattern: The regex pattern or pattern key
            replacement: The replacement string (for simple patterns)
            pattern_type: Type of pattern (error, success, metric)
            pattern_details: Detailed pattern configuration
        """
        # Support simple pattern/replacement pairs
        if replacement is not None and pattern_details is None:
            # Add as a custom transformation pattern
            if not hasattr(self, "custom_patterns"):
                self.custom_patterns: list[tuple[Any, str]] = []
            self.custom_patterns.append((re.compile(pattern), replacement))
            return

        # Support original 3-argument signature
        if pattern_type is not None:
            if pattern_type == "error":
                self.error_patterns[pattern] = pattern_details or {"message": replacement or ""}
            elif pattern_type == "success":
                success_list = (
                    pattern_details
                    if isinstance(pattern_details, list)
                    else ([replacement] if replacement else [])
                )
                self.success_patterns[pattern] = success_list
            elif pattern_type == "metric":
                self.metric_patterns[pattern] = pattern_details or {"name": replacement or ""}
            else:
                raise ValueError(f"Unknown pattern type: {pattern_type}")
            return

        raise ValueError("Either replacement or pattern_type must be provided")

    def format_success_message(self, action: str, context: dict[str, Any] | None = None) -> str:
        """Format success messages with action-specific templates using variety."""
        import random

        # Use the success_patterns if available for the action
        if action.lower() in self.success_patterns:
            message = random.choice(self.success_patterns[action.lower()])

            # Add context information if provided
            if context:
                context_parts = []
                for key, value in context.items():
                    context_parts.append(f"{key.capitalize()}: {value}")
                if context_parts:
                    message += f" - {', '.join(context_parts)}"

            return message

        # Fall back to simple templates with business-oriented language
        templates = {
            "created": "✅ Business entity created: {item}",
            "updated": "✅ Business data updated: {item}",
            "deployed": "🚀 Business service deployed: {item}",
            "saved": "💾 Business data saved: {item}",
            "validated": "✓ Business rules validated: {item}",
            "deleted": "🗑️ Business resource deleted: {item}",
            "optimized": "⚡ Business process optimized: {item}",
        }
        template = templates.get(action, "✅ Operation completed: {action}")
        return template.format(
            action=action,
            item=context.get("item", "resource") if context else "resource",
            **(context or {}),
        )

    def format_error_message(
        self, error_type: str, message: Any, context: dict[str, Any] | None = None
    ) -> str:
        """Format error messages with proper string handling."""
        if not isinstance(message, str):
            message = str(message)

        error_templates = {
            "DoesNotExist": "❌ Resource not found: {message}",
            "ValidationError": "⚠️ Validation failed: {message}",
            "TimeoutError": "⏱️ Operation timed out: {message}",
            "PermissionDenied": "🔒 Access denied: {message}",
            "IntegrityError": "🚨 Data integrity issue: {message}",
            "Http404": "🔍 Page not found: {message}",
            "MemoryError": "💾 Memory limit exceeded: {message}",
            "ConnectionError": "🔌 Connection failed: {message}",
        }

        template = error_templates.get(error_type, "❌ Error: {message}")
        return template.format(message=message, **(context or {}))

    def format_message(self, message: str, **kwargs: Any) -> str:
        """Format a general message."""
        return self.format(message, **kwargs)

    def format_error(self, message: Any, **_kwargs: Any) -> str:
        """
        Format an error message in professional business language.

        Args:
            message: Error message (string or Exception).

        Returns:
            A formatted error string.
        """
        # Handle Exception objects
        if isinstance(message, Exception):
            error_str = str(message)
            error_type = message.__class__.__name__
        else:
            error_str = str(message)
            error_type = "UNKNOWN_ERROR"
            # Try to extract error type from message if it's an exception string
            match = re.match(r"(\w+):", error_str)
            if match:
                error_type = match.group(1)

        # Check for known error patterns
        for pattern, details in self.error_patterns.items():
            if re.search(pattern, error_type, re.IGNORECASE) or re.search(
                pattern, error_str, re.IGNORECASE
            ):
                # Format as string with business context
                guidance = details.get("guidance", "")
                formatted = f"❌ {details['message']}"
                if guidance:
                    formatted += f"\n📌 {guidance}"
                return formatted

        # Default professional error format
        # Check if it's a custom exception that doesn't match any pattern
        if error_type != "UNKNOWN_ERROR" and "Error" in error_type:
            return f"❌ System exception detected in {error_type}: {error_str}\n📌 Storm Development error handling protocols engaged"

        return f"❌ Business process exception: {error_str}\n📌 Implementing Storm Development error resolution protocols with data integrity validation."

    def format_success(self, message: str, **_kwargs: Any) -> str:
        """
        Format a success message in professional business language with variety.

        Args:
            message: Success message string.

        Returns:
            Formatted success message string.
        """
        import random

        # Look for action keywords to choose appropriate pattern
        action = None
        for pattern in self.success_patterns:
            if pattern.lower() in message.lower():
                action = pattern
                break

        if action and action in self.success_patterns:
            # Use variety from success patterns
            return random.choice(self.success_patterns[action])

        # Default success messages with variety
        default_messages = [
            f"✅ Operation completed: {message}",
            f"✨ Excellent! Business process completed: {message}",
            f"🎯 Outstanding! Storm Development achieved: {message}",
            f"⭐ Superb! Quality standards met: {message}",
            f"✨ Success! Business value delivered: {message}",
        ]

        return random.choice(default_messages)


# Singleton instance for global access
storm_formatter = StormMessageFormatter()
