"""
Build a RobustTextAnalyzerTool that analyzes text sentiment and extracts insights

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

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


class RobusttextanalyzerTool(BaseTool):
    """
    Build a RobustTextAnalyzerTool that analyzes text sentiment and extracts insights
    
    Purpose: analyzes text sentiment and extracts insights
    
    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 = "robusttextanalyzertool"
        self.description = "Build a RobustTextAnalyzerTool that analyzes text sentiment and extracts insights"
    
    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 = ["extracts", "evaluate", "analyzes", "inspect", "insights", "assess", "text", "examine", "analyze", "sentiment"]
        
        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 re
            from collections import Counter
            
            # Get text to analyze
            text = kwargs.get('text') or kwargs.get('content')
            
            if not text:
                # Try to extract text from task
                text_patterns = [r'"([^"]+)"', r"'([^']+)'"]
                for pattern in text_patterns:
                    matches = re.findall(pattern, task)
                    if matches:
                        text = ' '.join(matches)
                        break
            
            if not text:
                text = task  # Use the task itself as text to analyze
            
            # Basic text analysis
            words = re.findall(r'\w+', text.lower())
            sentences = re.split(r'[.!?]+', text)
            
            # Word frequency analysis
            word_freq = Counter(words)
            common_words = word_freq.most_common(10)
            
            # Basic sentiment analysis (simple keyword-based)
            positive_words = ['good', 'great', 'excellent', 'amazing', 'wonderful', 'fantastic', 
                            'love', 'like', 'happy', 'pleased', 'satisfied', 'perfect']
            negative_words = ['bad', 'terrible', 'awful', 'horrible', 'hate', 'dislike', 
                            'angry', 'frustrated', 'disappointed', 'poor', 'worst']
            
            positive_count = sum(1 for word in words if word in positive_words)
            negative_count = sum(1 for word in words if word in negative_words)
            
            if positive_count > negative_count:
                sentiment = 'positive'
                confidence = min(0.9, (positive_count - negative_count) / len(words) * 10)
            elif negative_count > positive_count:
                sentiment = 'negative'
                confidence = min(0.9, (negative_count - positive_count) / len(words) * 10)
            else:
                sentiment = 'neutral'
                confidence = 0.5
            
            # Extract key phrases (simple n-gram approach)
            bigrams = [f"{words[i]} {words[i+1]}" for i in range(len(words)-1)]
            key_phrases = [phrase for phrase, count in Counter(bigrams).most_common(5) if count > 1]
            
            analysis_result = {
                'text_stats': {
                    'character_count': len(text),
                    'word_count': len(words),
                    'sentence_count': len([s for s in sentences if s.strip()]),
                    'avg_word_length': sum(len(word) for word in words) / len(words) if words else 0
                },
                'sentiment': {
                    'label': sentiment,
                    'confidence': round(confidence, 2),
                    'positive_indicators': positive_count,
                    'negative_indicators': negative_count
                },
                'keywords': {
                    'most_common_words': common_words[:5],
                    'key_phrases': key_phrases,
                    'unique_words': len(set(words))
                },
                'text_preview': text[:200] + '...' if len(text) > 200 else text
            }
            
            return {
                'success': True,
                'analysis': analysis_result,
                'message': f"Text analysis completed. Analyzed {len(words)} words with {sentiment} sentiment."
            }
            
        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": ["moderate", "complex"],
            "input_types": ["text", "structured_data"],
            "output_types": ["analysis_results", "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: analyzes text sentiment and extracts insights",
        ]
