"""
Utility module for managing thread-local logging scope and categories.

This module provides functions for working with scope stacks and categories
to organize logging context across multiple threads.

Functions:
    _get_scope_stack() -> list: Get the current thread's scope stack.
    _push_scope(scope: str) -> None: Push a new scope onto the scope stack.
    _pop_scope() -> dict: Pop the most recent scope from the stack.
    _clear_scope() -> None: Clear the current thread's scope stack.
    _set_category(category: str) -> None: Set the category for the current thread.
    _get_category() -> str: Get the current thread's category.
"""


import threading


_thread_locals = threading.local()


def _get_scope_stack():
    """
    Retrieve the current thread's scope stack.

    Returns:
        list: List of dictionaries representing the scopes in the stack.
    """

    return getattr(_thread_locals, 'scope_stack', [])


def _push_scope(scope):
    """
    Push a new scope onto the current thread's scope stack.

    Args:
        scope (str): Scope string containing key-value pairs separated by commas.
    """

    if not hasattr(_thread_locals, 'scope_stack'):
        _thread_locals.scope_stack = []
    kv_pairs = {pair.split(":")[0]: ":".join(pair.split(":")[1:]) for pair in scope.split(", ")}
    formatted_scope = {'Message': scope, **kv_pairs}
    _thread_locals.scope_stack.append(formatted_scope)


def _pop_scope():
    """
    Pop the most recent scope from the current thread's scope stack.

    Returns:
        dict: The popped scope dictionary, or None if the stack is empty.
    """

    if hasattr(_thread_locals, 'scope_stack') and _thread_locals.scope_stack:
        return _thread_locals.scope_stack.pop()


def _clear_scope():
    """
    Clear the current thread's scope stack.
    """

    _thread_locals.scope_stack = []


def _set_category(category):
    """
    Set the category for the current thread.

    Args:
        category (str): Category name to set for logging.
    """

    _thread_locals.category = category


def _get_category():
    """
    Get the current thread's category.

    Returns:
        str: The category name, defaulting to 'Program' if not set.
    """

    return getattr(_thread_locals, 'category', 'Program')


# That's all folks...
