"""Local file storage tool implementation"""

import os
from typing import Optional, Tuple
from diona.project.storage.storage import get_storage_instance
from diona.project.shell.shell import DefaultShellCommander


class LocalFileStorage:
    """Local file storage tool class"""
    
    def __init__(self):
        """Initialize LocalFileStorage"""
        self.storage = get_storage_instance()
        # Create shell commander with appropriate encoding for Windows
        from diona.project.shell.shell import ShellCommander
        from diona.project.shell.config import ShellConfig
        
        config = ShellConfig()
        if os.name == 'nt':
            # Use GBK encoding for Windows cmd
            config.encoding = 'gbk'
        
        # Set command whitelist and blacklist
        config.command_whitelist = [
            "echo", "dir", "ls", "type", "more", "find", "findstr",
            "grep", "sort", "date", "time", "cls", "clear",
            "ipconfig", "ping", "netstat", "tasklist", "systeminfo",
            "ver", "whoami", "set", "path"
        ]
        config.command_blacklist = [
            "rm", "del", "erase", "rd", "rmdir", "move", "ren",
            "rename", "copy", "xcopy", "robocopy", "mkdir", "md"
        ]
        
        self.shell = ShellCommander(config)
    
    def write_file(self, relative_path: str, content: str, module_name: str = "agent", storage_type: str = "project") -> bool:
        """Write file to specified storage type directory
        
        Args:
            relative_path: Relative path under the specified storage type directory
            content: Content to write to file
            module_name: Module name (default: "agent")
            storage_type: Storage type (default: "project")
            
        Returns:
            bool: True if write successful, False otherwise
        """
        # Ensure we're only writing to ~/.diona directory
        # The storage module already enforces this
        return self.storage.write(module_name, relative_path, content, storage_type=storage_type)
    
    def read_file(self, path: str) -> Optional[str]:
        """Read file content using shell commands
        
        Args:
            path: Path to read
            
        Returns:
            Optional[str]: File content if successful, None otherwise
        """
        # Use shell commands to read file content
        # For Windows, use type command
        # For Linux/Mac, use cat command
        if os.name == 'nt':
            # Convert forward slashes to backslashes for Windows
            windows_path = path.replace('/', '\\')
            # Escape backslashes for Windows command
            escaped_path = windows_path.replace('\\', '\\\\')
            command = f"type {escaped_path}"
        else:
            command = f"cat {path}"
        
        try:
            returncode, stdout, stderr = self.shell.execute(command)
            if returncode == 0:
                return stdout
            return None
        except Exception:
            return None
    
    def list_directory(self, path: str) -> Optional[str]:
        """List directory contents using shell commands
        
        Args:
            path: Directory path to list
            
        Returns:
            Optional[str]: Directory listing if successful, None otherwise
        """
        # Use shell commands to list directory
        # For Windows, use dir command
        # For Linux/Mac, use ls command
        if os.name == 'nt':
            command = f"dir {path}"
        else:
            command = f"ls -la {path}"
        
        try:
            returncode, stdout, stderr = self.shell.execute(command)
            if returncode == 0:
                return stdout
            return None
        except Exception:
            return None
    
    def get_full_path(self, relative_path: str, module_name: str = "agent", storage_type: str = "project") -> str:
        """Get full path for a given relative path
        
        Args:
            relative_path: Relative path under the specified storage type directory
            module_name: Module name (default: "agent")
            storage_type: Storage type (default: "project")
            
        Returns:
            str: Full path
        """
        return self.storage.get_path(module_name, relative_path, storage_type=storage_type)
    
    def file_exists(self, relative_path: str, module_name: str = "agent", storage_type: str = "project") -> bool:
        """Check if file exists
        
        Args:
            relative_path: Relative path under the specified storage type directory
            module_name: Module name (default: "agent")
            storage_type: Storage type (default: "project")
            
        Returns:
            bool: True if file exists, False otherwise
        """
        return self.storage.exists(module_name, relative_path, storage_type=storage_type)
