from fastapi import UploadFile, HTTPException
from typing import Optional
import sys
import os
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
from core import MessageType, AppConfig, StudentNationality
from repositories import StorageRepository
from services.response_manager import ResponseManager
from services.openai_service import OpenAIService
from services.agent_service import AgentService


class ChatService:
    def __init__(self, storage_repo: StorageRepository, response_manager: ResponseManager, 
                 config: AppConfig, openai_service: OpenAIService, agent_service: AgentService):
        from handlers import AudioMessageHandler, TextMessageHandler
        
        self.storage_repo = storage_repo
        self.response_manager = response_manager
        self.config = config
        self.openai_service = openai_service
        self.agent_service = agent_service
        
        # Message handlers
        self.handlers = {
            MessageType.AUDIO: AudioMessageHandler(
                storage_repo, 
                config.minio_bucket,
                openai_service
            ),
            MessageType.TEXT: TextMessageHandler()
        }

    def process_message(self, 
                       student_id: str,
                       file: Optional[UploadFile] = None, 
                       text: Optional[str] = None,
                       nationality: StudentNationality = StudentNationality.EGYPTIAN) -> dict:
        """Process message for student using database memory"""
        self.response_manager.clear_response()

        try:
            # Process the input message
            if file and file.filename:
                result = self.handlers[MessageType.AUDIO].handle(file=file)
                if result.get("status") == "success":
                    user_message = result.get("transcription", "")
                    if not user_message:
                        user_message = "تم إرسال رسالة صوتية - فشل في التفريغ المحلي"
                else:
                    raise HTTPException(status_code=400, detail="Failed to process audio message")
                    
            elif text:
                result = self.handlers[MessageType.TEXT].handle(text=text)
                user_message = text
                
            else:
                raise HTTPException(status_code=400, detail="No text or audio file provided.")
            
            # Generate agent response using database
            try:
                agent_response = self.agent_service.generate_response(
                    user_message=user_message,
                    student_id=student_id,
                    nationality=nationality
                )

                # Generate TTS audio
                audio_filename = self._generate_and_upload_audio(agent_response)
                
                # Store response for retrieval
                self.response_manager.store_response(agent_response, audio_filename)
                
                print(f"Generated response for student {student_id}: {agent_response[:100]}...")
                
                return {
                    "status": "success",
                    "message": "Message processed and agent response ready",
                    "student_id": student_id,
                    "agent_response": agent_response,
                    "audio_filename": audio_filename
                }
                
            except Exception as agent_error:
                print(f"Agent error for student {student_id}: {agent_error}")
                raise HTTPException(status_code=500, detail=f"Agent response failed: {str(agent_error)}")
                
        except Exception as e:
            print(f"Error processing message for student {student_id}: {e}")
            raise HTTPException(status_code=500, detail=f"Failed to process message: {str(e)}")

    def _generate_and_upload_audio(self, text: str) -> str:
        """Generate and upload TTS audio"""
        try:
            import time
            
            temp_file_path = self.openai_service.generate_speech(text)
            
            timestamp = int(time.time())
            filename = f"agent_response_{timestamp}.mp3"
            minio_file_path = f"audio/{filename}"
            
            print(f"Uploading audio to MinIO: {minio_file_path}")
            
            with open(temp_file_path, 'rb') as audio_file:
                self.storage_repo.upload_file(audio_file, self.config.minio_bucket, minio_file_path)
            
            self.openai_service.cleanup_temp_file(temp_file_path)
            
            print(f"Successfully generated TTS audio: {filename}")
            return filename
            
        except Exception as e:
            print(f"Error generating audio: {e}")
            return None