"""
Logging utilities for Core CLI.
"""

import logging
import sys
from pathlib import Path
from typing import Optional


def setup_logger(name: str = 'core-cli', verbose: bool = False, log_file: Optional[str] = None) -> logging.Logger:
    """Set up logging configuration."""
    # Create logger
    logger = logging.getLogger(name)
    logger.setLevel(logging.DEBUG if verbose else logging.INFO)
    
    # Clear existing handlers
    logger.handlers.clear()
    
    # Create console handler
    console_handler = logging.StreamHandler(sys.stdout)
    console_handler.setLevel(logging.DEBUG if verbose else logging.INFO)
    
    # Create formatter
    if verbose:
        console_format = logging.Formatter(
            '%(asctime)s - %(name)s - %(levelname)s - %(message)s',
            datefmt='%Y-%m-%d %H:%M:%S'
        )
    else:
        console_format = logging.Formatter('%(levelname)s: %(message)s')
    
    console_handler.setFormatter(console_format)
    logger.addHandler(console_handler)
    
    # Add file handler if specified or use default .logs directory
    if log_file or verbose:
        if log_file:
            log_path = Path(log_file)
        else:
            # Use .logs directory relative to this file's parent (cli folder)
            cli_dir = Path(__file__).parent.parent
            logs_dir = cli_dir / ".logs"
            logs_dir.mkdir(exist_ok=True)
            log_path = logs_dir / "core-cli.log"
        
        log_path.parent.mkdir(parents=True, exist_ok=True)
        
        file_handler = logging.FileHandler(log_path)
        file_handler.setLevel(logging.DEBUG)
        
        file_format = logging.Formatter(
            '%(asctime)s - %(name)s - %(levelname)s - %(funcName)s:%(lineno)d - %(message)s',
            datefmt='%Y-%m-%d %H:%M:%S'
        )
        file_handler.setFormatter(file_format)
        logger.addHandler(file_handler)
    
    return logger


class ColoredFormatter(logging.Formatter):
    """Colored log formatter."""
    
    COLORS = {
        'DEBUG': '\033[36m',    # Cyan
        'INFO': '\033[32m',     # Green
        'WARNING': '\033[33m',  # Yellow
        'ERROR': '\033[31m',    # Red
        'CRITICAL': '\033[35m', # Magenta
    }
    RESET = '\033[0m'
    
    def format(self, record):
        log_color = self.COLORS.get(record.levelname, '')
        record.levelname = f"{log_color}{record.levelname}{self.RESET}"
        return super().format(record)
