"""Base formatter interface for log formatting."""

import logging
from abc import ABC, abstractmethod
from typing import Any

from ..core.backend import LogRecord


class LogFormatter(ABC):
    """Abstract base class for log formatters."""

    def __init__(self, **kwargs: Any) -> None:
        """Initialize the formatter.
        
        Args:
            **kwargs: Formatter-specific configuration
        """
        self.config = kwargs

    @abstractmethod
    def format(self, record: LogRecord) -> str:
        """Format a log record into a string.
        
        Args:
            record: The log record to format
            
        Returns:
            Formatted log message as string
        """
        pass

    @abstractmethod
    def format_dict(self, record: LogRecord) -> dict[str, Any]:
        """Format a log record into a dictionary.
        
        Args:
            record: The log record to format
            
        Returns:
            Formatted log message as dictionary
        """
        pass

    def _get_level_name(self, level: int) -> str:
        """Get string name for logging level.
        
        Args:
            level: Numeric logging level
            
        Returns:
            String name for the level
        """
        return logging.getLevelName(level)

    def _format_timestamp(self, record: LogRecord, iso_format: bool = True) -> str:
        """Format timestamp from log record.
        
        Args:
            record: The log record
            iso_format: Whether to use ISO format (default) or custom format
            
        Returns:
            Formatted timestamp string
        """
        if iso_format:
            return record.timestamp.isoformat()
        else:
            return record.timestamp.strftime("%Y-%m-%d %H:%M:%S.%f")[:-3]

    def _format_exception(self, record: LogRecord) -> str:
        """Format exception information from log record.
        
        Args:
            record: The log record
            
        Returns:
            Formatted exception string, empty if no exception
        """
        if record.exc_info:
            import traceback
            return ''.join(traceback.format_exception(*record.exc_info))
        return ""
