# services/chat_service.py

from fastapi import UploadFile, HTTPException
from typing import Optional
import sys
import os
import time
import io
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
from core import MessageType, AppConfig
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
        
        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):
        """Process message and generate text and audio response."""
        self.response_manager.clear_response()
        try:
            if file and file.filename:
                result = self.handlers[MessageType.AUDIO].handle(file=file)
                user_message = result.get("transcription", "")
            elif text:
                user_message = text
            else:
                raise HTTPException(status_code=400, detail="No text or audio file provided.")
            
            agent_response_text = self.agent_service.generate_response(
                user_message=user_message,
                student_id=student_id,
            )

            # --- MODIFIED: Call the audio generation method ---
            audio_data = self._generate_and_upload_audio(agent_response_text, student_id)
            
            # --- FIXED: Use the correct 'store_response' method name ---
            self.response_manager.store_response(
                text=agent_response_text,
                audio_filename=audio_data.get("filename"),
                audio_bytes=audio_data.get("bytes")
            )
            
            print(f"Generated response for student {student_id}: {agent_response_text[:100]}...")
            
            return {
                "status": "success",
                "message": "Message processed and agent response ready",
                "student_id": student_id,
                "agent_response": agent_response_text,
                "audio_filename": audio_data.get("filename")
            }
            
        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, student_id: str) -> dict:
        """
        Generates TTS audio and uploads the resulting audio bytes directly to MinIO.
        """
        try:
            student_info = self.agent_service.db_service.get_student_info(student_id)
            if not student_info:
                raise ValueError(f"Could not find student {student_id} for TTS.")
            language = "ar" if student_info.get('is_arabic') else "en"

            audio_bytes = self.agent_service.text_to_speech(text, language)

            provider = os.getenv("TTS_PROVIDER", "openai").lower()
            file_extension = "wav" if provider == "custom" else "mp3"
            
            timestamp = int(time.time())
            filename = f"agent_response_{timestamp}.{file_extension}"
            minio_file_path = f"audio/{filename}"

            print(f"Uploading audio to MinIO: {minio_file_path}")

            # --- FIXED: Call the upload method with the correct argument names ---
            # Your MinIO repo uses 'upload_fileobj' which matches this call.
            self.storage_repo.upload_file(
                file_obj=io.BytesIO(audio_bytes),
                bucket=self.config.minio_bucket,
                file_path=minio_file_path
            )
            
            print(f"Successfully generated and uploaded TTS audio: {filename}")
            return {"bytes": audio_bytes, "filename": filename}
            
        except Exception as e:
            print(f"Error in _generate_and_upload_audio: {e}")
            return {"bytes": None, "filename": None}