import logging
import os
from typing import Optional
import sys
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))

from core import Models
from services.pgvector_service import PGVectorService
from services.openai_service import OpenAIService
from services.chat_database_service import ChatDatabaseService
from services.pedagogy_service import PedagogyService
from services.connection_pool import ConnectionPool
from services.agent_helpers.query_handlers import QueryHandler
from services.agent_helpers.context_generator import ContextGenerator
from services.agent_helpers.response_generator import ResponseGenerator
from services.agent_helpers.tashkeel_agent import TashkeelAgent
from services.agent_helpers.tashkeel_fixer import apply_fixes, custom_fixes
from services.tts.tts_manager import get_tts_service
from schemas import AgentRequest

logger = logging.getLogger(__name__)

class AgentService:
    """Main service class for handling AI agent conversations with modular architecture"""

    def __init__(self, use_pgvector: bool = True, pgvector: PGVectorService = None,
                 db_service: ChatDatabaseService = None):
        # Initialize core services
        self.openai_service = OpenAIService()
        if not self.openai_service.is_available():
            logger.warning("Warning: OPENAI_API_KEY not found. Agent service will be disabled.")
        
        self.tts_service = get_tts_service(self.openai_service)
        if not self.tts_service.is_available():
            logger.warning("Warning: No TTS service is available.")

        
        
        self.db_service = db_service
        
        # PGVector setup
        self.use_pgvector = use_pgvector
        if self.use_pgvector:
            self.pgvector = pgvector
            self.pgvector.setup_curriculum_table()
        else:
            self.pgvector = None

        self.pedagogy_service = PedagogyService()
        
        # Initialize modular components
        self.query_handler = QueryHandler(self.openai_service, self.pgvector, self.db_service)
        self.context_generator = ContextGenerator(self.openai_service, self.pgvector)
        self.response_generator = ResponseGenerator(
            self.openai_service, self.db_service, self.pedagogy_service,
            self.query_handler, self.context_generator, self
        )

        self.tashkeel_agent = TashkeelAgent(self.openai_service)


    def is_available(self) -> bool:
        return self.openai_service.is_available()



    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):

        """
        Main response generation method, now handles both string and dictionary responses.
        """
        # This can return either a string (for text answers) or a dict (for MCQs)
        response = self.response_generator.generate_response(
            user_message, student_id, subject, model, temperature, top_k
        )

        # Check if the response is a special dictionary type (like our MCQ response).
        # If it is, we must return it directly without any text processing.
        if isinstance(response, dict):
            logger.info("AgentService received a structured response (MCQ). Bypassing text processing.")
            return response

        # If we reach here, it means the response is a normal text string.
        # Now it is safe to apply text-based fixes.
        #response = apply_fixes(response, custom_fixes)
        # response = self.tashkeel_agent.apply_tashkeel(response)

        print(f"response: {response}")
        return response
