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

from typing import Any

from .config import StormLoggerConfig
from .console.storm_console import get_storm_console
from .core.formatters.message_formatter import StormMessageFormatter
from .core.logger import StormLogger


class StormProfessionalLogger(StormLogger):
    """
    Storm Development Professional Logger
    Modern architecture with business-oriented console output
    """

    def __init__(
        self,
        name: str,
        config: StormLoggerConfig | None = None,
        auto_detect_context: bool = True,
    ) -> None:
        super().__init__(name, config, auto_detect_context)
        self.console = get_storm_console(config)
        self.formatter = StormMessageFormatter()
        self._show_console = True
        self.test_mode = False

    def _format_message(
        self, message: str, _level: str, _exc_info: Any = None, **kwargs: Any
    ) -> str:
        """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: Any = None, **kwargs: Any
    ) -> None:
        """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
                MIN_EXC_INFO_LENGTH = 2
                if isinstance(exc_info, tuple) and len(exc_info) >= MIN_EXC_INFO_LENGTH:
                    error_type = (
                        exc_info[0].__name__
                        if hasattr(exc_info[0], "__name__")
                        else str(exc_info[0])
                    )
                    error_msg = str(exc_info[1])
                else:
                    error_type = "ERROR"
                    error_msg = str(exc_info)
                formatted_error = self.formatter.format_error_message(error_type, error_msg)
                self.console.print_error("SYSTEM ERROR", formatted_error)
            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: Any | None = None, **kwargs: 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}", **kwargs)

    def django_operation(
        self, operation: str, model: str | None = None, success: bool = True
    ) -> None:
        """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) -> None:
        """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 (ValueError, TypeError, ZeroDivisionError):
            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]) -> None:
        """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: Any) -> None:
        """Override for professional test pass"""
        self.formatter.format_test_message(test_name, "passed")
        # print_test_progress expects duration, not details - pass None
        self.console.print_test_progress(test_name, "passed", None)
        super().test_pass(test_name, **kwargs)

    def test_fail(self, test_name: str, error_message: str = "", **kwargs: Any) -> None:
        """Override for professional test failure"""
        test_info = self.formatter.format_test_message(test_name, "failed", error_message)
        # print_test_progress expects duration, not details - pass None
        self.console.print_test_progress(test_name, "failed", None)

        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) -> None:
        """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

        MIN_SUCCESS_RATE = 80
        if success_rate < MIN_SUCCESS_RATE:
            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: str | None = None) -> 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: Any) -> None:
        """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: Any) -> None:
        """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 = None, config: StormLoggerConfig | None = 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()
        if frame and frame.f_back:
            name = frame.f_back.f_globals.get("__name__", "storm.professional")
        else:
            name = "storm.professional"

    return StormProfessionalLogger(name, config)


def get_professional_test_logger(name: str | None = 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",
]
