"""Global memory tool for OpenAI Agent"""

from diona.project.agent.globals import get_global_memory
from agents import function_tool


global_memory = get_global_memory()


@function_tool
async def global_memory_tool(action: str, key: str = None, value: str = None, page: int = 1, page_size: int = 10, return_all: bool = False) -> str:
    """Manage global memory storage for important information that should persist across conversations.
    
    This tool allows you to:
    1. Add or update global memory entries
    2. Delete global memory entries
    3. Retrieve global memory entries
    4. List all global memory entries
    
    Important usage guidelines:
    - Only store the most critical information in global memory
    - Keep stored information concise to save space
    - Use clear, descriptive keys for easy retrieval
    - Check global memory before asking the user for information that might already be stored
    
    Args:
        action: One of "add", "delete", "get", "list"
        key: The memory key (required for add, delete, get actions)
        value: The memory value (required for add action)
        page: Page number for listing (default: 1)
        page_size: Number of items per page (default: 10)
        return_all: Whether to return all memories at once (default: False)
    
    Returns:
        Result message
    """
    if action == "add":
        if not key or not value:
            return "Error: Key and value are required for add action"
        success = global_memory.add_memory(key, value)
        if success:
            return f"Successfully added memory: {key} = {value}"
        else:
            return "Error: Failed to add memory"
    
    elif action == "delete":
        if not key:
            return "Error: Key is required for delete action"
        success = global_memory.delete_memory(key)
        if success:
            return f"Successfully deleted memory: {key}"
        else:
            return "Error: Failed to delete memory"
    
    elif action == "get":
        if not key:
            return "Error: Key is required for get action"
        value = global_memory.get_memory(key)
        if value is not None:
            return f"Memory: {key} = {value}"
        else:
            return f"Memory not found: {key}"
    
    elif action == "list":
        if return_all:
            # Return all memories at once
            memories = global_memory.list_memories(1, 1000)  # Use a large page size
            if not memories:
                return "No global memories found"
            
            result = "All global memories:\n"
            for key, val in memories:
                result += f"- {key}: {val}\n"
            
            total_count = global_memory.get_memory_count()
            total_chars = global_memory.get_memory_char_count()
            result += f"\nTotal entries: {total_count}"
            result += f"\nTotal characters: {total_chars}"
            
            return result
        else:
            # Return paginated memories
            memories = global_memory.list_memories(page, page_size)
            if not memories:
                return "No global memories found"
            
            result = f"Global memories (page {page}):\n"
            for key, val in memories:
                result += f"- {key}: {val}\n"
            
            total_count = global_memory.get_memory_count()
            total_chars = global_memory.get_memory_char_count()
            result += f"\nTotal entries: {total_count}"
            result += f"\nTotal characters: {total_chars}"
            
            return result
    
    else:
        return f"Error: Invalid action: {action}"
