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

from typing import List
from core import StudentNationality, StudyLanguage
from schemas import StudentProfile, SearchResult 

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[SearchResult], student_info: StudentProfile, query_type: str) -> str:
        """Generate enhanced context with JSON-based curriculum structure awareness"""
        if not search_results:
            return ""
        
        # Access via Dot Notation
        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:
            # Access via Dot Notation
            unit_info = f"الوحدة: {result.unit}" if result.unit else ""
            concept_info = f"المفهوم: {result.concept}" if result.concept else ""
            lesson_info = f"الدرس: {result.lesson}" if result.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 result.curriculum_context:
                ctx = result.curriculum_context
                if ctx.navigation_hint:
                    context_message += f"\n💡 {ctx.navigation_hint}\n"
                
                if ctx.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: StudentProfile, subject: str, top_k: int = 3) -> List[SearchResult]:
        """Search for enhanced content with curriculum context"""
        if not self.pgvector:
            return []
            
        try:
            query_embedding = self.openai_service.generate_embedding(query)
            # PGVector now returns List[SearchResult]
            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
            )

            # Access via Dot Notation
            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 []