"""
ContextRetentionPolicy
Generated by Eden via recursive self-improvement
2025-10-27 22:54:33.905545
"""

class ContextRetentionPolicy:
    """A class to manage context retention across conversation turns.
    
    Attributes:
        storage (dict): Dictionary to store contextual data.
        max_size (int): Maximum number of contexts to retain. If exceeded, older entries are removed.
        ttl (int): Default time-to-live in seconds for each context entry (default 3600).
    """
    
    def __init__(self, max_size=1000, ttl=3600):
        """Initialize the ContextRetentionPolicy with specified maximum size and TTL."""
        self.storage = {}
        self.max_size = max_size
        self.ttl = ttl
        
    def add_context(self, key, value, user_id=None, ttl=None):
        """Add contextual information to storage.
        
        Args:
            key (str): The context key to store under.
            value (dict): The contextual data to store.
            user_id (str, optional): Identifier for the user or conversation. Defaults to None.
            ttl (int, optional): Time-to-live in seconds for this entry. Defaults to self.ttl.
        """
        if ttl is None:
            ttl = self.ttl
            
        context_entry = {
            "value": value,
            "timestamp": time.time(),
            "ttl": ttl
        }
        
        if user_id:
            key += f"_{user_id}"
            
        # Add or update the entry
        if key in self.storage:
            self.storage[key]["value"] = context_entry["value"]
            self.storage[key]["timestamp"] = context_entry["timestamp"]
            self.storage[key]["ttl"] = ttl
        else:
            self.storage[key] = context_entry
            
        # Enforce max size by removing old entries
        self._cleanup_expired()
        
    def get_context(self, key, user_id=None):
        """Retrieve contextual information from storage.
        
        Args:
            key (str): The context key to retrieve.
            user_id (str, optional): Identifier for the user or conversation. Defaults to None.
            
        Returns:
            dict: The stored contextual data if found, otherwise empty dict.
        """
        if user_id:
            key += f"_{user_id}"
            
        current_time = time.time()
        # Return a copy of the value to prevent external modification
        matching_keys = [k for k in self.storage.keys() if k.endswith(f"_{key}") or k == key]
        
        latest_entry = None
        for candidate_key in matching_keys:
            entry = self.storage[candidate_key]
            if (entry["ttl"] > current_time - entry["timestamp"]):
                if latest_entry is None or entry["timestamp"] > latest_entry["timestamp"]:
                    latest_entry = entry
        
        return latest_entry.copy() if latest_entry else {}
    
    def clear_context(self, key=None, user_id=None):
        """Clear contextual information from storage.
        
        Args:
            key (str, optional): Specific context key to clear. Defaults to None (clear all).
            user_id (str, optional): User identifier to scope the clearance. Defaults to None.
        """
        keys_to_clear = []
        if key:
            keys_to_clear.append(f"{key}_{user_id}" if user_id else key)
        else:
            for k in self.storage.keys():
                if user_id and f"_{user_id}" in k:
                    keys_to_clear.append(k)
        
        for key_to_remove in keys_to_clear:
            if key_to_remove in self.storage:
                del self.storage[key_to_remove]
                
    def _cleanup_expired(self):
        """Internal method to clean up expired context entries."""
        current_time = time.time()
        keys_to_remove = [k for k, v in self.storage.items() 
                         if (v["ttl"] <= current_time - v["timestamp"])]
        
        for key in keys_to_remove:
            del self.storage[key]
            
        # Enforce max size by removing oldest entries if needed
        while len(self.storage) > self.max_size:
            oldest_key = min(self.storage.keys(), key=lambda k: self.storage[k]["timestamp"])
            del self.storage[oldest_key]
# Initialize the context manager with default settings
context_manager = ContextRetentionPolicy(max_size=1000, ttl=3600)

# Store contextual information during a conversation turn
context_manager.add_context("user_info", {"name": "Alice", "age": 30}, user_id="1234")

# Retrieve the stored context later in the conversation
retrieved_context = context_manager.get_context("user_info", user_id="1234")
print(retrieved_context)  # Output: {"name": "Alice", "age": 30}

# Clear all contexts for a specific user
context_manager.clear_context(user_id="1234")

# Clear all contexts
context_manager.clear_context()