"""Plain text formatter for human-readable logs."""

from typing import Any

from ..core.backend import LogRecord
from .base import LogFormatter


class PlainFormatter(LogFormatter):
    """Formatter that outputs human-readable plain text logs."""

    def __init__(
        self,
        template: str = "{timestamp} - {level} - {logger} - {message}",
        format_template: str = None,
        include_extra: bool = True,
        extra_separator: str = " | ",
        timestamp_format: str = "iso",
        **kwargs: Any
    ) -> None:
        """Initialize plain text formatter.
        
        Args:
            template: Format template string with placeholders
            format_template: Backward compatibility alias for template
            include_extra: Include extra fields in output
            extra_separator: Separator for extra fields
            timestamp_format: Timestamp format ("iso" or "simple")
            **kwargs: Additional configuration
        """
        super().__init__(**kwargs)

        # Handle backward compatibility for format_template parameter
        if format_template is not None:
            template = format_template

        self.template = template
        self.format_template = template  # Backward compatibility attribute
        self.include_extra = include_extra
        self.extra_separator = extra_separator
        self.timestamp_format = timestamp_format

    def format(self, record: LogRecord) -> str:
        """Format log record as plain text string.
        
        Args:
            record: The log record to format
            
        Returns:
            Plain text formatted log message
        """
        data = self.format_dict(record)

        # Format main message using template
        try:
            formatted_message = self.template.format(**data)
        except KeyError:
            # Handle missing fields gracefully with safe_substitute approach
            from string import Template
            template = Template(self.template.replace("{", "${").replace("}", "}"))
            formatted_message = template.safe_substitute(**data)

        # Add extra fields if enabled
        if self.include_extra and record.extra:
            extra_parts = []
            for key, value in record.extra.items():
                extra_parts.append(f"{key}={value}")

            if extra_parts:
                extra_text = self.extra_separator.join(extra_parts)
                formatted_message = f"{formatted_message}{self.extra_separator}{extra_text}"

        # Add exception information if present
        if record.exc_info:
            exception_text = self._format_exception(record)
            if exception_text:
                formatted_message = f"{formatted_message}\n{exception_text}"

        # Add stack information if present
        if record.stack_info:
            formatted_message = f"{formatted_message}\nStack Info:\n{record.stack_info}"

        return formatted_message

    def format_dict(self, record: LogRecord) -> dict[str, Any]:
        """Format log record as dictionary for template substitution.
        
        Args:
            record: The log record to format
            
        Returns:
            Dictionary with template placeholder values
        """
        timestamp_str = self._format_timestamp(
            record,
            iso_format=(self.timestamp_format == "iso")
        )

        return {
            "timestamp": timestamp_str,
            "level": self._get_level_name(record.level),
            "logger": record.logger_name,
            "logger_name": record.logger_name,  # Backward compatibility
            "message": record.message,
        }
