"""
Generate a RobustDataProcessorTool that validates and transforms data formats

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

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


class RobustdataprocessorTool(BaseTool):
    """
    Generate a RobustDataProcessorTool that validates and transforms data formats
    
    Purpose: validates and transforms data formats
    
    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 = "robustdataprocessortool"
        self.description = "Generate a RobustDataProcessorTool that validates and transforms data formats"
    
    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 = ["process", "formats", "transform", "parse", "format", "data", "transforms", "convert", "validates"]
        
        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 json
            import csv
            import re
            from io import StringIO
            
            # Get data from kwargs or try to parse from task
            data = kwargs.get('data')
            data_format = kwargs.get('format', 'auto')
            
            if not data:
                # Try to extract data from task description
                if '{' in task and '}' in task:
                    # Looks like JSON
                    json_match = re.search(r'\{.*\}', task, re.DOTALL)
                    if json_match:
                        try:
                            data = json.loads(json_match.group())
                            data_format = 'json'
                        except json.JSONDecodeError:
                            pass
                
                if not data:
                    # Create sample data for demonstration
                    data = {
                        'sample_field': 'sample_value',
                        'numbers': [1, 2, 3, 4, 5],
                        'timestamp': str(datetime.now())
                    }
                    data_format = 'json'
            
            result = {}
            
            # Determine operation
            task_lower = task.lower()
            if 'validate' in task_lower:
                # Data validation
                if isinstance(data, dict):
                    validation_result = {
                        'valid': True,
                        'type': 'object',
                        'fields': len(data),
                        'field_types': {k: type(v).__name__ for k, v in data.items()}
                    }
                elif isinstance(data, list):
                    validation_result = {
                        'valid': True,
                        'type': 'array',
                        'length': len(data),
                        'item_types': list(set(type(item).__name__ for item in data))
                    }
                else:
                    validation_result = {
                        'valid': True,
                        'type': type(data).__name__,
                        'value': str(data)[:100]
                    }
                result['validation'] = validation_result
            
            elif 'convert' in task_lower or 'transform' in task_lower:
                # Data conversion
                target_format = kwargs.get('target_format', 'json')
                
                if target_format == 'json':
                    result['converted_data'] = json.dumps(data, indent=2)
                elif target_format == 'csv':
                    if isinstance(data, list) and data and isinstance(data[0], dict):
                        output = StringIO()
                        writer = csv.DictWriter(output, fieldnames=data[0].keys())
                        writer.writeheader()
                        writer.writerows(data)
                        result['converted_data'] = output.getvalue()
                    else:
                        result['converted_data'] = str(data)
                else:
                    result['converted_data'] = str(data)
                
                result['target_format'] = target_format
            
            elif 'clean' in task_lower or 'sanitize' in task_lower:
                # Data cleaning
                if isinstance(data, dict):
                    cleaned_data = {k: v for k, v in data.items() if v is not None and v != ''}
                elif isinstance(data, list):
                    cleaned_data = [item for item in data if item is not None and item != '']
                elif isinstance(data, str):
                    cleaned_data = re.sub(r'\s+', ' ', data.strip())
                else:
                    cleaned_data = data
                
                result['cleaned_data'] = cleaned_data
                result['original_size'] = len(str(data))
                result['cleaned_size'] = len(str(cleaned_data))
            
            else:
                # Default processing - analyze data
                if isinstance(data, dict):
                    analysis = {
                        'type': 'object',
                        'field_count': len(data),
                        'fields': list(data.keys()),
                        'sample_values': {k: str(v)[:50] for k, v in list(data.items())[:3]}
                    }
                elif isinstance(data, list):
                    analysis = {
                        'type': 'array',
                        'length': len(data),
                        'sample_items': data[:3],
                        'item_types': list(set(type(item).__name__ for item in data))
                    }
                else:
                    analysis = {
                        'type': type(data).__name__,
                        'length': len(str(data)),
                        'preview': str(data)[:100]
                    }
                
                result['analysis'] = analysis
            
            return {
                'success': True,
                'input_format': data_format,
                'processed_data': result,
                'message': f"Data processing completed successfully"
            }
            
        except json.JSONDecodeError as e:
            return {
                'success': False,
                'error': f"JSON parsing error: {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", "structured_data"],
            "output_types": ["structured_data"],
            "requires_filesystem": False,
            "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: validates and transforms data formats",
        ]
