"""
Content Generator Tool

This tool provides content generation capabilities including
book writing, article creation, and document generation.
"""

import openai
from openai import OpenAI
import time
from typing import Dict, Any, List, Optional
from tools.tool_registry import BaseTool


class ContentGeneratorTool(BaseTool):
    """Tool for generating various types of content"""
    
    def __init__(self):
        super().__init__(
            name="content_generator_tool",
            description="Generate books, articles, documents, and other written content. Supports structured writing, research-based content, and creative writing."
        )
        self.client = OpenAI()
        self.model_name = "gpt-4"
    
    def execute(self, query: str, context: Dict[str, Any]) -> Any:
        """
        Execute content generation based on query
        
        Args:
            query: User query containing content generation instructions
            context: Task analysis and other context
            
        Returns:
            Generated content result
        """
        # Determine content type based on query
        content_type = self._determine_content_type(query)
        
        if content_type == "book":
            return self._generate_book(query, context)
        elif content_type == "article":
            return self._generate_article(query, context)
        elif content_type == "document":
            return self._generate_document(query, context)
        elif content_type == "outline":
            return self._generate_outline(query, context)
        else:
            return self._generate_general_content(query, context)
    
    def _determine_content_type(self, query: str) -> str:
        """Determine the type of content to generate"""
        query_lower = query.lower()
        
        if any(word in query_lower for word in ['book', 'novel', 'manuscript', 'chapters']):
            return "book"
        elif any(word in query_lower for word in ['article', 'blog', 'post', 'essay']):
            return "article"
        elif any(word in query_lower for word in ['document', 'report', 'paper', 'manual']):
            return "document"
        elif any(word in query_lower for word in ['outline', 'structure', 'plan', 'framework']):
            return "outline"
        else:
            return "general"
    
    def _generate_book(self, query: str, context: Dict[str, Any]) -> Dict[str, Any]:
        """Generate book content"""
        try:
            # Extract book details from query
            book_details = self._extract_book_details(query)
            
            # Generate book outline first
            outline_prompt = f"""
Create a detailed outline for a book with the following specifications:
{book_details}

Provide a structured outline with:
1. Title
2. Target audience
3. Main themes
4. Chapter breakdown (at least 8-12 chapters)
5. Key points for each chapter

Format the response as a clear, hierarchical outline.
"""
            
            outline_response = self.client.chat.completions.create(
                model=self.model_name,
                messages=[
                    {"role": "system", "content": "You are a professional book writing assistant."},
                    {"role": "user", "content": outline_prompt}
                ],
                temperature=0.7
            )
            
            outline = outline_response.choices[0].message.content
            
            # Generate first chapter as sample
            first_chapter_prompt = f"""
Based on this book outline:
{outline}

Write the first chapter of the book. Make it engaging, well-structured, and approximately 2000-3000 words.
Include proper chapter formatting and maintain consistency with the outlined themes.
"""
            
            chapter_response = self.client.chat.completions.create(
                model=self.model_name,
                messages=[
                    {"role": "system", "content": "You are a professional book writer."},
                    {"role": "user", "content": first_chapter_prompt}
                ],
                temperature=0.7
            )
            
            first_chapter = chapter_response.choices[0].message.content
            
            return {
                "success": True,
                "content_type": "book",
                "book_details": book_details,
                "outline": outline,
                "first_chapter": first_chapter,
                "word_count_estimate": len(first_chapter.split()),
                "message": "Generated book outline and first chapter",
                "next_steps": [
                    "Review and refine the outline",
                    "Generate additional chapters",
                    "Develop character profiles (if fiction)",
                    "Create chapter-by-chapter writing plan"
                ]
            }
            
        except Exception as e:
            return {
                "success": False,
                "error": str(e),
                "message": f"Error generating book content: {str(e)}"
            }
    
    def _extract_book_details(self, query: str) -> str:
        """Extract book details from query"""
        # Simple extraction - in a real implementation, this would be more sophisticated
        details = []
        
        if "about" in query.lower():
            # Try to extract topic after "about"
            import re
            about_match = re.search(r'about\s+(.+?)(?:\s+(?:with|for|in)|$)', query, re.IGNORECASE)
            if about_match:
                details.append(f"Topic: {about_match.group(1)}")
        
        if "fiction" in query.lower():
            details.append("Genre: Fiction")
        elif "non-fiction" in query.lower() or "nonfiction" in query.lower():
            details.append("Genre: Non-fiction")
        
        if "beginner" in query.lower():
            details.append("Target Audience: Beginners")
        elif "advanced" in query.lower():
            details.append("Target Audience: Advanced readers")
        
        return "\n".join(details) if details else query
    
    def _generate_article(self, query: str, context: Dict[str, Any]) -> Dict[str, Any]:
        """Generate article content"""
        try:
            article_prompt = f"""
Write a comprehensive article based on this request:
{query}

Structure the article with:
1. Compelling headline
2. Introduction that hooks the reader
3. Well-organized main content with subheadings
4. Conclusion that summarizes key points
5. Aim for 1500-2500 words

Make it informative, engaging, and well-researched.
"""
            
            response = self.client.chat.completions.create(
                model=self.model_name,
                messages=[
                    {"role": "system", "content": "You are a professional content writer and journalist."},
                    {"role": "user", "content": article_prompt}
                ],
                temperature=0.7
            )
            
            article_content = response.choices[0].message.content
            word_count = len(article_content.split())
            
            return {
                "success": True,
                "content_type": "article",
                "content": article_content,
                "word_count": word_count,
                "estimated_reading_time": f"{word_count // 200} minutes",
                "message": f"Generated article with {word_count} words"
            }
            
        except Exception as e:
            return {
                "success": False,
                "error": str(e),
                "message": f"Error generating article: {str(e)}"
            }
    
    def _generate_document(self, query: str, context: Dict[str, Any]) -> Dict[str, Any]:
        """Generate document content"""
        try:
            document_prompt = f"""
Create a professional document based on this request:
{query}

Structure the document with:
1. Title page information
2. Executive summary (if applicable)
3. Table of contents outline
4. Main content sections with clear headings
5. Conclusion and recommendations
6. Professional formatting

Make it comprehensive and well-organized.
"""
            
            response = self.client.chat.completions.create(
                model=self.model_name,
                messages=[
                    {"role": "system", "content": "You are a professional technical writer and document specialist."},
                    {"role": "user", "content": document_prompt}
                ],
                temperature=0.6
            )
            
            document_content = response.choices[0].message.content
            word_count = len(document_content.split())
            
            return {
                "success": True,
                "content_type": "document",
                "content": document_content,
                "word_count": word_count,
                "message": f"Generated professional document with {word_count} words"
            }
            
        except Exception as e:
            return {
                "success": False,
                "error": str(e),
                "message": f"Error generating document: {str(e)}"
            }
    
    def _generate_outline(self, query: str, context: Dict[str, Any]) -> Dict[str, Any]:
        """Generate content outline"""
        try:
            outline_prompt = f"""
Create a detailed outline based on this request:
{query}

Provide:
1. Main topic/title
2. Target audience
3. Key objectives
4. Hierarchical structure with main sections and subsections
5. Key points for each section
6. Estimated word counts for each section

Make it comprehensive and actionable.
"""
            
            response = self.client.chat.completions.create(
                model=self.model_name,
                messages=[
                    {"role": "system", "content": "You are a professional content strategist and outline specialist."},
                    {"role": "user", "content": outline_prompt}
                ],
                temperature=0.6
            )
            
            outline_content = response.choices[0].message.content
            
            return {
                "success": True,
                "content_type": "outline",
                "outline": outline_content,
                "message": "Generated comprehensive content outline"
            }
            
        except Exception as e:
            return {
                "success": False,
                "error": str(e),
                "message": f"Error generating outline: {str(e)}"
            }
    
    def _generate_general_content(self, query: str, context: Dict[str, Any]) -> Dict[str, Any]:
        """Generate general content"""
        try:
            content_prompt = f"""
Generate high-quality content based on this request:
{query}

Make it:
1. Well-structured and organized
2. Informative and engaging
3. Appropriate length for the topic
4. Professional in tone
5. Include relevant examples where appropriate
"""
            
            response = self.client.chat.completions.create(
                model=self.model_name,
                messages=[
                    {"role": "system", "content": "You are a professional content creator."},
                    {"role": "user", "content": content_prompt}
                ],
                temperature=0.7
            )
            
            content = response.choices[0].message.content
            word_count = len(content.split())
            
            return {
                "success": True,
                "content_type": "general",
                "content": content,
                "word_count": word_count,
                "message": f"Generated content with {word_count} words"
            }
            
        except Exception as e:
            return {
                "success": False,
                "error": str(e),
                "message": f"Error generating content: {str(e)}"
            }
    
    def generate_chapter(self, book_outline: str, chapter_number: int, chapter_title: str) -> Dict[str, Any]:
        """Generate a specific chapter for a book"""
        try:
            chapter_prompt = f"""
Based on this book outline:
{book_outline}

Write Chapter {chapter_number}: {chapter_title}

Make it:
1. 2000-3000 words
2. Consistent with the overall book theme
3. Well-structured with proper flow
4. Engaging and informative
5. Include proper chapter formatting
"""
            
            response = self.client.chat.completions.create(
                model=self.model_name,
                messages=[
                    {"role": "system", "content": "You are a professional book writer."},
                    {"role": "user", "content": chapter_prompt}
                ],
                temperature=0.7
            )
            
            chapter_content = response.choices[0].message.content
            word_count = len(chapter_content.split())
            
            return {
                "success": True,
                "chapter_number": chapter_number,
                "chapter_title": chapter_title,
                "content": chapter_content,
                "word_count": word_count,
                "message": f"Generated Chapter {chapter_number} with {word_count} words"
            }
            
        except Exception as e:
            return {
                "success": False,
                "error": str(e),
                "message": f"Error generating chapter: {str(e)}"
            }
    
    def get_capabilities(self) -> List[str]:
        """Return capabilities of this tool"""
        return [
            "book_writing",
            "article_generation",
            "document_creation",
            "outline_generation",
            "creative_writing",
            "technical_writing",
            "content_planning",
            "chapter_generation"
        ]
    
    def validate_input(self, query: str, context: Dict[str, Any]) -> bool:
        """Validate input for content generation"""
        content_keywords = [
            'write', 'generate', 'create', 'book', 'article', 'document',
            'content', 'story', 'essay', 'report', 'manual', 'guide'
        ]
        
        query_lower = query.lower()
        return any(keyword in query_lower for keyword in content_keywords)
    
    def get_writing_tips(self, content_type: str) -> List[str]:
        """Get writing tips for specific content types"""
        tips = {
            "book": [
                "Start with a detailed outline",
                "Develop consistent characters and themes",
                "Write regularly, even if just 500 words per day",
                "Focus on one chapter at a time",
                "Edit and revise multiple times"
            ],
            "article": [
                "Hook readers with a compelling introduction",
                "Use subheadings to break up content",
                "Include relevant examples and data",
                "End with a strong conclusion",
                "Optimize for your target audience"
            ],
            "document": [
                "Use clear, professional language",
                "Include executive summary for longer documents",
                "Use bullet points and lists for clarity",
                "Include relevant charts and data",
                "Proofread carefully for errors"
            ]
        }
        
        return tips.get(content_type, [
            "Know your audience",
            "Plan before you write",
            "Edit ruthlessly",
            "Use active voice",
            "Keep sentences clear and concise"
        ])

