import logging
import os
import sys
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '../../')))

from typing import Dict, Tuple
from core import StudentNationality, StudyLanguage

logger = logging.getLogger(__name__)




class ContextGenerator:
    """Handles context generation for AI responses"""
    
    def __init__(self, openai_service, pgvector_service):
        self.openai_service = openai_service
        self.pgvector = pgvector_service

    def generate_enhanced_context(self, search_results: list[Dict], student_info: Dict, query_type: str) -> str:
        """Generate enhanced context with JSON-based curriculum structure awareness"""
        if not search_results:
            return ""
        
        is_arabic = student_info['is_arabic']
        study_language = student_info['study_language']
        grade = student_info['grade']
        
        if study_language == StudyLanguage.ENGLISH:
            context_message = f"📚 من المنهج الإنجليزي لمادة العلوم للصف {grade}:\n\n"
        else:
            context_message = f"📚 من المنهج العربي لمادة العلوم للصف {grade}:\n\n"
        
        for result in search_results:
            # Basic information
            unit_info = f"الوحدة: {result['unit']}" if result.get('unit') else ""
            concept_info = f"المفهوم: {result['concept']}" if result.get('concept') else ""
            lesson_info = f"الدرس: {result['lesson']}" if result.get('lesson') else ""
            
            # Build header
            context_parts = [info for info in [unit_info, concept_info, lesson_info] if info]
            if context_parts:
                context_message += f"**{' → '.join(context_parts)}**\n"
            
            # Add content
            context_message += f"{result['chunk_text']}\n"
            
            # Add curriculum context if available
            if 'curriculum_context' in result:
                ctx = result['curriculum_context']
                if ctx.get('navigation_hint'):
                    context_message += f"\n💡 {ctx['navigation_hint']}\n"
                
                if ctx.get('related_concepts') and query_type == "specific_content":
                    related = ', '.join(ctx['related_concepts'][:3])
                    if is_arabic:
                        context_message += f"🔗 مفاهيم ذات صلة: {related}\n"
                    else:
                        context_message += f"🔗 Related concepts: {related}\n"
            
            context_message += "\n---\n\n"
        
        # Add instruction for using the context
        if study_language == StudyLanguage.ENGLISH:
            context_message += f"استخدم هذه المعلومات لتقديم شرح دقيق للطفل. المنهج إنجليزي فاذكر المصطلحات الإنجليزية مع الشرح بالعربي."
        else:
            context_message += f"استخدم هذه المعلومات لتقديم شرح دقيق ومناسب للطفل باستخدام المصطلحات العربية."
            
        return context_message

    def search_enhanced_content(self, query: str, student_info: Dict, subject: str, top_k: int = 3) -> list[Dict]:
        """Search for enhanced content with curriculum context"""
        if not self.pgvector:
            return []
            
        try:
            query_embedding = self.openai_service.generate_embedding(query)
            search_results = self.pgvector.search_with_curriculum_context(
                query_embedding=query_embedding,
                grade=student_info['grade'],
                subject=subject,
                is_arabic=student_info['is_arabic'],
                limit=top_k
            )

            relevant_results = [r for r in search_results if r['distance'] < 1.3] if search_results else []
            return relevant_results

        except Exception as e:
            logger.warning(f"Error in enhanced content search: {e}")
            return []