"""
Logging utilities for MbetterClient
"""

import os
import logging
import logging.handlers
from pathlib import Path
from typing import Optional


def setup_logging(level: int = logging.INFO, log_file: Optional[str] = None, 
                 component: Optional[str] = None) -> logging.Logger:
    """Setup application logging with file and console handlers"""
    
    # Create logger name
    logger_name = f"mbetterclient"
    if component:
        logger_name += f".{component}"
    
    # Get logger
    logger = logging.getLogger(logger_name)
    logger.setLevel(level)
    
    # Clear existing handlers
    logger.handlers.clear()
    
    # Create formatters
    console_formatter = logging.Formatter(
        '%(asctime)s - %(name)s - %(levelname)s - %(message)s',
        datefmt='%Y-%m-%d %H:%M:%S'
    )
    
    file_formatter = logging.Formatter(
        '%(asctime)s - %(name)s - %(levelname)s - %(funcName)s:%(lineno)d - %(message)s',
        datefmt='%Y-%m-%d %H:%M:%S'
    )
    
    # Console handler
    console_handler = logging.StreamHandler()
    console_handler.setLevel(level)
    console_handler.setFormatter(console_formatter)
    logger.addHandler(console_handler)
    
    # File handler
    if log_file:
        # Ensure log directory exists
        log_path = Path(log_file)
        log_path.parent.mkdir(parents=True, exist_ok=True)
        
        # Rotating file handler
        file_handler = logging.handlers.RotatingFileHandler(
            log_file,
            maxBytes=10 * 1024 * 1024,  # 10MB
            backupCount=5,
            encoding='utf-8'
        )
        file_handler.setLevel(logging.DEBUG)
        file_handler.setFormatter(file_formatter)
        logger.addHandler(file_handler)
    
    # Prevent propagation to root logger
    logger.propagate = False
    
    return logger


def get_logger(name: str = "mbetterclient") -> logging.Logger:
    """Get existing logger instance"""
    return logging.getLogger(name)


def setup_loguru_logging(log_file: Optional[str] = None, level: str = "INFO") -> None:
    """Setup loguru-based logging as alternative"""
    try:
        from loguru import logger as loguru_logger
    except ImportError:
        raise ImportError("loguru is required for setup_loguru_logging but is not installed")
    
    # Remove default handler
    loguru_logger.remove()
    
    # Console logging
    loguru_logger.add(
        sink=lambda message: print(message, end=""),
        level=level,
        format="<green>{time:YYYY-MM-DD HH:mm:ss}</green> | "
               "<level>{level: <8}</level> | "
               "<cyan>{name}</cyan>:<cyan>{function}</cyan>:<cyan>{line}</cyan> | "
               "<level>{message}</level>",
        colorize=True
    )
    
    # File logging
    if log_file:
        log_path = Path(log_file)
        log_path.parent.mkdir(parents=True, exist_ok=True)
        
        loguru_logger.add(
            sink=log_file,
            level="DEBUG",
            format="{time:YYYY-MM-DD HH:mm:ss} | {level: <8} | {name}:{function}:{line} | {message}",
            rotation="10 MB",
            retention="7 days",
            compression="zip",
            encoding="utf-8"
        )


class ComponentLogger:
    """Logger wrapper for components with automatic component name"""
    
    def __init__(self, component_name: str, base_logger: Optional[logging.Logger] = None):
        self.component_name = component_name
        if base_logger:
            self.logger = base_logger.getChild(component_name)
        else:
            self.logger = logging.getLogger(f"mbetterclient.{component_name}")
    
    def debug(self, message: str, **kwargs):
        """Log debug message"""
        self.logger.debug(f"[{self.component_name}] {message}", **kwargs)
    
    def info(self, message: str, **kwargs):
        """Log info message"""
        self.logger.info(f"[{self.component_name}] {message}", **kwargs)
    
    def warning(self, message: str, **kwargs):
        """Log warning message"""
        self.logger.warning(f"[{self.component_name}] {message}", **kwargs)
    
    def error(self, message: str, **kwargs):
        """Log error message"""
        self.logger.error(f"[{self.component_name}] {message}", **kwargs)
    
    def critical(self, message: str, **kwargs):
        """Log critical message"""
        self.logger.critical(f"[{self.component_name}] {message}", **kwargs)
    
    def exception(self, message: str, **kwargs):
        """Log exception with traceback"""
        self.logger.exception(f"[{self.component_name}] {message}", **kwargs)