"""
Educational Tutor Bot AI Helper Functions
Author: RSK World (https://rskworld.in)
Founded by: Molla Samser
Designer & Tester: Rima Khatun
Contact: info@rskworld.com, +91 93305 39277
Year: 2026
"""

import re
import time
import json
from typing import List, Dict, Optional, Tuple
from openai import OpenAI

class AIHelper:
    """Helper class for AI-related operations"""
    
    def __init__(self, api_key: str):
        self.client = OpenAI(api_key=api_key)
        self.model = "gpt-3.5-turbo"
        self.max_tokens = 500
        self.temperature = 0.7
    
    def get_tutoring_response(self, message: str, subject: str = None, 
                            difficulty: str = 'Intermediate', 
                            context: List[Dict] = None) -> str:
        """Get AI tutoring response"""
        
        system_prompt = self._build_system_prompt(subject, difficulty)
        
        try:
            messages = [
                {"role": "system", "content": system_prompt}
            ]
            
            # Add conversation context if provided
            if context:
                messages.extend(context[-5:])  # Last 5 messages for context
            
            messages.append({"role": "user", "content": message})
            
            start_time = time.time()
            
            response = self.client.chat.completions.create(
                model=self.model,
                messages=messages,
                max_tokens=self.max_tokens,
                temperature=self.temperature
            )
            
            response_time = int((time.time() - start_time) * 1000)
            
            return {
                'response': response.choices[0].message.content,
                'tokens_used': response.usage.total_tokens if response.usage else 0,
                'response_time': response_time
            }
            
        except Exception as e:
            return {
                'response': f"I apologize, but I'm having trouble connecting right now. Please try again later. Error: {str(e)}",
                'tokens_used': 0,
                'response_time': 0
            }
    
    def _build_system_prompt(self, subject: str, difficulty: str) -> str:
        """Build system prompt based on subject and difficulty"""
        
        base_prompt = """
        You are an expert educational tutor for RSK World's Educational Tutor Bot.
        Your role is to provide clear, educational, and engaging tutoring sessions.
        
        Guidelines:
        - Provide step-by-step explanations
        - Use examples and analogies
        - Ask follow-up questions to ensure understanding
        - Be encouraging and supportive
        - Adapt to the student's level
        - Provide additional learning resources when helpful
        
        """
        
        subject_prompts = {
            'Mathematics': """
            You are an expert Mathematics tutor. Show your work step-by-step.
            Use visual descriptions when explaining concepts. Include practice problems.
            """,
            'Science': """
            You are an expert Science tutor (Physics, Chemistry, Biology).
            Explain scientific concepts with real-world examples. Encourage scientific thinking.
            """,
            'History': """
            You are an expert History tutor. Provide historical context and timelines.
            Connect past events to present-day relevance. Make history engaging.
            """,
            'English': """
            You are an expert English tutor. Help with grammar, vocabulary, and literature.
            Provide constructive feedback on writing. Explain literary devices clearly.
            """,
            'Computer Science': """
            You are an expert Computer Science tutor. Explain programming concepts clearly.
            Use code examples when helpful. Cover algorithms, data structures, and best practices.
            """
        }
        
        difficulty_modifiers = {
            'Beginner': "Use simple language. Break down complex topics into small, manageable steps. Avoid jargon.",
            'Intermediate': "Use appropriate technical terms but explain them. Provide balanced depth and breadth.",
            'Advanced': "Use technical language appropriately. Cover advanced concepts and nuances. Challenge the student."
        }
        
        prompt = base_prompt
        prompt += subject_prompts.get(subject, "")
        prompt += f"\n\nDifficulty Level: {difficulty}\n"
        prompt += difficulty_modifiers.get(difficulty, "")
        prompt += "\n\nRemember: You are representing RSK World (https://rskworld.in), founded by Molla Samser."
        
        return prompt
    
    def generate_practice_questions(self, subject: str, topic: str, 
                                  difficulty: str = 'Intermediate',
                                  count: int = 5) -> List[Dict]:
        """Generate practice questions for a subject and topic"""
        
        prompt = f"""
        Generate {count} practice questions for {subject} - {topic} at {difficulty} level.
        Each question should include:
        1. The question text
        2. Multiple choice options (if applicable)
        3. The correct answer
        4. A brief explanation
        
        Format as JSON array with objects containing: question, options, answer, explanation
        """
        
        try:
            response = self.client.chat.completions.create(
                model=self.model,
                messages=[
                    {"role": "system", "content": "You are an educational content creator."},
                    {"role": "user", "content": prompt}
                ],
                max_tokens=800,
                temperature=0.5
            )
            
            content = response.choices[0].message.content
            
            # Try to parse JSON
            try:
                questions = json.loads(content)
                return questions if isinstance(questions, list) else []
            except json.JSONDecodeError:
                # If JSON parsing fails, return empty list
                return []
                
        except Exception as e:
            print(f"Error generating practice questions: {e}")
            return []
    
    def explain_concept(self, concept: str, subject: str = None,
                       difficulty: str = 'Intermediate') -> str:
        """Get detailed explanation of a concept"""
        
        prompt = f"""
        Explain the concept of "{concept}" in {subject if subject else 'general terms'}.
        Provide a comprehensive explanation suitable for {difficulty} level students.
        Include:
        1. Clear definition
        2. Key components or principles
        3. Real-world examples
        4. Common misconceptions
        5. Related concepts to explore
        """
        
        try:
            response = self.client.chat.completions.create(
                model=self.model,
                messages=[
                    {"role": "system", "content": "You are an expert educational explainer."},
                    {"role": "user", "content": prompt}
                ],
                max_tokens=600,
                temperature=0.6
            )
            
            return response.choices[0].message.content
            
        except Exception as e:
            return f"Sorry, I couldn't generate an explanation for {concept}. Please try again."
    
    def analyze_student_response(self, question: str, student_answer: str,
                               correct_answer: str = None) -> Dict:
        """Analyze student's answer and provide feedback"""
        
        prompt = f"""
        Analyze this student's answer and provide educational feedback:
        
        Question: {question}
        Student's Answer: {student_answer}
        {f'Correct Answer: {correct_answer}' if correct_answer else ''}
        
        Provide:
        1. Assessment of correctness (correct/partially correct/incorrect)
        2. What the student did well
        3. Areas for improvement
        4. Specific feedback to help them understand better
        5. Encouragement and next steps
        
        Be constructive and educational in your feedback.
        """
        
        try:
            response = self.client.chat.completions.create(
                model=self.model,
                messages=[
                    {"role": "system", "content": "You are an educational assessor providing constructive feedback."},
                    {"role": "user", "content": prompt}
                ],
                max_tokens=400,
                temperature=0.5
            )
            
            return {
                'feedback': response.choices[0].message.content,
                'tokens_used': response.usage.total_tokens if response.usage else 0
            }
            
        except Exception as e:
            return {
                'feedback': f"I couldn't analyze your answer right now. Please try again later.",
                'tokens_used': 0
            }
    
    def suggest_learning_resources(self, subject: str, topic: str,
                                 difficulty: str = 'Intermediate') -> List[str]:
        """Suggest learning resources for a subject and topic"""
        
        prompt = f"""
        Suggest 5 learning resources for studying {topic} in {subject} at {difficulty} level.
        Include a mix of:
        1. Online courses or tutorials
        2. Books or articles
        3. Videos or documentaries
        4. Interactive websites or tools
        5. Practice exercises or problems
        
        For each resource, provide:
        - Type of resource
        - Title/name
        - Brief description
        - Why it's helpful for this topic
        
        Format as a numbered list.
        """
        
        try:
            response = self.client.chat.completions.create(
                model=self.model,
                messages=[
                    {"role": "system", "content": "You are an educational resource curator."},
                    {"role": "user", "content": prompt}
                ],
                max_tokens=500,
                temperature=0.6
            )
            
            content = response.choices[0].message.content
            
            # Split into lines and clean up
            resources = []
            for line in content.split('\n'):
                line = line.strip()
                if line and (line[0].isdigit() or line.startswith('-')):
                    resources.append(line)
            
            return resources[:5]  # Return up to 5 resources
            
        except Exception as e:
            return ["Sorry, I couldn't generate resource suggestions right now. Please try again later."]
    
    def extract_key_topics(self, text: str) -> List[str]:
        """Extract key topics from text"""
        
        prompt = f"""
        Extract the main educational topics from this text:
        
        {text}
        
        List the key topics or concepts that would be important for learning.
        Return as a comma-separated list.
        """
        
        try:
            response = self.client.chat.completions.create(
                model=self.model,
                messages=[
                    {"role": "system", "content": "You are an educational content analyzer."},
                    {"role": "user", "content": prompt}
                ],
                max_tokens=200,
                temperature=0.3
            )
            
            content = response.choices[0].message.content
            
            # Split and clean topics
            topics = [topic.strip() for topic in content.split(',') if topic.strip()]
            return topics[:10]  # Return up to 10 topics
            
        except Exception as e:
            return []
    
    def assess_difficulty_level(self, text: str) -> str:
        """Assess the difficulty level of educational content"""
        
        prompt = f"""
        Assess the difficulty level of this educational content:
        
        {text[:500]}...
        
        Rate it as one of: Beginner, Intermediate, or Advanced
        Consider:
        - Vocabulary complexity
        - Concept depth
        - Prerequisite knowledge required
        
        Respond with just the difficulty level.
        """
        
        try:
            response = self.client.chat.completions.create(
                model=self.model,
                messages=[
                    {"role": "system", "content": "You are an educational content assessor."},
                    {"role": "user", "content": prompt}
                ],
                max_tokens=50,
                temperature=0.1
            )
            
            content = response.choices[0].message.content.strip()
            
            # Validate response
            if content in ['Beginner', 'Intermediate', 'Advanced']:
                return content
            else:
                return 'Intermediate'  # Default fallback
                
        except Exception as e:
            return 'Intermediate'

class TextProcessor:
    """Helper class for text processing operations"""
    
    @staticmethod
    def clean_text(text: str) -> str:
        """Clean and normalize text"""
        # Remove extra whitespace
        text = re.sub(r'\s+', ' ', text)
        # Remove special characters but keep basic punctuation
        text = re.sub(r'[^\w\s.,!?;:()-]', '', text)
        return text.strip()
    
    @staticmethod
    def extract_keywords(text: str, max_keywords: int = 10) -> List[str]:
        """Extract keywords from text"""
        # Simple keyword extraction based on word frequency
        words = re.findall(r'\b[a-zA-Z]{3,}\b', text.lower())
        
        # Common educational stop words
        stop_words = {
            'the', 'and', 'for', 'are', 'with', 'this', 'that', 'from', 'they', 'have',
            'been', 'has', 'had', 'was', 'were', 'will', 'would', 'could', 'should',
            'what', 'when', 'where', 'why', 'how', 'can', 'may', 'might', 'must'
        }
        
        # Filter stop words and count frequency
        word_freq = {}
        for word in words:
            if word not in stop_words and len(word) > 3:
                word_freq[word] = word_freq.get(word, 0) + 1
        
        # Sort by frequency and return top keywords
        keywords = sorted(word_freq.items(), key=lambda x: x[1], reverse=True)
        return [word for word, freq in keywords[:max_keywords]]
    
    @staticmethod
    def estimate_reading_time(text: str) -> int:
        """Estimate reading time in minutes"""
        word_count = len(text.split())
        # Average reading speed: 200 words per minute
        reading_time = max(1, round(word_count / 200))
        return reading_time
