"""
Storm Development Professional Console
Business-oriented terminal output with Rich integration
"""

from typing import Any

from ..config import StormLoggerConfig
from ..interfaces import ConsoleInterface
from .console_interfaces import (
    ConfigProvider,
    ConsoleFactory,
    ProgressFactory,
    RichComponentFactory,
    SafetyProvider,
    SyntaxFactory,
    ThemeProvider,
)
from .safety import SafeConsoleWrapper


class StormConsole(ConsoleInterface):
    """
    Storm Development Professional Console with Rich formatting.

    Provides business-oriented console output with Storm branding,
    safety wrappers, and framework-agnostic functionality.
    """

    def __init__(
        self,
        config: StormLoggerConfig | None = None,
        console_factory: ConsoleFactory | None = None,
        syntax_factory: SyntaxFactory | None = None,
        progress_factory: ProgressFactory | None = None,
        component_factory: RichComponentFactory | None = None,
        theme_provider: ThemeProvider | None = None,
        config_provider: ConfigProvider | None = None,
        safety_provider: SafetyProvider | None = None,
    ) -> None:
        # Use injected dependencies or create defaults (will be implemented in concrete classes)
        self._config_provider = config_provider
        self._console_factory = console_factory
        self._syntax_factory = syntax_factory
        self._progress_factory = progress_factory
        self._component_factory = component_factory
        self._theme_provider = theme_provider
        self._safety_provider = safety_provider

        # Get config (use provided config or get from provider)
        if config is not None:
            self.config = config
        elif self._config_provider is not None:
            self.config = self._config_provider.get_config()
        else:
            # This maintains backward compatibility
            from ..config import get_config

            self.config = get_config()

        # Get theme
        if self._theme_provider is not None:
            self.theme = self._theme_provider.get_theme(self.config.storm_theme.value)
        else:
            # Backward compatibility
            from .themes import get_theme

            self.theme = get_theme(self.config.storm_theme.value)

        # Get safety wrapper
        if self._safety_provider is not None:
            self.safety = self._safety_provider.get_safety_wrapper()
        else:
            self.safety = SafeConsoleWrapper()

        self._console: Any = None
        self._live_contexts: list[Any] = []

    def get_console(self) -> Any:
        """Get the Rich console instance with Storm theming."""
        if self._console is None:
            if self._console_factory is not None:
                self._console = self._console_factory.create_console(
                    theme=self.theme,
                    force_terminal=self.config.console_colors,
                    legacy_windows=False,
                    safe_box=True,
                    stderr=False,
                )
            else:
                # Backward compatibility
                from rich.console import Console

                self._console = Console(
                    theme=self.theme,
                    force_terminal=self.config.console_colors,
                    legacy_windows=False,
                    safe_box=True,
                    stderr=False,
                )
        return self._console

    def print(self, *args: Any, **kwargs: Any) -> None:
        """Enhanced print with Storm styling."""
        console = self.get_console()
        self.safety.safe_print(console, *args, **kwargs)

    def print_header(self, title: str, subtitle: str | None = None) -> None:
        """Print professional header with Storm styling."""
        console = self.get_console()

        header_content = f"[storm.header] {title} [/storm.header]"
        if subtitle:
            header_content += f"\n[storm.subheader]{subtitle}[/storm.subheader]"

        self.safety.safe_panel(console, header_content, style="storm-royal-blue", padding=(1, 2))

    def print_business_context(self, context: str, technology: str = "django") -> None:
        """Print business context information."""
        console = self.get_console()

        # Map technology to Storm colors
        tech_colors = {
            "django": "storm.django",
            "midas": "storm.midas",
            "animation": "storm.animation",
            "business": "storm.business",
        }

        style = tech_colors.get(technology, "storm.info")
        message = f"[{style}]🎯 Business Context: {context}[/{style}]"

        self.safety.safe_print(console, message)

    def print_analysis(self, analysis_type: str, details: str) -> None:
        """Print analysis information with professional formatting."""
        console = self.get_console()

        analysis_content = f"[storm.info]📊 {analysis_type}[/storm.info]\n{details}"

        self.safety.safe_panel(console, analysis_content, style="storm-cyan", title="Analysis")

    def print_error(self, error_type: str, message: str, guidance: str | None = None) -> None:
        """Print error information with business guidance."""
        console = self.get_console()

        error_content = f"[storm.error]❌ {error_type}[/storm.error]\n{message}"

        if guidance:
            error_content += f"\n\n[storm.warning]💡 Guidance:[/storm.warning]\n{guidance}"

        self.safety.safe_panel(console, error_content, style="storm-error", title="Error Analysis")

    def print_success(self, title: str, message: str) -> None:
        """Print success message with Storm styling."""
        console = self.get_console()

        success_content = f"[storm.success]✅ {title}[/storm.success]\n{message}"

        self.safety.safe_panel(console, success_content, style="storm-success", title="Success")

    def print_warning(self, title: str, message: str) -> None:
        """Print warning message with Storm styling."""
        console = self.get_console()

        warning_content = f"[storm.warning]⚠️ {title}[/storm.warning]\n{message}"

        self.safety.safe_panel(console, warning_content, style="storm-warning", title="Warning")

    def print_info(self, title: str, message: str) -> None:
        """Print info message with Storm styling."""
        console = self.get_console()

        info_content = f"[storm.info]ℹ️ {title}[/storm.info]\n{message}"

        self.safety.safe_panel(console, info_content, style="storm-info", title="Info")

    def print_panel(self, title: str, content: str, style: str = "storm.info") -> None:
        """Print a panel with Storm styling."""
        console = self.get_console()
        self.safety.safe_panel(console, content, style=style, title=title)

    def print_business_metric(
        self,
        metric_name: str,
        value: Any,
        threshold: Any | None = None,
        _context: str = "business",
    ) -> None:
        """Print business metric with professional formatting."""
        console = self.get_console()

        metric_content = f"[storm.metric]📈 {metric_name}:[/storm.metric] {value}"

        if threshold is not None:
            if isinstance(value, int | float) and isinstance(threshold, int | float):
                if value > threshold:
                    metric_content += (
                        f" [storm.error](exceeds threshold: {threshold})[/storm.error]"
                    )
                else:
                    metric_content += (
                        f" [storm.success](within threshold: {threshold})[/storm.success]"
                    )
            else:
                metric_content += f" [storm.info](threshold: {threshold})[/storm.info]"

        self.safety.safe_print(console, metric_content)

    def print_test_progress(
        self, test_name: str, status: str, duration: float | None = None
    ) -> None:
        """Print test progress with status-specific styling."""
        console = self.get_console()

        status_styles = {
            "passed": "storm.success",
            "failed": "storm.error",
            "running": "storm.info",
            "skipped": "storm.warning",
        }

        status_icons = {"passed": "✅", "failed": "❌", "running": "🏃", "skipped": "⏭️"}

        style = status_styles.get(status.lower(), "storm.info")
        icon = status_icons.get(status.lower(), "•")

        message = f"[{style}]{icon} {test_name}: {status.upper()}[/{style}]"

        if duration is not None:
            message += f" [storm.debug]({duration:.2f}s)[/storm.debug]"

        self.safety.safe_print(console, message)

    def print_session_summary(
        self, tests_run: int, passed: int, failed: int, duration: float
    ) -> None:
        """Print test session summary with business metrics."""
        console = self.get_console()

        success_rate = (passed / tests_run * 100) if tests_run > 0 else 0

        summary_content = f"""
[storm.metric]Tests Run:[/storm.metric] {tests_run}
[storm.success]Passed:[/storm.success] {passed}
[storm.error]Failed:[/storm.error] {failed}
[storm.kpi]Success Rate:[/storm.kpi] {success_rate:.1f}%
[storm.info]Duration:[/storm.info] {duration:.2f}s
"""

        self.safety.safe_panel(
            console, summary_content.strip(), style="storm-royal-blue", title="Test Session Summary"
        )

    def print_business_recommendation(self, title: str, recommendations: list[str]) -> None:
        """Print business recommendations with Storm styling."""
        console = self.get_console()

        rec_content = f"[storm.business]{title}[/storm.business]\n\n"

        for i, rec in enumerate(recommendations, 1):
            rec_content += f"[storm.highlight]{i}.[/storm.highlight] {rec}\n"

        self.safety.safe_panel(
            console, rec_content.strip(), style="storm-pine", title="Business Recommendations"
        )

    def print_table(self, title: str, columns: list[str], rows: list[list[Any]]) -> None:
        """Print a table with Storm styling."""
        console = self.get_console()
        self.safety.safe_table(console, columns, rows, title=title)

    def print_code(self, code: str, language: str = "python", theme: str = "monokai") -> None:
        """Print code with syntax highlighting."""
        console = self.get_console()

        if self.safety.is_rich_available():
            try:
                if self._syntax_factory is not None:
                    syntax = self._syntax_factory.create_syntax(code, language, theme)
                else:
                    # Backward compatibility
                    from rich.syntax import Syntax

                    syntax = Syntax(code, language, theme=theme)
                console.print(syntax)
            except Exception:
                pass
            else:
                return

        # Fallback to plain code
        self.safety.safe_print(
            console,
            f"""```
{language}
{code}
""",
        )

    def create_progress(self, description: str = "Processing...") -> Any:
        """Create a progress bar with Storm styling."""
        console = self.get_console()

        if self.safety._rich_available:
            if self._progress_factory is not None:
                # Use factory to create progress components
                spinner = self._progress_factory.create_spinner_column()
                text = self._progress_factory.create_text_column(
                    "[progress.description]{task.description}"
                )
                bar = self._progress_factory.create_bar_column()
                percent = self._progress_factory.create_text_column(
                    "[progress.percentage]{task.percentage:>3.0f}%"
                )
                return self._progress_factory.create_progress(
                    spinner, text, bar, percent, console=console
                )
            else:
                # Backward compatibility
                from rich.progress import BarColumn, Progress, SpinnerColumn, TextColumn

                return Progress(
                    SpinnerColumn(),
                    TextColumn("[progress.description]{task.description}"),
                    BarColumn(),
                    TextColumn("[progress.percentage]{task.percentage:>3.0f}%"),
                    console=console,
                )
        else:
            return self.safety.safe_progress(console, [description])

    def print_separator(self, title: str | None = None) -> None:
        """Print a separator line with optional title."""
        console = self.get_console()

        if title:
            separator = f"[storm.debug]{'=' * 20} {title} {'=' * 20}[/storm.debug]"
        else:
            separator = f"[storm.debug]{'=' * 60}[/storm.debug]"

        self.safety.safe_print(console, separator)

    def print_debug(self, message: str) -> None:
        """Print debug message with muted styling."""
        if self.config.debug_mode:
            console = self.get_console()
            debug_msg = f"[storm.debug]🔍 DEBUG: {message}[/storm.debug]"
            self.safety.safe_print(console, debug_msg)

    def print_metrics(self, metrics_dict: dict[str, Any]) -> None:
        """Display business metrics as a formatted table."""
        console = self.get_console()

        if not metrics_dict:
            self.safety.safe_print(console, "[storm.warning]📊 No metrics available[/storm.warning]")
            return

        if self._component_factory is not None:
            table = self._component_factory.create_table(
                title="📈 Business Metrics", show_header=True, header_style="storm.header"
            )
        else:
            # Backward compatibility
            from rich.table import Table

            table = Table(title="📈 Business Metrics", show_header=True, header_style="storm.header")

        table.add_column("Metric", style="storm.metric", no_wrap=True)
        table.add_column("Value", style="storm.value")
        table.add_column("Status", style="storm.status", justify="center")

        for metric_name, metric_value in metrics_dict.items():
            # Determine status based on value type and content
            if isinstance(metric_value, int | float):
                status = "✅ Good" if metric_value > 0 else "⚠️ Warning"
            elif isinstance(metric_value, str) and "error" in metric_value.lower():
                status = "❌ Error"
            else:
                status = "ℹ️ Info"

            table.add_row(metric_name, str(metric_value), status)

        self.safety.safe_print(console, table)

    def print_solution(self, message: str, subtitle: str | None = None) -> None:
        """Display solution messages with Storm branding."""
        console = self.get_console()

        solution_content = f"[storm.success]💡 Solution:[/storm.success]\n{message}"

        if subtitle:
            solution_content = f"[storm.info]{subtitle}[/storm.info]\n\n{solution_content}"

        self.safety.safe_panel(
            console, solution_content, style="storm-success", title="💡 Solution Found"
        )

    def print_django_spellbook_tip(self, tip: str) -> None:
        """Display Django-Spellbook tips with special branding."""
        console = self.get_console()

        tip_content = f"[storm.django]🔮 Django Spellbook Tip:[/storm.django]\n{tip}"

        self.safety.safe_panel(
            console, tip_content, style="storm-django", title="🔮 Django Spellbook"
        )

    def print_midas_optimization(self, optimization: str) -> None:
        """Display MIDAS optimization information with golden styling."""
        console = self.get_console()

        optimization_content = f"[storm.midas]⚡ MIDAS Optimization:[/storm.midas]\n{optimization}"

        self.safety.safe_panel(
            console,
            optimization_content,
            style="storm-midas",
            title="⚡ MIDAS WebAssembly Optimization",
        )

    def print_storm_animation_insight(self, insight: str) -> None:
        """Display Storm Animation insights with dynamic styling."""
        console = self.get_console()

        animation_content = (
            f"[storm.animation]🎬 Storm Animation Insight:[/storm.animation]\n{insight}"
        )

        self.safety.safe_panel(
            console,
            animation_content,
            style="storm-animation",
            title="🎬 60fps Storm Animation System",
        )


# Global console instance
_storm_console = None


def get_storm_console(
    config: StormLoggerConfig | None = None,
    console_factory: ConsoleFactory | None = None,
    syntax_factory: SyntaxFactory | None = None,
    progress_factory: ProgressFactory | None = None,
    component_factory: RichComponentFactory | None = None,
    theme_provider: ThemeProvider | None = None,
    config_provider: ConfigProvider | None = None,
    safety_provider: SafetyProvider | None = None,
) -> StormConsole:
    """Get the global Storm console instance."""
    global _storm_console  # noqa: PLW0603
    if _storm_console is None or config is not None:  # type: ignore[unreachable]
        _storm_console = StormConsole(
            config=config,
            console_factory=console_factory,
            syntax_factory=syntax_factory,
            progress_factory=progress_factory,
            component_factory=component_factory,
            theme_provider=theme_provider,
            config_provider=config_provider,
            safety_provider=safety_provider,
        )
    return _storm_console


# Convenience instance for backward compatibility
storm_console = get_storm_console()
