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 (no webhook dependencies)
        self.handlers = {
            MessageType.AUDIO: AudioMessageHandler(
                storage_repo, 
                config.minio_bucket,
                openai_service
            ),
            MessageType.TEXT: TextMessageHandler()
        }

    def process_message(self, file: Optional[UploadFile] = None, text: Optional[str] = None) -> dict:
        """Process incoming message and generate agent response directly"""
        self.response_manager.clear_response()

        try:
            # Process the input message first
            if file and file.filename:
                # Handle audio message - transcribe first
                result = self.handlers[MessageType.AUDIO].handle(file=file)
                if result.get("status") == "success":
                    # Get transcribed text from the result
                    user_message = result.get("transcription", "")
                    if not user_message:
                        # Fallback message if transcription failed
                        user_message = "تم إرسال رسالة صوتية - فشل في التفريغ المحلي"
                else:
                    raise HTTPException(status_code=400, detail="Failed to process audio message")
                    
            elif text:
                # Handle text message
                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 the local agent service
            try:
                agent_response = self.agent_service.generate_response(user_message, nationality=StudentNationality.EGYPTIAN)

                # Generate TTS audio from the response
                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 agent response: {agent_response[:100]}...")
                
                return {
                    "status": "success",
                    "message": "Message processed and agent response ready",
                    "agent_response": agent_response,
                    "audio_filename": audio_filename
                }
                
            except Exception as agent_error:
                print(f"Agent service error: {agent_error}")
                raise HTTPException(status_code=500, detail=f"Agent response generation failed: {str(agent_error)}")
                
        except Exception as e:
            print(f"Error processing message: {e}")
            raise HTTPException(status_code=500, detail=f"Failed to process message: {str(e)}")

    def _generate_and_upload_audio(self, text: str) -> str:
        """Generate audio from text and upload to MinIO, return filename"""
        try:
            import time
            
            # Generate audio using OpenAI service
            temp_file_path = self.openai_service.generate_speech(text)
            
            # Generate unique filename for MinIO
            timestamp = int(time.time())
            filename = f"agent_response_{timestamp}.mp3"
            minio_file_path = f"audio/{filename}"
            
            print(f"Uploading generated audio to MinIO: {minio_file_path}")
            
            # Upload to MinIO
            with open(temp_file_path, 'rb') as audio_file:
                self.storage_repo.upload_file(audio_file, self.config.minio_bucket, minio_file_path)
            
            # Clean up temporary file
            self.openai_service.cleanup_temp_file(temp_file_path)
            
            print(f"Successfully generated and uploaded TTS audio: {filename}")
            return filename
            
        except Exception as e:
            print(f"Error generating and uploading audio: {e}")
            # Don't fail the entire request if TTS fails
            return None
    
    def get_agent_stats(self, conversation_id: str = "default") -> dict:
        """Get conversation statistics from agent service"""
        return self.agent_service.get_conversation_stats(conversation_id)
    
    def clear_conversation(self, conversation_id: str = "default"):
        """Clear conversation history"""
        self.agent_service.clear_conversation(conversation_id)
        return {"status": "success", "message": f"Conversation {conversation_id} cleared"}
    
    def set_system_prompt(self, prompt: str):
        """Update the agent's system prompt"""
        self.agent_service.set_system_prompt(prompt)
        return {"status": "success", "message": "System prompt updated"}