"""Console backend for logging to stdout/stderr."""

from __future__ import annotations

import sys
from dataclasses import dataclass
from typing import Any, TextIO

from ..core.backend import BackendConfig, LoggingBackend, LogRecord
from ..formatters import LogFormatter, PlainFormatter


@dataclass
class ConsoleBackendConfig(BackendConfig):
    """Configuration for console backend."""

    enabled: bool = True
    timeout: float = 1.0
    retry_attempts: int = 0
    retry_delay: float = 0.1
    stream: str = "stdout"  # "stdout" or "stderr"
    use_colors: bool = True
    use_stderr: bool = False  # Alternative way to specify stderr


class ConsoleBackend(LoggingBackend):
    """Backend that logs to console (stdout/stderr)."""

    def __init__(
        self,
        name: str = "console",
        config: ConsoleBackendConfig | None = None,
        formatter: LogFormatter | None = None,
        **kwargs: Any
    ) -> None:
        """Initialize console backend.
        
        Args:
            name: Backend name
            config: Backend configuration
            formatter: Log formatter to use
            **kwargs: Additional configuration
        """
        self.config = config or ConsoleBackendConfig()
        super().__init__(name, self.config, **kwargs)

        self.formatter = formatter or PlainFormatter()
        # Support both stream and use_stderr for backwards compatibility
        use_stderr = self.config.use_stderr or self.config.stream == "stderr"
        self._stream: TextIO = sys.stderr if use_stderr else sys.stdout

        # ANSI color codes for different log levels
        self._colors = {
            10: "\033[36m",     # DEBUG - Cyan
            20: "\033[32m",     # INFO - Green
            30: "\033[33m",     # WARNING - Yellow
            40: "\033[31m",     # ERROR - Red
            50: "\033[35m",     # CRITICAL - Magenta
        } if self.config.use_colors else {}
        self._reset_color = "\033[0m" if self.config.use_colors else ""

    async def connect(self) -> None:
        """Connect to console (always available)."""
        self._connected = True

    async def disconnect(self) -> None:
        """Disconnect from console."""
        if hasattr(self._stream, 'flush'):
            self._stream.flush()
        self._connected = False

    async def send_log(self, record: LogRecord) -> bool:
        """Send log record to console.
        
        Args:
            record: The log record to send
            
        Returns:
            True if successfully written, False otherwise
        """
        try:
            formatted_message = self.formatter.format(record)

            # Add color if enabled
            if self.config.use_colors and record.level in self._colors:
                color = self._colors[record.level]
                formatted_message = f"{color}{formatted_message}{self._reset_color}"

            # Write to stream (use sys.stdout/stderr dynamically for testability)
            stream = sys.stderr if self.config.use_stderr or self.config.stream == "stderr" else sys.stdout
            print(formatted_message, file=stream)

            # Flush immediately for real-time output
            if hasattr(stream, 'flush'):
                stream.flush()

            return True
        except Exception:
            return False

    async def health_check(self) -> bool:
        """Check if console is available.
        
        Returns:
            True if console is available, False otherwise
        """
        try:
            # Test if we can write to the stream
            return hasattr(self._stream, 'write') and callable(self._stream.write)
        except Exception:
            return False
