import os
import sys
from typing import Dict
from fastapi import HTTPException
from services.agent_helpers.agent_prompts import SYSTEM_PROMPTS
import logging
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '../../')))
from core import StudentNationality, StudyLanguage, Models

logger = logging.getLogger(__name__)

class ResponseGenerator:
    """Handles AI response generation and conversation management"""
    
    def __init__(self, openai_service, db_service, pedagogy_service, query_handler, context_generator):
        self.openai_service = openai_service
        self.db_service = db_service
        self.pedagogy_service = pedagogy_service
        self.query_handler = query_handler
        self.context_generator = context_generator

    def get_conversation_history(self, student_id: str) -> list[Dict[str, str]]:
        """Get conversation history from database"""
        try:
            return self.db_service.get_chat_history(student_id)
        except Exception as e:
            logger.error(f"Error getting conversation history for {student_id}: {e}")
            return []

    def add_message_to_history(self, student_id: str, message: str, role: str = "user"):
        """Add message to database"""
        try:
            self.db_service.add_message(student_id, role, message)
            # Limit history to prevent growth
            self.db_service.limit_history(student_id, max_messages=38)
        except Exception as e:
            logger.error(f"Error adding message to history for {student_id}: {e}")

    def prepare_system_prompt(self, student_info: Dict) -> str:
        """Prepare system prompt based on student information"""
        student_name = student_info.get('student_name', 'الطالب').split()[0]
        study_language = student_info['study_language']
        
        # Map nationality
        nationality_lower = student_info['nationality'].lower().strip()
        nationality_mapping = {
            'egyptian': StudentNationality.EGYPTIAN,
            'saudi': StudentNationality.SAUDI
        }
        nationality = nationality_mapping.get(nationality_lower, StudentNationality.EGYPTIAN)

        # Get appropriate system prompt
        prompt_key = (nationality, study_language)
        base_system_prompt = SYSTEM_PROMPTS.get(prompt_key, 
            SYSTEM_PROMPTS.get((StudentNationality.EGYPTIAN, StudyLanguage.ARABIC), ""))
        
        formatted_base_prompt = base_system_prompt.format(
            student_name=student_name,
            grade=student_info['grade']
        )

        # Add Socratic instructions if any
        socratic_instructions = self.pedagogy_service.get_socratic_instructions(
            student_info['grade'], student_info['nationality']
        )
        if socratic_instructions:
            formatted_base_prompt += f"\n\n{socratic_instructions}"

        return formatted_base_prompt

    def generate_response(
        self,
        user_message: str,
        student_id: str,
        subject: str = "Science",
        model: str = Models.chat,
        temperature: float = 0.3,
        top_k: int = 3
    ) -> str:
        """Enhanced AI response generation with JSON-based curriculum structure awareness"""
        if not self.openai_service.is_available():
            raise HTTPException(status_code=500, detail="Agent service not available")

        try:
            # Get student info
            student_info = self.db_service.get_student_info(student_id)
            if not student_info:
                raise HTTPException(status_code=404, detail=f"Student with ID {student_id} not found")

            student_name = student_info.get('student_name', 'الطالب').split()[0]
            study_language = student_info['study_language']

            # Add user message to DB
            self.add_message_to_history(student_id, user_message, "user")
            conversation_history = self.get_conversation_history(student_id)

            # Classify query type
            query_type = self.query_handler.classify_query_type(user_message, student_info, student_id)
            logger.info(f"Query type: {query_type} for student {student_name} ({study_language.value}) with conversation context")

            # Prepare system prompt
            formatted_base_prompt = self.prepare_system_prompt(student_info)

            # Build base messages
            messages = [{"role": "system", "content": formatted_base_prompt}]
            messages.extend(conversation_history)
            messages.append({"role": "user", "content": user_message})

            # ==========================
            # HANDLE UNSAFE QUERIES
            # ==========================
            if query_type.startswith("unsafe_"):
                if query_type == "unsafe_religion":
                    unsafe_context = self.query_handler.handle_unsafe_religion_query(student_info)
                elif query_type == "unsafe_sensitive_emotion":
                    unsafe_context = self.query_handler.handle_unsafe_sensitive_emotion_query(student_info)
                elif query_type == "unsafe_sensitive_bio":
                    unsafe_context = self.query_handler.handle_unsafe_sensitive_bio_query(student_info)
                elif query_type == "unsafe_personal":
                    unsafe_context = self.query_handler.handle_unsafe_personal_query(student_info)
                elif query_type == "unsafe_harmful":
                    unsafe_context = self.query_handler.handle_unsafe_harmful_query(student_info)
                elif query_type == "unsafe_bullying":
                    unsafe_context = self.query_handler.handle_unsafe_bullying_query(student_info)
                else:
                    unsafe_context = "هذا الموضوع غير مناسب للمناقشة هنا."

                # نضيف التعليمات كـ system context بدل الرد المباشر
                messages.append({
                    "role": "system",
                    "content": f"التعليمات للتعامل مع الموضوع الحساس:\n{unsafe_context}"
                })

            # ==========================
            # HANDLE SAFE QUERIES
            # ==========================
            else:
                if query_type == "general_chat":
                    chat_context = self.query_handler.handle_general_chat_query(user_message, student_info)
                    messages.append({"role": "system", "content": f"سياق المحادثة العامة:\n{chat_context}"})
                    
                elif query_type == "overview":
                    overview_response = self.query_handler.handle_overview_query(student_info, subject)
                    messages.append({"role": "system", "content": f"المنهج الكامل من ملف JSON:\n{overview_response}"})
                    
                elif query_type == "navigation":
                    navigation_response = self.query_handler.handle_navigation_query(user_message, student_info, subject)
                    messages.append({"role": "system", "content": f"تفاصيل الوحدة/المفهوم من JSON:\n{navigation_response}"})
                    
                elif query_type == "specific_content":
                    # Enhanced content search
                    relevant_results = self.context_generator.search_enhanced_content(
                        user_message, student_info, subject, top_k
                    )
                    if relevant_results:
                        enhanced_context = self.context_generator.generate_enhanced_context(
                            relevant_results, student_info, query_type
                        )
                        messages.append({"role": "system", "content": enhanced_context})
                        logger.info(f"Added enhanced context with {len(relevant_results)} chunks for student {student_name}")

            # ==========================
            # CALL AI MODEL
            # ==========================
            response = self.openai_service.client.chat.completions.create(
                model=model,
                messages=messages,
                temperature=temperature
            )
            ai_response = response.choices[0].message.content.strip()
            if not ai_response:
                raise ValueError("Empty response from AI model")

            # Save AI response
            self.add_message_to_history(student_id, ai_response, "assistant")
            
            logger.info(f"Generated {query_type} response for {student_name} ({study_language.value}) with conversation context: {len(ai_response)} characters")
            
            return ai_response

        except HTTPException:
            raise
        except Exception as e:
            logger.error(f"Error generating response for student {student_id}: {e}")
            raise HTTPException(status_code=500, detail="Error generating response")
