"""File storage tool for OpenAI Agent"""

from typing import Optional
from agents import function_tool
from diona.project.tools import LocalFileStorage


@function_tool
async def write_file(
    file_path: str,
    content: str,
    module_name: str = "agent"
) -> str:
    """Write content to a file in ~/.diona/user/agent directory
    
    This tool allows you to write content to a file in the ~/.diona/user/agent directory.
    You can specify subdirectories in the file_path parameter.
    
    Args:
        file_path: Relative path to the file (including subdirectories) under ~/.diona/user/agent
        content: Content to write to the file
        module_name: Module name (default: "agent")
        
    Returns:
        Success message or error message
    """
    try:
        storage = LocalFileStorage()
        success = storage.write_file(file_path, content, module_name, storage_type="user")
        if success:
            full_path = storage.get_full_path(file_path, module_name, storage_type="user")
            return f"File written successfully to: {full_path}"
        else:
            return "Failed to write file"
    except Exception as e:
        return f"Error: {str(e)}"


@function_tool
async def read_file(
    file_path: str,
    is_directory: bool = False
) -> str:
    """Read file content or list directory contents
    
    This tool allows you to:
    1. Read the content of a file
    2. List the contents of a directory
    
    Args:
        file_path: Path to the file or directory
        is_directory: Set to True to list directory contents, False to read file content
        
    Returns:
        File content, directory listing, or error message
    """
    try:
        storage = LocalFileStorage()
        if is_directory:
            # List directory contents
            result = storage.list_directory(file_path)
            if result:
                return f"Directory listing for {file_path}:\n{result}"
            else:
                return f"Failed to list directory: {file_path}"
        else:
            # Read file content
            result = storage.read_file(file_path)
            if result:
                return f"File content of {file_path}:\n{result}"
            else:
                return f"Failed to read file: {file_path}"
    except Exception as e:
        return f"Error: {str(e)}"
