"""
Content Generation Tool for Metis Agent.

This tool specializes in creating written content such as articles, blog posts,
reports, outlines, plans, and research papers.
"""
from typing import Any, Dict, List, Optional
import re
from ..core.llm_interface import get_llm
from ..auth.api_key_manager import APIKeyManager
from .base import BaseTool


class ContentGenerationTool(BaseTool):
    """
    Specializes in creating written content such as articles, blog posts, reports,
    outlines, plans, and research papers. Do NOT use for code generation tasks.
    """
    
    def __init__(self, api_key: Optional[str] = None):
        """
        Initialize the content generation tool.
        
        Args:
            api_key: API key for the LLM (optional)
        """
        # Initialize LLM (uses configured provider - no need for API key here)
        # The LLM is already configured via configure_llm() in the main application
        self.llm = get_llm()
        
        # Define content type prompts
        self.content_prompts = {
            "article": "Write a well-structured article with clear sections, engaging introduction, and strong conclusion.",
            "blog_post": "Write an engaging blog post with a conversational tone, personal insights, and practical takeaways.",
            "report": "Write a formal report with executive summary, methodology, findings, and recommendations.",
            "outline": "Create a detailed outline with main sections, subsections, and key points to cover.",
            "plan": "Develop a comprehensive plan with objectives, strategies, timeline, and success metrics.",
            "research_paper": "Write a scholarly research paper with abstract, literature review, methodology, results, discussion, and conclusion.",
            "email": "Compose a professional email with clear subject, greeting, body, and closing.",
            "social_media": "Create engaging social media content optimized for the target platform.",
            "presentation": "Develop presentation content with clear slides, talking points, and visual elements.",
            "summary": "Write a concise summary capturing the key points and main ideas.",
            "analysis": "Provide an in-depth analysis with critical evaluation and insights.",
            "review": "Write a balanced review highlighting strengths, weaknesses, and overall assessment.",
            "guide": "Create a step-by-step guide with clear instructions and helpful tips.",
            "script": "Write a conversational script with natural dialogue and clear direction."
        }
        
    def can_handle(self, task: str) -> bool:
        """
        Determine if this tool can handle the given task.
        
        Args:
            task: The task to check
            
        Returns:
            True if the tool can handle the task, False otherwise
        """
        task_lower = task.lower()
        words = set(re.findall(r'\b\w+\b', task_lower))
        
        # Check for content creation keywords
        content_keywords = {
            'write', 'create', 'draft', 'compose', 'generate', 'develop',
            'article', 'blog', 'post', 'report', 'outline', 'plan',
            'research', 'paper', 'essay', 'content', 'text', 'document',
            'summary', 'analysis', 'review', 'guide', 'script', 'email',
            'social media', 'presentation', 'speech', 'letter', 'proposal'
        }
        
        # Check for negative indicators (coding tasks)
        coding_keywords = {
            'code', 'program', 'script', 'function', 'class', 'algorithm',
            'implement', 'compile', 'debug', 'refactor', 'python', 'javascript',
            'java', 'c++', 'html', 'css', 'typescript', 'ruby', 'golang', 'rust'
        }
        
        # If task contains coding keywords, don't handle it
        if any(keyword in words for keyword in coding_keywords):
            return False
            
        # Check for content creation keywords
        if any(keyword in words for keyword in content_keywords):
            return True
            
        # Check for content creation phrases
        content_phrases = [
            'write a blog', 'create an article', 'write a report',
            'draft a document', 'create content', 'write a summary',
            'develop a plan', 'create an outline', 'write a research paper',
            'compose an email', 'write a social media post', 'create a presentation'
        ]
        
        if any(phrase in task_lower for phrase in content_phrases):
            return True
            
        return False
        
    def execute(self, task: str) -> str:
        """
        Generate content based on the task description.
        
        Args:
            task: The content generation task
            
        Returns:
            Generated content
        """
        # Detect content type
        content_type = self._detect_content_type(task)
        
        # Get content type prompt
        content_prompt = self.content_prompts.get(content_type, "Write high-quality content that is clear, engaging, and well-structured.")
        
        # Create prompt for content generation
        prompt = [
            {"role": "system", "content": f"""You are an expert content creator specializing in {content_type} writing.
Your task is to generate high-quality, engaging content based on the user's requirements.

{content_prompt}

Guidelines:
1. Write clear, concise, and engaging content
2. Use appropriate structure and formatting for the content type
3. Include relevant examples and evidence where appropriate
4. Maintain a consistent tone and style
5. Ensure factual accuracy and logical flow
6. Optimize for readability and audience engagement
7. Use proper grammar, spelling, and punctuation

Format your response with appropriate headings, paragraphs, and formatting."""},
            {"role": "user", "content": task}
        ]
        
        # Generate content
        response = self.llm.chat(prompt)
        
        return response
        
    def _detect_content_type(self, task: str) -> str:
        """
        Detect the content type from the task description.
        
        Args:
            task: The task description
            
        Returns:
            Detected content type
        """
        task_lower = task.lower()
        
        # Check for explicit content type mentions
        content_types = {
            'article': 'article',
            'blog': 'blog_post',
            'post': 'blog_post',
            'report': 'report',
            'outline': 'outline',
            'plan': 'plan',
            'research paper': 'research_paper',
            'paper': 'research_paper',
            'essay': 'research_paper',
            'email': 'email',
            'social media': 'social_media',
            'presentation': 'presentation',
            'summary': 'summary',
            'analysis': 'analysis',
            'review': 'review',
            'guide': 'guide',
            'script': 'script'
        }
        
        for keyword, content_type in content_types.items():
            if keyword in task_lower:
                return content_type
                
        # Default to article if no content type is detected
        return 'article'
        
    def get_examples(self) -> List[str]:
        """
        Get example tasks that this tool can handle.
        
        Returns:
            List of example tasks
        """
        return [
            "Write a blog post about AI ethics",
            "Create a research paper outline",
            "Generate a marketing plan",
            "Design a cognitive architecture for AI",
            "Develop a knowledge representation model",
            "Define the problem that requires AI agents to think",
            "Outline a strategy for implementing AI systems",
            "Create a framework for natural language processing",
            "Plan the development process for an AI agent",
            "Write documentation for an AI system"
        ]