"""
Centralized logging configuration for the autoclicker application.
Provides both file and console logging for easier debugging.
"""

import logging
import os
import sys
from logging.handlers import RotatingFileHandler
from pathlib import Path

def setup_logging(log_level=logging.INFO):
    """
    Set up logging to both file and console with consistent formatting.
    
    Args:
        log_level: Logging level (default: INFO)
    """
    # Env toggles
    disable_file_logging = (os.getenv("DISABLE_FILE_LOGS", "false").strip().lower() == "true")
    use_rotation = (os.getenv("LOG_ROTATE", "true").strip().lower() == "true")
    max_bytes_env = os.getenv("LOG_MAX_BYTES", "1048576")  # 1MB default
    backup_count_env = os.getenv("LOG_BACKUP_COUNT", "3")
    try:
        max_bytes = int(max_bytes_env)
    except Exception:
        max_bytes = 1048576
    try:
        backup_count = int(backup_count_env)
    except Exception:
        backup_count = 3

    # Create logs directory if it doesn't exist (only when file logging enabled)
    log_dir = Path("logs")
    if not disable_file_logging:
        log_dir.mkdir(exist_ok=True)
    
    # Clear any existing handlers to avoid duplicates
    root_logger = logging.getLogger()
    for handler in root_logger.handlers[:]:
        root_logger.removeHandler(handler)
    
    # Create formatter
    formatter = logging.Formatter(
        '%(asctime)s [%(levelname)s] %(name)s: %(message)s',
        datefmt='%H:%M:%S'
    )
    
    # Console handler for terminal output with UTF-8 encoding
    console_handler = logging.StreamHandler(sys.stdout)
    console_handler.setLevel(log_level)
    console_handler.setFormatter(formatter)
    # Force UTF-8 encoding for Windows console
    if sys.platform == 'win32':
        console_handler.stream.reconfigure(encoding='utf-8')
    
    # Optional file handler (rotating by default)
    file_handler = None
    if not disable_file_logging:
        if use_rotation:
            file_handler = RotatingFileHandler('logs/app_debug.log', mode='a', maxBytes=max_bytes, backupCount=backup_count, encoding='utf-8')
        else:
            file_handler = logging.FileHandler('logs/app_debug.log', mode='a', encoding='utf-8')
        file_handler.setLevel(log_level)
        file_handler.setFormatter(formatter)
    
    # Configure root logger
    root_logger.setLevel(log_level)
    root_logger.addHandler(console_handler)
    if file_handler is not None:
        root_logger.addHandler(file_handler)
    
    # Also set up specific loggers for different modules
    loggers = [
        'autoclicker.playlist_manager',
        'autoclicker.recording',
        'autoclicker.playback',
        'autoclicker.direct_integration',
        'mysql.mysql_client'
    ]
    
    for logger_name in loggers:
        logger = logging.getLogger(logger_name)
        logger.setLevel(log_level)
        # Don't add handlers here - they inherit from root logger
    
    if disable_file_logging:
        logging.info("Logging initialized - console only (file logging disabled)")
    else:
        logging.info("Logging initialized - console + logs/app_debug.log")

def get_logger(name):
    """Get a logger for a specific module."""
    return logging.getLogger(name)
