# /mnt/e/genesis-system/core/rwl/guard/integration.py

from functools import wraps
from typing import Callable, Any
from genesis_system.core.rwl.guard.guard import RWLGuard  # Assuming guard logic is in guard.py
import logging

logger = logging.getLogger(__name__)

def enforce_rwl(guard: RWLGuard) -> Callable[[Callable[..., Any]], Callable[..., Any]]:
    """
    A decorator that enforces RWL guard checks on a function.

    Args:
        guard: An RWLGuard instance to use for enforcement.

    Returns:
        A decorated function that performs RWL checks before execution.
    """
    def decorator(func: Callable[..., Any]) -> Callable[..., Any]:
        @wraps(func)
        def wrapper(*args: Any, **kwargs: Any) -> Any:
            try:
                if not guard.is_allowed():
                    logger.warning(f"RWLGuard blocked access to {func.__name__}")
                    return guard.handle_denial()  # Or raise an exception, depending on requirement.

                logger.debug(f"RWLGuard allowed access to {func.__name__}")
                return func(*args, **kwargs)
            except Exception as e:
                logger.exception(f"An error occurred during RWL enforcement for {func.__name__}: {e}")
                raise  # Re-raise the exception to avoid masking errors

        return wrapper

    return decorator

def integrate_all_entrypoints(guard: RWLGuard, entrypoints: list[Callable[..., Any]]) -> None:
    """
    Integrates the RWL guard into multiple entry points using the enforce_rwl decorator.

    Args:
        guard: The RWLGuard instance to use for enforcement.
        entrypoints: A list of callable entry points to protect.
    """
    for entrypoint in entrypoints:
        # Ideally, you'd modify the entrypoints in-place if possible.
        # However, depending on the system structure, you might need to
        # create new decorated versions of the functions.

        # This approach assumes you can reassign the original names:
        globals()[entrypoint.__name__] = enforce_rwl(guard)(entrypoint) # careful with globals, could be problematic

        # Alternatives:
        # 1. Return a list of decorated functions if direct reassignment isn't feasible.
        # 2. Modify a configuration file or mapping to point to the decorated functions.
        logger.info(f"Successfully integrated RWL guard into entrypoint: {entrypoint.__name__}")


if __name__ == '__main__':
    # Example usage (for demonstration purposes only - do not use in production directly)
    from genesis_system.core.rwl.guard.guard import MockRWLGuard  # Assuming guard.py contains MockRWLGuard for testing

    # Define a mock entrypoint function
    def my_entrypoint(arg1: str, arg2: int) -> str:
        """My dummy entrypoint."""
        return f"Entrypoint called with {arg1} and {arg2}"

    # Create a mock guard instance that always denies access
    mock_guard = MockRWLGuard(allow=False)

    # Decorate the entrypoint with the RWL guard
    decorated_entrypoint = enforce_rwl(mock_guard)(my_entrypoint)

    # Call the decorated entrypoint
    result = decorated_entrypoint("test", 123)
    print(f"Result from decorated entrypoint: {result}")

    # Example with integration function
    def entrypoint1(): return "Entrypoint 1"
    def entrypoint2(): return "Entrypoint 2"
    mock_guard2 = MockRWLGuard(allow=True)
    integrate_all_entrypoints(mock_guard2, [entrypoint1, entrypoint2])
    print(f"entrypoint1(): {entrypoint1()}") # should print decorated result after integrate
    print(f"entrypoint2(): {entrypoint2()}")