"""
Called RobustFileManagerTool that manages files and directories with advanced operations

This tool was automatically generated by ToolGeneratorTool.
Generated on: 2025-07-29T21:54:28.613577
"""

from typing import Any, Dict, List, Optional
from datetime import datetime
from ..base import BaseTool


class RobustfilemanagerTool(BaseTool):
    """
    Called RobustFileManagerTool that manages files and directories with advanced operations
    
    Purpose: manages files and directories with advanced operations
    
    This tool follows the Metis Agent tool rules:
    - Stateless architecture (no LLM dependencies)
    - Single responsibility principle
    - Standardized interface with can_handle() and execute()
    """
    
    def __init__(self):
        """Initialize the tool."""
        self.name = "robustfilemanagertool"
        self.description = "Called RobustFileManagerTool that manages files and directories with advanced operations"
    
    def can_handle(self, task: str) -> bool:
        """
        Determine if this tool can handle the given task.
        
        Args:
            task: The task description
            
        Returns:
            True if tool can handle the task, False otherwise
        """
        task_lower = task.lower()
        
        # Keywords that indicate this tool can handle the task
        keywords = ["create", "write", "operations", "read", "advanced", "directory", "file", "delete", "manages", "files", "directories", "with"]
        
        return any(keyword in task_lower for keyword in keywords)
    
    def execute(self, task: str, **kwargs) -> Dict[str, Any]:
        """
        Execute the tool's functionality.
        
        Args:
            task: The primary task description
            **kwargs: Additional parameters
            
        Returns:
            Structured dictionary with results
        """
        try:
            import os
            import shutil
            from pathlib import Path
            import json
            
            # Extract file path from task or kwargs
            file_path = kwargs.get('file_path') or kwargs.get('path')
            
            if not file_path:
                # Try to extract path from task description
                import re
                path_patterns = [r'"([^"]+)"', r"'([^']+)'", r'([A-Za-z]:[\\w\s\.\-]+)']
                for pattern in path_patterns:
                    matches = re.findall(pattern, task)
                    if matches:
                        file_path = matches[0]
                        break
            
            if not file_path:
                file_path = kwargs.get('default_path', './test_file.txt')
            
            path_obj = Path(file_path)
            operation = kwargs.get('operation', 'info')
            
            # Determine operation from task
            task_lower = task.lower()
            if 'create' in task_lower or 'make' in task_lower:
                operation = 'create'
            elif 'delete' in task_lower or 'remove' in task_lower:
                operation = 'delete'
            elif 'copy' in task_lower:
                operation = 'copy'
            elif 'move' in task_lower:
                operation = 'move'
            elif 'list' in task_lower or 'show' in task_lower:
                operation = 'list'
            elif 'read' in task_lower:
                operation = 'read'
            
            result = {}
            
            if operation == 'create':
                if path_obj.suffix:
                    # Create file
                    path_obj.parent.mkdir(parents=True, exist_ok=True)
                    content = kwargs.get('content', f'File created by {self.name} at {datetime.now()}')
                    path_obj.write_text(content)
                    result = {'action': 'file_created', 'path': str(path_obj), 'size': path_obj.stat().st_size}
                else:
                    # Create directory
                    path_obj.mkdir(parents=True, exist_ok=True)
                    result = {'action': 'directory_created', 'path': str(path_obj)}
            
            elif operation == 'delete':
                if path_obj.exists():
                    if path_obj.is_file():
                        path_obj.unlink()
                        result = {'action': 'file_deleted', 'path': str(path_obj)}
                    else:
                        shutil.rmtree(path_obj)
                        result = {'action': 'directory_deleted', 'path': str(path_obj)}
                else:
                    result = {'action': 'not_found', 'path': str(path_obj)}
            
            elif operation == 'list':
                if path_obj.is_dir():
                    items = [{'name': item.name, 'type': 'dir' if item.is_dir() else 'file', 
                             'size': item.stat().st_size if item.is_file() else None} 
                            for item in path_obj.iterdir()]
                    result = {'action': 'directory_listed', 'path': str(path_obj), 'items': items}
                else:
                    result = {'action': 'not_directory', 'path': str(path_obj)}
            
            elif operation == 'read':
                if path_obj.is_file():
                    content = path_obj.read_text()[:1000]  # Limit to first 1000 chars
                    result = {'action': 'file_read', 'path': str(path_obj), 'content': content}
                else:
                    result = {'action': 'not_file', 'path': str(path_obj)}
            
            else:
                # Default info operation
                if path_obj.exists():
                    stat = path_obj.stat()
                    result = {
                        'action': 'file_info',
                        'path': str(path_obj),
                        'exists': True,
                        'type': 'dir' if path_obj.is_dir() else 'file',
                        'size': stat.st_size if path_obj.is_file() else None,
                        'modified': stat.st_mtime
                    }
                else:
                    result = {'action': 'file_info', 'path': str(path_obj), 'exists': False}
            
            return {
                'success': True,
                'operation': operation,
                'result': result,
                'message': f"File operation '{operation}' completed successfully"
            }
            
        except PermissionError as e:
            return {
                'success': False,
                'error': f"Permission denied: {str(e)}",
                'task': task
            }
        except Exception as e:
            return {
                'success': False,
                'error': str(e),
                'task': task
            }
    
    def get_capabilities(self) -> Dict[str, Any]:
        """Return tool capability metadata."""
        return {
            "complexity_levels": ["simple", "moderate"],
            "input_types": ["text", "file_path"],
            "output_types": ["structured_data", "file_content"],
            "requires_filesystem": True,
            "requires_internet": False,
            "estimated_execution_time": "1-5s",
            "concurrent_safe": True,
            "resource_intensive": False,
            "memory_usage": "low",
            "api_dependencies": [],
            "supported_intents": [],
        }
    
    def get_examples(self) -> List[str]:
        """Get example tasks that this tool can handle."""
        return [
            "Example usage: manages files and directories with advanced operations",
        ]
