import logging
import os
import sys
from datetime import datetime

class ColorFormatter(logging.Formatter):
    """Custom formatter with cross-platform color support"""

    # ANSI color codes
    COLORS = {
        'DEBUG': '\033[90m',    # Gray
        'INFO': '\033[0m',      # White (default)
        'WARNING': '\033[93m',  # Yellow
        'ERROR': '\033[91m',    # Red
        'RESET': '\033[0m'      # Reset
    }

    # Windows color support
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.use_colors = self._supports_color()

        # Enable Windows color support if available
        if sys.platform == "win32" and self.use_colors:
            try:
                import colorama
                colorama.init()
            except ImportError:
                # Try to enable Windows 10 ANSI support
                try:
                    import ctypes
                    kernel32 = ctypes.windll.kernel32
                    kernel32.SetConsoleMode(kernel32.GetStdHandle(-11), 7)
                except:
                    self.use_colors = False

    def _supports_color(self):
        """Check if terminal supports color"""
        # Check if output is redirected
        if not hasattr(sys.stdout, 'isatty') or not sys.stdout.isatty():
            return False

        # Windows and Unix-like systems
        if sys.platform == "win32":
            return True  # We'll handle Windows color support in __init__
        else:
            # Unix-like systems
            return 'TERM' in os.environ and os.environ['TERM'] != 'dumb'

    def format(self, record):
        # Simple format: [HH:MM:SS] message
        timestamp = datetime.fromtimestamp(record.created).strftime('%H:%M:%S')
        message = record.getMessage()
        if record.exc_info:
            message += "\n" + self.formatException(record.exc_info)

        # Ensure message is safe for console output
        try:
            # Try to encode/decode to catch problematic characters
            message.encode('utf-8')
        except UnicodeEncodeError:
            # Replace problematic characters
            message = message.encode('utf-8', errors='replace').decode('utf-8')

        if self.use_colors:
            color = self.COLORS.get(record.levelname, self.COLORS['INFO'])
            reset = self.COLORS['RESET']
            return f"{color}[{timestamp}] {message}{reset}"
        else:
            return f"[{timestamp}] {message}"