"""
Storm Logger Base Implementation
Core logging functionality abstracted from framework dependencies
"""

import logging
from abc import ABC, abstractmethod
from typing import Any

from ..config import StormLoggerConfig, get_config
from ..interfaces import LoggerInterface
from .base_implementations import (
    DefaultConfigurationBuilder,
    DefaultDependencyChecker,
    DefaultDirectoryManager,
    DefaultFormatterFactory,
    DefaultLoggerFactory,
)
from .base_interfaces import (
    ConfigurationBuilder,
    DependencyChecker,
    DirectoryManager,
    LoggerFactory,
)


class BaseStormLogger(LoggerInterface, ABC):
    """
    Abstract base class for Storm Logger implementations.

    This class defines the interface that all Storm Logger implementations
    must follow, enabling framework-specific customizations while maintaining
    consistent core functionality.
    """

    def __init__(
        self,
        name: str,
        config: StormLoggerConfig | None = None,
        logger_factory: LoggerFactory | None = None,
        directory_manager: DirectoryManager | None = None,
    ):
        self.name = name
        self.config = config or get_config()
        self._logger = None
        self._handlers_configured = False

        # Use injected dependencies or create defaults
        self._logger_factory = logger_factory or DefaultLoggerFactory()
        self._directory_manager = directory_manager or DefaultDirectoryManager()

    @property
    def logger(self) -> Any:
        """Get the underlying logger instance."""
        if self._logger is None:
            self._logger = self._logger_factory.get_logger(self.name)
            self._configure_logger()
        return self._logger

    def _configure_logger(self) -> None:
        """Configure the underlying logger with Storm settings."""
        if self._handlers_configured:
            return

        # Set log level
        self._logger_factory.set_level(self.logger, self.config.get_logging_level())

        # Create log directories
        self._directory_manager.create_directories(self.config)

        # Configure handlers
        self._configure_handlers()

        # Configure formatters
        self._configure_formatters()

        self._handlers_configured = True

    @abstractmethod
    def _configure_handlers(self) -> None:
        """Configure log handlers (implemented by subclasses)."""
        pass

    @abstractmethod
    def _configure_formatters(self) -> None:
        """Configure log formatters (implemented by subclasses)."""
        pass

    def debug(self, message: str, **kwargs: Any) -> None:
        """Log a debug message."""
        self._logger_factory.log(self.logger, logging.DEBUG, message, **kwargs)

    def info(self, message: str, **kwargs: Any) -> None:
        """Log an info message."""
        self._logger_factory.log(self.logger, logging.INFO, message, **kwargs)

    def warning(self, message: str, **kwargs: Any) -> None:
        """Log a warning message."""
        self._logger_factory.log(self.logger, logging.WARNING, message, **kwargs)

    def error(self, message: str, exc_info: bool = False, **kwargs: Any) -> None:
        """Log an error message."""
        kwargs["exc_info"] = exc_info
        self._logger_factory.log(self.logger, logging.ERROR, message, **kwargs)

    def critical(self, message: str, exc_info: bool = False, **kwargs: Any) -> None:
        """Log a critical message."""
        kwargs["exc_info"] = exc_info
        self._logger_factory.log(self.logger, logging.CRITICAL, message, **kwargs)

    def exception(self, message: str, **kwargs: Any) -> None:
        """Log an exception with traceback."""
        kwargs["exc_info"] = True
        self._logger_factory.log(self.logger, logging.ERROR, message, **kwargs)

    def log(self, level: int, message: str, **kwargs: Any) -> None:
        """Log at a specific level."""
        self._logger_factory.log(self.logger, level, message, **kwargs)

    def success(self, message: str, **kwargs: Any) -> None:
        """Log a success message."""
        self.info(f"✅ SUCCESS: {message}", **kwargs)

    def test_pass(self, test_name: str, **kwargs: Any) -> None:
        """Log a passed test."""
        self.info(f"✅ PASS: {test_name}", **kwargs)

    def test_fail(self, test_name: str, error_message: str = "", **kwargs: Any) -> None:
        """Log a failed test."""
        msg = f"❌ FAIL: {test_name}"
        if error_message:
            msg += f" - {error_message}"
        self.error(msg, **kwargs)

    def helpful_tip(self, message: str, **kwargs: Any) -> None:
        """Log a helpful development tip."""
        self.info(f"💡 TIP: {message}", **kwargs)

    def teaching_moment(self, message: str, **kwargs: Any) -> None:
        """Log educational content."""
        self.info(f"📚 LEARN: {message}", **kwargs)

    def isEnabledFor(self, level: int) -> bool:
        """Check if logging is enabled for level."""
        return self._logger_factory.is_enabled_for(self.logger, level)

    def setLevel(self, level: int) -> None:
        """Set logging level."""
        self._logger_factory.set_level(self.logger, level)

    def getLevel(self) -> int:
        """Get current logging level."""
        return self._logger_factory.get_level(self.logger)


def check_optional_dependency(
    module_name: str, dependency_checker: DependencyChecker | None = None
) -> bool:
    """Check if an optional dependency is available."""
    checker = dependency_checker or DefaultDependencyChecker()
    return checker.is_available(module_name)


def get_colored_formatter(dependency_checker: DependencyChecker | None = None) -> dict[str, Any]:
    """Get colored formatter configuration with fallback."""
    formatter_factory = DefaultFormatterFactory(dependency_checker or DefaultDependencyChecker())
    return formatter_factory.create_colored_formatter()


def get_json_formatter(dependency_checker: DependencyChecker | None = None) -> dict[str, Any]:
    """Get JSON formatter configuration with fallback."""
    formatter_factory = DefaultFormatterFactory(dependency_checker or DefaultDependencyChecker())
    return formatter_factory.create_json_formatter()


def create_base_logging_config(
    config: StormLoggerConfig, configuration_builder: ConfigurationBuilder | None = None
) -> dict[str, Any]:
    """
    Create base logging configuration that works across frameworks.

    This function creates a framework-agnostic logging configuration
    that can be extended by specific framework integrations.
    """
    builder = configuration_builder or DefaultConfigurationBuilder()
    return builder.build_base_config(config)


def setup_logging_directories(
    config: StormLoggerConfig, directory_manager: DirectoryManager | None = None
) -> None:
    """Set up logging directories for Storm Logger."""
    manager = directory_manager or DefaultDirectoryManager()
    manager.create_directories(config)
