"""
Logger utility for detailed colored output with progress tracking
"""
import sys
from datetime import datetime
from typing import Optional
from enum import Enum


class LogLevel(Enum):
    INFO = "INFO"
    SUCCESS = "SUCCESS"
    WARNING = "WARNING"
    ERROR = "ERROR"
    DEBUG = "DEBUG"


class Color:
    """ANSI color codes"""
    RESET = "\033[0m"
    RED = "\033[91m"
    GREEN = "\033[92m"
    YELLOW = "\033[93m"
    BLUE = "\033[94m"
    MAGENTA = "\033[95m"
    CYAN = "\033[96m"
    WHITE = "\033[97m"
    BOLD = "\033[1m"


class Logger:
    """Detailed logger with colors and progress tracking"""
    
    def __init__(self, verbose: bool = True, version: str = None):
        self.verbose = verbose
        self.version = version
        self.start_time = datetime.now()
        self.checks_passed = 0
        self.checks_failed = 0
        self.checks_warnings = 0
        self.errors = []
        self.warnings = []
        
    def _get_timestamp(self) -> str:
        """Get formatted timestamp"""
        return datetime.now().strftime("%H:%M:%S")
    
    def _colorize(self, text: str, color: str) -> str:
        """Apply color to text"""
        return f"{color}{text}{Color.RESET}"
    
    def _log(self, level: LogLevel, category: str, message: str, 
             success: Optional[bool] = None):
        """Internal log method"""
        if not self.verbose:
            return
            
        timestamp = self._get_timestamp()
        
        # Determine color based on level or success state
        if success is True:
            color = Color.GREEN
            symbol = "✓"
        elif success is False:
            color = Color.RED
            symbol = "✗"
        elif level == LogLevel.SUCCESS:
            color = Color.GREEN
            symbol = "✓"
        elif level == LogLevel.ERROR:
            color = Color.RED
            symbol = "✗"
        elif level == LogLevel.WARNING:
            color = Color.YELLOW
            symbol = "⚠"
        else:
            color = Color.CYAN
            symbol = "•"
        
        category_colored = self._colorize(f"[{category}]", Color.BOLD + Color.BLUE)
        level_colored = self._colorize(f"[{level.value}]", color)
        
        print(f"{timestamp} {category_colored} {level_colored} {message} {symbol}")
        
        # Track statistics
        if success is True:
            self.checks_passed += 1
        elif success is False:
            self.checks_failed += 1
            self.errors.append(f"{category}: {message}")
        elif level == LogLevel.WARNING:
            self.checks_warnings += 1
    
    def info(self, category: str, message: str):
        """Log info message"""
        self._log(LogLevel.INFO, category, message)
    
    def success(self, category: str, message: str):
        """Log success message"""
        self._log(LogLevel.SUCCESS, category, message, success=True)
    
    def warning(self, category: str, message: str):
        """Log warning message"""
        self._log(LogLevel.WARNING, category, message)
    
    def warning_with_details(self, category: str, message: str, details: str):
        """Log warning message with details"""
        self._log(LogLevel.WARNING, category, message)
        self.warnings.append({
            "category": category,
            "message": message,
            "details": details
        })
    
    def error(self, category: str, message: str):
        """Log error message"""
        self._log(LogLevel.ERROR, category, message, success=False)
    
    def debug(self, category: str, message: str):
        """Log debug message"""
        self._log(LogLevel.DEBUG, category, message)
    
    def header(self, text: str):
        """Print section header"""
        if not self.verbose:
            return
        print()
        print(self._colorize("=" * 60, Color.BOLD + Color.CYAN))
        print(self._colorize(f"  {text}", Color.BOLD + Color.CYAN))
        print(self._colorize("=" * 60, Color.BOLD + Color.CYAN))
    
    def subheader(self, text: str):
        """Print subsection header"""
        if not self.verbose:
            return
        print()
        print(self._colorize(f"  {text}", Color.BOLD + Color.MAGENTA))
        print(self._colorize("-" * 40, Color.MAGENTA))
    
    def progress(self, category: str, message: str, current: int, total: int):
        """Show progress bar"""
        if not self.verbose:
            return
            
        percentage = (current / total) * 100
        bar_length = 30
        filled = int(bar_length * current / total)
        bar = "█" * filled + "░" * (bar_length - filled)
        
        timestamp = self._get_timestamp()
        category_colored = self._colorize(f"[{category}]", Color.BOLD + Color.BLUE)
        bar_colored = self._colorize(bar, Color.GREEN)
        
        # Print message and bar on same line for cleaner output
        print(f"{timestamp} {category_colored} {message} [{bar_colored}] {percentage:.1f}% ({current}/{total})")
    
    def print_summary(self):
        """Print final summary"""
        if not self.verbose:
            return
        
        elapsed = datetime.now() - self.start_time
        total_checks = self.checks_passed + self.checks_failed
        
        print()
        print(self._colorize("=" * 60, Color.BOLD + Color.CYAN))
        print(self._colorize("  SUMMARY", Color.BOLD + Color.CYAN))
        print(self._colorize("=" * 60, Color.BOLD + Color.CYAN))
        print()
        print(f"  Total checks: {total_checks}")
        print(f"  {self._colorize('Passed:', Color.GREEN)} {self.checks_passed}")
        print(f"  {self._colorize('Failed:', Color.RED)} {self.checks_failed}")
        print(f"  {self._colorize('Warnings:', Color.YELLOW)} {self.checks_warnings}")
        print(f"  Total time: {elapsed.total_seconds():.2f}s")
        print()
        
        if self.warnings:
            print(self._colorize("  WARNINGS:", Color.BOLD + Color.YELLOW))
            for warning in self.warnings:
                print(f"    - [{warning['category']}] {warning['message']}")
                print(f"      {warning['details']}")
            print()
        
        if self.errors:
            print(self._colorize("  ERRORS:", Color.BOLD + Color.RED))
            for error in self.errors:
                print(f"    - {error}")
            print()
        
        if self.checks_failed == 0:
            print(self._colorize("  ✓ All tests passed!", Color.BOLD + Color.GREEN))
        else:
            print(self._colorize("  ✗ Some tests failed!", Color.BOLD + Color.RED))
        
        print()
