"""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 edit_file(
    file_path: str,
    start_line: int,
    end_line: int,
    original_content: str,
    new_content: str
) -> str:
    """Edit file by line range with original content verification
    
    This tool edits a file by replacing a specific line range.
    IMPORTANT: You must provide the EXACT original content that matches the lines
    in the file. The tool will verify the content before making any changes.
    
    Args:
        file_path: FULL ABSOLUTE path to the file
        start_line: Start line number (1-based)
        end_line: End line number (1-based)
        original_content: Exact original content of the lines to replace
        new_content: New content to replace with
        
    Returns:
        Success message or error message
    """
    try:
        storage = LocalFileStorage()
        success, message = storage.edit_file(file_path, start_line, end_line, original_content, new_content)
        return message
    except Exception as e:
        return f"Error: {str(e)}"


@function_tool
async def write_diona_file(
    file_path: str,
    content: str,
    module_name: str = "agent"
) -> str:
    """Write content to a file in ~/.diona/user/ directory
    
    Root directory is ~/.diona/user/. The module_name defaults to "agent", 
    so files are written to ~/.diona/user/agent/ by default.
    You can specify subdirectories in the file_path parameter.
    
    Examples:
    - file_path="test.txt" -> ~/.diona/user/agent/test.txt
    - module_name="cli", file_path="config.json" -> ~/.diona/user/cli/config.json
    
    Args:
        file_path: Relative path to the file (including subdirectories) under ~/.diona/user/<module_name>/
        content: Content to write to the file
        module_name: Module name (default: "agent"), subdirectory under ~/.diona/user/
        
    Returns:
        Success message or error message
    """
    try:
        storage = LocalFileStorage()
        success = storage.write_diona_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 write_file(
    file_path: str,
    content: str
) -> str:
    """Write content to a file in any directory 
    
    This tool allows you to write content to any file on the system.
    Use with caution - this can overwrite existing files.
    
    IMPORTANT: You MUST use a FULL ABSOLUTE path (e.g., "C:\\Users\\name\\file.txt" or "/home/user/file.txt").
    DO NOT use relative paths.
    
    Args:
        file_path: FULL ABSOLUTE path to the file (e.g., "C:\\Users\\name\\file.txt")
        content: Content to write to the file
        
    Returns:
        Success message or error message
    """
    try:
        storage = LocalFileStorage()
        success = storage.write_file(file_path, content)
        if success:
            return f"File written successfully to: {file_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
    
    IMPORTANT: You MUST use a FULL ABSOLUTE path (e.g., "C:\\Users\\name\\file.txt" or "/home/user/file.txt").
    
    Args:
        file_path: FULL ABSOLUTE 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:
            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:
            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)}"


@function_tool
async def read_file_head(
    file_path: str,
    n: int = 10
) -> str:
    """Read the first N lines of a file
    
    This tool reads the first N lines of a file, useful for previewing large files
    without loading the entire content into memory.
    
    IMPORTANT: You MUST use a FULL ABSOLUTE path (e.g., "C:\\Users\\name\\file.txt" or "/home/user/file.txt").
    
    Args:
        file_path: FULL ABSOLUTE path to the file
        n: Number of lines to read (default: 10)
        
    Returns:
        First N lines of the file or error message
    """
    try:
        storage = LocalFileStorage()
        result = storage.read_lines(file_path, n)
        if result:
            return f"First {n} lines of {file_path}:\n{result}"
        else:
            return f"Failed to read file: {file_path}"
    except Exception as e:
        return f"Error: {str(e)}"
