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 handlers import AudioMessageHandler, TextMessageHandler
from services.response_manager import ResponseManager


class ChatService:
    def __init__(self, storage_repo: StorageRepository, webhook_client: WebhookClient, 
                 response_manager: ResponseManager, config: AppConfig):
        self.storage_repo = storage_repo
        self.webhook_client = webhook_client
        self.response_manager = response_manager
        self.config = config
        
        # Message handlers
        self.handlers = {
            MessageType.AUDIO: AudioMessageHandler(storage_repo, webhook_client, config.minio_bucket),
            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.")
