import logging
import os

try:
    from concurrent_log_handler import ConcurrentRotatingFileHandler as RFHandler
except ImportError:
    pass  # Fallback # type: ignore
import sys  # Add this
from pathlib import Path  # Ensure Path is imported
from typing import Union, Optional  # Ensure Optional and List are imported

# If this logger module also needs access to CONFIG for MAX_BYTES etc.,
# it's better to pass those values directly or have a separate config mechanism
# accessible here, rather than relying on gui.py's CONFIG.
# For simplicity, assuming those values are hardcoded here or passed if needed.
LOG_MAX_BYTES_DEFAULT = 10 * 1024 * 1024  # 10 MB
LOG_BACKUP_COUNT_DEFAULT = 5

_LOGGING_CONFIGURED = False  # Sentinel flag at module level


# Use Union for Python 3.9 compatibility
def configure_logging(
    log_file: Path,  # Changed to Path and made mandatory as per new spec
    level: Union[str, int] = "INFO",
    # Add a distinct logger for configuration messages to avoid confusion
    app_version: str = "Unknown",  # Added app_version
) -> None:
    """Configure root logging exactly once per process."""
    # Get the name of the module that called this function
    # sys._getframe(1) gets the frame of the caller.
    # f_globals['__name__'] gets the __name__ variable from the caller's global scope.
    caller_name = sys._getframe(1).f_globals.get("__name__", "unknown_caller")
    logger_for_this_message = logging.getLogger(
        "fmatch.logger_config"
    )  # Use a distinct logger name
    # Use a distinct logger for messages about the logging setup itself
    config_event_logger = logging.getLogger(
        "fmatch.logger_config_process"
    )  # Fixed name
    # Temporarily set a basic config for this logger if no handlers exist, so its messages appear
    if not logging.getLogger().hasHandlers() and not config_event_logger.hasHandlers():
        logging.basicConfig(level="INFO", handlers=[logging.StreamHandler(sys.stdout)])
        config_event_logger = logging.getLogger(
            "fmatch.logger_config_process"
        )  # Re-fetch after basicConfig

    global _LOGGING_CONFIGURED
    if _LOGGING_CONFIGURED:
        config_event_logger.info(
            f"configure_logging call from '{caller_name}' (level: {level}) skipped, "
            f"as logging was already configured. "
            f"Current Root Level: {logging.getLevelName(logging.getLogger().getEffectiveLevel())}"
        )
        return

    if os.getenv("FM_TEST_MODE") == "1" or os.getenv("FM_UNIT_TEST") == "1":
        level = os.getenv("LOG_LEVEL", level)
    log_level = getattr(logging, str(level).upper(), logging.INFO)

    log_formatter = logging.Formatter(
        "%(asctime)s | %(levelname)-8s | %(processName)s (%(process)d) | %(threadName)s | %(name)s - %(filename)s:%(lineno)d | %(funcName)s | %(message)s",
        datefmt="%Y-%m-%d %H:%M:%S",
    )

    # file handler …
    file_handler: Optional[logging.handlers.RotatingFileHandler] = None
    try:
        log_file.parent.mkdir(parents=True, exist_ok=True)
        file_handler = logging.handlers.RotatingFileHandler(
            log_file,
            maxBytes=LOG_MAX_BYTES_DEFAULT,
            backupCount=LOG_BACKUP_COUNT_DEFAULT,
            encoding="utf-8",
        )
        file_handler.setFormatter(log_formatter)
        file_handler.setLevel(log_level)
    except Exception as e:
        print(
            f"ERROR: Could not configure file logger at {log_file}: {e}",
            file=sys.stderr,
        )
        file_handler = None

    # stderr handler …
    console_handler = logging.StreamHandler(sys.stdout)  # Changed to stdout
    console_handler.setFormatter(
        logging.Formatter("%(asctime)s %(levelname)-8s [%(name)s] %(message)s")
    )
    console_handler.setLevel(logging.INFO if log_level == logging.DEBUG else log_level)

    root_logger = logging.getLogger()
    if root_logger.hasHandlers():
        test_mode = os.getenv("FM_TEST_MODE") == "1" or os.getenv("FM_UNIT_TEST") == "1"
        for handler in root_logger.handlers[:]:
            root_logger.removeHandler(handler)
            if test_mode and isinstance(handler, logging.StreamHandler):
                # Avoid closing pytest capture streams during tests.
                continue
            handler.close()
    root_logger.setLevel(log_level)
    if file_handler:
        root_logger.addHandler(file_handler)
    root_logger.addHandler(console_handler)

    _LOGGING_CONFIGURED = True  # Set flag AFTER successful configuration

    logging.info(f"--- Logging configured by fmatch.logger (v{app_version}) ---")
    if file_handler:
        logging.info(f"Logging to file: {log_file.resolve()}")
    else:
        logging.warning("File logging is not active due to an earlier error.")
    logging.info(f"Root logger level set to: {str(level).upper()}")


# Example of how to get a logger in other modules:
# import logging
# logger = logging.getLogger(__name__)
# logger.info("This is a message from another module.")
