from .logger import Logger
from ...common import AttributeManager

from contextvars import ContextVar, Token



class _Context:
    """
    Thread-safe and async-safe context manager for Logger instances.
    Uses ContextVar to ensure that each execution flow (thread/coroutine) has its own logger reference.
    """
    __slots__ = ('__context',)

    __instance = None


    def __new__(cls, *args, **kwargs):
        """
        Singleton pattern implementation with private slot initialization.
        """
        if cls.__instance is None:
            cls.__instance = super(_Context, cls).__new__(cls)

            AttributeManager.set_attribute(
                obj=cls.__instance,
                attr='__context',
                value=ContextVar(
                    'LogContext',
                    default=None
                )
            )
        return cls.__instance


    @property
    def logger(self) -> Logger|None:
        """
        Retrieve the logger associated with the current execution context.

        :return: Logger instance or None.
        """
        return self.__context.get()


    def set(self, logger: Logger) -> Token:
        """
        Set a new logger for the current context.

        :param logger: The logger instance to track.
        :return: A Token used to restore the previous context.
        """
        return self.__context.set(logger)


    def reset(self, token: Token):
        """
        Restore the context to its previous state using the provided token.

        :param token: The token returned by the set() method.
        """
        self.__context.reset(token)
        pass

    pass



Context = _Context()
