"""
Storm Development Professional Logger
Business-oriented logging system with modern architecture
"""

import logging
from typing import Optional, Any, Dict
from .core.logger import StormLogger, get_storm_logger
from .console.storm_console import get_storm_console
from .core.formatters.message_formatter import StormMessageFormatter
from .context_detector import ContextDetector
from .config import StormLoggerConfig


class StormProfessionalLogger(StormLogger):
    """
    Storm Development Professional Logger
    Modern architecture with business-oriented console output
    """
    
    def __init__(self, name: str, config: Optional[StormLoggerConfig] = None, auto_detect_context: bool = True):
        super().__init__(name, config, auto_detect_context)
        self.console = get_storm_console(config)
        self.formatter = StormMessageFormatter()
        self._show_console = True
        
    def _format_message(self, message: str, level: str, exc_info=None, **kwargs):
        """Override to add professional console output"""
        # Get base formatted message
        formatted = super()._format_message(message, level, exc_info, **kwargs)
        
        # Show in professional console if enabled
        if self._show_console:
            self._display_professional(message, level, exc_info, **kwargs)
            
        return formatted
        
    def _display_professional(self, message: str, level: str, exc_info=None, **kwargs):
        """Display message using professional Storm console"""
        context = kwargs.get('context', 'system')
        
        if level == "DEBUG":
            # Debug messages are for development only
            pass
        elif level == "INFO":
            if "test" in context.lower():
                # Test-related info
                if "passed" in message.lower():
                    self.console.print_test_progress(message, "passed")
                elif "failed" in message.lower():
                    self.console.print_test_progress(message, "failed")
                else:
                    self.console.print_test_progress(message, "running")
            else:
                # General info
                self.console.print_analysis("SYSTEM OPERATION", message)
        elif level == "WARNING":
            self.console.print_analysis("BUSINESS ATTENTION", message)
        elif level == "ERROR":
            if exc_info:
                # Format error with business context
                error_info = self.formatter.format_error_message(exc_info)
                self.console.print_error(
                    error_info["type"],
                    error_info["message"],
                    error_info["guidance"]
                )
            else:
                self.console.print_error("SYSTEM ERROR", message)
        elif level == "CRITICAL":
            self.console.print_error(
                "CRITICAL FAILURE",
                message,
                "Contact Storm Development support immediately"
            )
            
    def business_metric(self, metric_name: str, value: Any, threshold: Optional[Any] = None):
        """Log business metrics"""
        metric_info = self.formatter.format_metric_message(metric_name, value, threshold)
        
        metrics = {
            metric_info["name"]: {
                "value": metric_info["value"],
                "target": metric_info["target"],
                "status": metric_info["status"] == "optimal"
            }
        }
        
        self.console.print_metrics(metrics)
        self.info(f"Business metric: {metric_name}={value}")
        
    def django_operation(self, operation: str, model: Optional[str] = None, success: bool = True):
        """Log Django-Spellbook operations"""
        if success:
            msg = self.formatter.format_success_message(operation, {"model": model} if model else None)
            self.console.print_solution(
                msg,
                "Django-Spellbook pattern applied successfully"
            )
            tip = self.formatter.format_django_spellbook_tip(operation)
            self.console.print_django_spellbook_tip(tip)
            self.success(msg)
        else:
            msg = f"Django operation failed: {operation}" + (f" for {model}" if model else "")
            self.console.print_error(
                "DJANGO OPERATION FAILURE",
                msg,
                "Review Django-Spellbook best practices"
            )
            self.error(msg)
            
    def midas_optimization(self, component: str, before_metric: Any, after_metric: Any):
        """Log MIDAS optimizations"""
        try:
            before_val = float(before_metric)
            after_val = float(after_metric)
            if before_val > 0:
                improvement = ((before_val - after_val) / before_val) * 100
            else:
                improvement = 100.0 if after_val > 0 else 0.0
        except:
            improvement = 0.0
            
        self.console.print_midas_optimization(
            f"{component} optimized: {improvement:.1f}% performance gain"
        )
        
        optimization = self.formatter.format_midas_optimization(component)
        self.console.print_analysis("MIDAS OPTIMIZATION", optimization)
        self.info(f"MIDAS optimization: {component} improved by {improvement:.1f}%")
        
    def storm_animation_event(self, event_type: str, details: Dict[str, Any]):
        """Log Storm Animation System events"""
        self.console.print_storm_animation_insight(
            f"Animation event '{event_type}' triggered with {len(details)} parameters"
        )
        
        if "conversion" in details:
            self.console.print_business_recommendation(
                "Animation Conversion Impact",
                [
                    f"Event '{event_type}' shows {details['conversion']}% conversion rate",
                    "Consider A/B testing this animation pattern",
                    "Track user engagement in Storm Dashboard"
                ]
            )
            
        self.info(f"Storm Animation: {event_type}", **details)
        
    def test_pass(self, test_name: str, **kwargs):
        """Override for professional test pass"""
        test_info = self.formatter.format_test_message(test_name, "passed")
        self.console.print_test_progress(test_name, "passed", test_info["details"])
        super().test_pass(test_name, **kwargs)
        
    def test_fail(self, test_name: str, error_message: str, **kwargs):
        """Override for professional test failure"""
        test_info = self.formatter.format_test_message(test_name, "failed", error_message)
        self.console.print_test_progress(test_name, "failed", test_info["details"])
        
        if test_info["recommendation"]:
            self.console.print_business_recommendation(
                "Quality Assurance Action Required",
                [test_info["recommendation"]]
            )
            
        super().test_fail(test_name, error_message, **kwargs)
        
    def session_summary(self, tests_run: int, passed: int, failed: int, duration: float):
        """Print professional session summary"""
        self.console.print_session_summary(tests_run, passed, failed, duration)
        
        success_rate = (passed / tests_run * 100) if tests_run > 0 else 0
        
        if success_rate < 80:
            recommendations = self.formatter.format_business_recommendation(
                "quality assurance",
                "performance"
            )
            self.console.print_business_recommendation(
                "Quality Improvement Plan",
                recommendations
            )
            
        self.info(f"Test session complete: {tests_run} tests, {passed} passed, {failed} failed")
        
    def print_header(self, title: str, subtitle: Optional[str] = None):
        """Print professional header"""
        self.console.print_header(title, subtitle)
        self.info(f"=== {title} ===" + (f" - {subtitle}" if subtitle else ""))
        
    def teaching_moment(self, message: str, **kwargs):
        """Override for professional teaching moment"""
        # Determine technology context
        tech = "django"
        if "midas" in message.lower():
            tech = "midas"
        elif "animation" in message.lower():
            tech = "animation"
            
        self.console.print_business_context(message, tech)
        super().teaching_moment(message, **kwargs)
        
    def helpful_tip(self, message: str, **kwargs):
        """Override for professional helpful tip"""
        # Check for specific technology tips
        if "django" in message.lower():
            tip = self.formatter.format_django_spellbook_tip(message)
            self.console.print_django_spellbook_tip(tip)
        elif "midas" in message.lower() or "performance" in message.lower():
            opt = self.formatter.format_midas_optimization(message)
            self.console.print_midas_optimization(opt)
        else:
            self.console.print_analysis("PROFESSIONAL TIP", message)
            
        super().helpful_tip(message, **kwargs)


def get_professional_logger(name: str = None, config: Optional[StormLoggerConfig] = None) -> StormProfessionalLogger:
    """
    Get a professional Storm logger instance
    
    Usage:
        logger = get_professional_logger(__name__)
        logger.info("Starting operation")
        logger.business_metric("response_time", 0.150, "< 200ms")
    """
    if name is None:
        import inspect
        frame = inspect.currentframe().f_back
        name = frame.f_globals.get('__name__', 'storm.professional')
        
    return StormProfessionalLogger(name, config)


def get_professional_test_logger(name: str = None) -> StormProfessionalLogger:
    """
    Get a professional Storm logger for tests
    
    Usage:
        logger = get_professional_test_logger()
        logger.test_pass("test_customer_creation")
    """
    logger = get_professional_logger(name)
    logger.test_mode = True
    return logger


# Create global instance
professional_logger = get_professional_logger('storm.professional')

__all__ = [
    'StormProfessionalLogger',
    'get_professional_logger', 
    'get_professional_test_logger',
    'professional_logger'
]