"""
Console UI Module

Rich console wrapper with terminal capability detection.

v2.0 Critical Fix #4: Terminal capability detection for dark/light mode support.
"""

import os
import sys

from rich.console import Console as RichConsole
from rich.markdown import Markdown
from rich.panel import Panel
from rich.prompt import Confirm, Prompt
from rich.theme import Theme

from honeydb_ai.domain.interfaces import Console as ConsoleInterface
from honeydb_ai.domain.models import Event
from honeydb_ai.utils.formatters import format_event_data


class RichConsoleUI(ConsoleInterface):
    """
    Console UI implementation using Rich library.

    v2.0 Critical: Includes terminal capability detection and color adjustment.
    """

    def __init__(self, theme: str = "auto"):
        """
        Initialize console with theme detection.

        Args:
            theme: Theme setting ("auto", "dark", "light")
        """
        self.theme_setting = theme
        self.capabilities = self.detect_terminal_capabilities()

        # Adjust theme based on detection
        if theme == "auto":
            detected_theme = "dark" if self.capabilities.get("dark_mode", True) else "light"
        else:
            detected_theme = theme

        # Create custom theme with appropriate colors
        custom_theme = self._create_theme(detected_theme)

        self.console = RichConsole(
            theme=custom_theme,
            force_terminal=self.capabilities.get("color_support", True),
            force_interactive=True,
        )

    def _create_theme(self, theme: str) -> Theme:
        """
        Create Rich theme based on terminal background.

        v2.0 Critical: Adjusts colors for readability on dark/light backgrounds.

        Args:
            theme: "dark" or "light"

        Returns:
            Rich Theme object
        """
        if theme == "dark":
            # Colors optimized for dark backgrounds
            return Theme({
                "info": "cyan",
                "warning": "yellow",
                "error": "red bold",
                "success": "green",
                "prompt": "bright_blue",
                "assistant": "bright_green",
                "user": "bright_cyan",
                "system": "bright_magenta",
                "tool": "yellow",
                "dim": "dim white",
            })
        else:
            # Colors optimized for light backgrounds
            return Theme({
                "info": "blue",
                "warning": "dark_orange",
                "error": "red bold",
                "success": "dark_green",
                "prompt": "blue",
                "assistant": "dark_green",
                "user": "dark_cyan",
                "system": "dark_magenta",
                "tool": "dark_orange",
                "dim": "dim black",
            })

    def detect_terminal_capabilities(self) -> dict[str, bool]:
        """
        Detect terminal capabilities.

        v2.0 Critical Fix #4: Detects dark/light mode and color support.

        Returns:
            Dictionary with capabilities:
            - "color_support": True if terminal supports colors
            - "unicode_support": True if terminal supports Unicode
            - "dark_mode": True if terminal has dark background
            - "is_tty": True if stdout is a TTY (interactive terminal)
        """
        capabilities = {
            "color_support": True,
            "unicode_support": True,
            "dark_mode": True,  # Default to dark mode
            "is_tty": sys.stdout.isatty(),
        }

        # Detect color support
        if not capabilities["is_tty"]:
            capabilities["color_support"] = False

        # Check common environment variables that indicate no color
        no_color = os.getenv("NO_COLOR")
        if no_color:
            capabilities["color_support"] = False

        # Detect Unicode support
        encoding = sys.stdout.encoding
        if encoding and "utf" not in encoding.lower():
            capabilities["unicode_support"] = False

        # Detect dark/light mode
        # Method 1: Check COLORFGBG environment variable (used by some terminals)
        colorfgbg = os.getenv("COLORFGBG")
        if colorfgbg:
            # Format is typically "foreground;background"
            # Light background typically has high value (>7), dark has low (<=7)
            try:
                parts = colorfgbg.split(";")
                if len(parts) >= 2:
                    bg = int(parts[-1])
                    capabilities["dark_mode"] = bg <= 7
            except (ValueError, IndexError):
                pass  # Keep default

        # Method 2: Check specific terminal variables
        term_program = os.getenv("TERM_PROGRAM", "").lower()
        if "light" in term_program:
            capabilities["dark_mode"] = False
        elif "dark" in term_program:
            capabilities["dark_mode"] = True

        # Method 3: Check if running in known light-mode environments
        if os.getenv("ITERM_PROFILE", "").lower() in ["light", "solarized light"]:
            capabilities["dark_mode"] = False

        return capabilities

    def print(self, text: str, style: str | None = None) -> None:
        """Print text to console with optional styling."""
        self.console.print(text, style=style)

    def print_markdown(self, markdown: str) -> None:
        """
        Render and print markdown content.

        v2.0: Chunks large content to avoid blocking UI.
        """
        # For very large markdown (>10KB), chunk it
        if len(markdown) > 10000:
            # Split by paragraphs
            chunks = markdown.split("\n\n")
            for chunk in chunks:
                if chunk.strip():
                    md = Markdown(chunk)
                    self.console.print(md)
        else:
            md = Markdown(markdown)
            self.console.print(md)

    def print_error(self, message: str) -> None:
        """Print an error message."""
        self.console.print(f"❌ {message}", style="error")

    def print_success(self, message: str) -> None:
        """Print a success message."""
        self.console.print(f"✅ {message}", style="success")

    def print_warning(self, message: str) -> None:
        """Print a warning message."""
        self.console.print(f"⚠️  {message}", style="warning")

    def print_event(self, event: Event) -> None:
        """
        Print an event (e.g., tool call notification).

        v2.0 Critical Fix #3: Real-time display of MCP tool invocations.
        """
        formatted = format_event_data(event.type, event.data)
        self.console.print(formatted, style="tool")

    def prompt(self, message: str, default: str | None = None) -> str:
        """Prompt user for input."""
        return Prompt.ask(message, default=default, console=self.console)

    def confirm(self, message: str, default: bool = False) -> bool:
        """Prompt user for yes/no confirmation."""
        return Confirm.ask(message, default=default, console=self.console)

    def print_panel(self, content: str, title: str | None = None, style: str = "info") -> None:
        """Print content in a panel."""
        panel = Panel(content, title=title, border_style=style)
        self.console.print(panel)

    def print_divider(self, char: str = "─") -> None:
        """Print a horizontal divider."""
        width = self.console.width
        if self.capabilities.get("unicode_support", True):
            self.console.print(char * width, style="dim")
        else:
            self.console.print("-" * width, style="dim")

    def print_banner(self) -> None:
        """Print HoneyDB ASCII art banner."""
        banner = """
 ██╗  ██╗ ██████╗ ███╗   ██╗███████╗██╗   ██╗██████╗ ██████╗
 ██║  ██║██╔═══██╗████╗  ██║██╔════╝╚██╗ ██╔╝██╔══██╗██╔══██╗
 ███████║██║   ██║██╔██╗ ██║█████╗   ╚████╔╝ ██║  ██║██████╔╝
 ██╔══██║██║   ██║██║╚██╗██║██╔══╝    ╚██╔╝  ██║  ██║██╔══██╗
 ██║  ██║╚██████╔╝██║ ╚████║███████╗   ██║   ██████╔╝██████╔╝
 ╚═╝  ╚═╝ ╚═════╝ ╚═╝  ╚═══╝╚══════╝   ╚═╝   ╚═════╝ ╚═════╝
        """
        self.console.print(banner, style="bold #B87333", justify="left")
        self.console.print(
            "Threat Intelligence Chat Interface",
            style="dim italic",
            justify="left"
        )
        self.console.print()  # Empty line for spacing

    def clear(self) -> None:
        """Clear the console screen."""
        self.console.clear()

    def get_width(self) -> int:
        """Get console width in characters."""
        return self.console.width

    def get_height(self) -> int:
        """Get console height in lines."""
        return self.console.height
