"""File system tool implementation"""

import os
import json
from typing import Dict, Any, List


class FileSystemTool:
    """File system operations tool"""
    
    def __init__(self, config: Dict[str, Any]):
        """Initialize file system tool
        
        Args:
            config: Tool configuration
        """
        self.config = config
        self.root = config.get('root', '.')
        self.description = "File system operations tool"
    
    def execute(self, operation: str, **params) -> Any:
        """Execute file system operation
        
        Args:
            operation: Operation to perform
            params: Operation parameters
            
        Returns:
            Operation result
        """
        operations = {
            'list_files': self.list_files,
            'read_file': self.read_file,
            'write_file': self.write_file,
            'create_directory': self.create_directory,
            'delete_file': self.delete_file
        }
        
        if operation in operations:
            return operations[operation](**params)
        else:
            return f"Unknown operation: {operation}"
    
    def list_files(self, directory: str = '.') -> str:
        """List files in directory
        
        Args:
            directory: Directory to list
            
        Returns:
            List of files and directories
        """
        try:
            full_path = os.path.join(self.root, directory)
            if not os.path.exists(full_path):
                return f"Directory not found: {directory}"
            
            items = os.listdir(full_path)
            result = f"Found {len(items)} items in {directory}:\n"
            for item in items:
                item_path = os.path.join(full_path, item)
                if os.path.isdir(item_path):
                    result += f"- {item}/\n"
                else:
                    result += f"- {item}\n"
            return result
        except Exception as e:
            return f"Error listing files: {str(e)}"
    
    def read_file(self, file_path: str) -> str:
        """Read file content
        
        Args:
            file_path: Path to file
            
        Returns:
            File content
        """
        try:
            full_path = os.path.join(self.root, file_path)
            if not os.path.exists(full_path):
                return f"File not found: {file_path}"
            
            with open(full_path, 'r', encoding='utf-8') as f:
                content = f.read()
            return content
        except Exception as e:
            return f"Error reading file: {str(e)}"
    
    def write_file(self, file_path: str, content: str) -> str:
        """Write content to file
        
        Args:
            file_path: Path to file
            content: Content to write
            
        Returns:
            Result message
        """
        try:
            full_path = os.path.join(self.root, file_path)
            # Create directory if it doesn't exist
            os.makedirs(os.path.dirname(full_path), exist_ok=True)
            
            with open(full_path, 'w', encoding='utf-8') as f:
                f.write(content)
            return f"File written: {file_path}"
        except Exception as e:
            return f"Error writing file: {str(e)}"
    
    def create_directory(self, directory: str) -> str:
        """Create directory
        
        Args:
            directory: Directory to create
            
        Returns:
            Result message
        """
        try:
            full_path = os.path.join(self.root, directory)
            os.makedirs(full_path, exist_ok=True)
            return f"Directory created: {directory}"
        except Exception as e:
            return f"Error creating directory: {str(e)}"
    
    def delete_file(self, file_path: str) -> str:
        """Delete file
        
        Args:
            file_path: Path to file
            
        Returns:
            Result message
        """
        try:
            full_path = os.path.join(self.root, file_path)
            if not os.path.exists(full_path):
                return f"File not found: {file_path}"
            
            os.remove(full_path)
            return f"File deleted: {file_path}"
        except Exception as e:
            return f"Error deleting file: {str(e)}"
    
    def get_schema(self) -> Dict[str, Any]:
        """Get tool schema
        
        Returns:
            JSON Schema for the tool
        """
        return {
            "name": "filesystem",
            "description": self.description,
            "parameters": {
                "type": "object",
                "properties": {
                    "operation": {
                        "type": "string",
                        "enum": ["list_files", "read_file", "write_file", "create_directory", "delete_file"],
                        "description": "File system operation to perform"
                    },
                    "directory": {
                        "type": "string",
                        "description": "Directory path for list_files or create_directory"
                    },
                    "file_path": {
                        "type": "string",
                        "description": "File path for read_file, write_file, or delete_file"
                    },
                    "content": {
                        "type": "string",
                        "description": "Content to write for write_file"
                    }
                },
                "required": ["operation"]
            }
        }
