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
from repositories import StorageRepository, WebhookClient
from services.response_manager import ResponseManager
from services.openai_service import OpenAIService


class ChatService:
    def __init__(self, storage_repo: StorageRepository, webhook_client: WebhookClient, 
                 response_manager: ResponseManager, config: AppConfig, openai_service: OpenAIService):
        from handlers import AudioMessageHandler, TextMessageHandler
        self.storage_repo = storage_repo
        self.webhook_client = webhook_client
        self.response_manager = response_manager
        self.config = config
        self.openai_service = openai_service
        
        # Message handlers with OpenAI service dependency
        self.handlers = {
            MessageType.AUDIO: AudioMessageHandler(
                storage_repo, 
                webhook_client, 
                config.minio_bucket,
                openai_service  # Pass OpenAI service
            ),
            MessageType.TEXT: TextMessageHandler(webhook_client)
        }

    def process_message(self, file: Optional[UploadFile] = None, text: Optional[str] = None) -> dict:
        self.response_manager.clear_response()

        if file and file.filename:
            return self.handlers[MessageType.AUDIO].handle(file=file)
        elif text:
            return self.handlers[MessageType.TEXT].handle(text=text)
        else:
            raise HTTPException(status_code=400, detail="No text or audio file provided.")