__all__ = ["Speak_Locally_Sync_LMMH", "TTS_Worker_LMMH"]


import threading, queue, io
from TTS.api import TTS
from pydub import AudioSegment
import torch
from .File_Text_utils import Clean_Text_LMMH, Detect_Language_LMMH



TTS_MODEL_NAME = "tts_models/multilingual/multi-dataset/your_tts"


def TTS_Worker_LMMH():
    #tts_engine = TTS(TTS_MODEL_NAME).to(device)
    #tts_engine = TTS(model_name=TTS_MODEL_NAME, gpu=device == "cuda")  # ✅ CORRECT
    tts_engine = TTS(model_name=TTS_MODEL_NAME, gpu=False)  # ✅ CORRECT

    tts_queue = queue.Queue()

    while True:
        item = tts_queue.get()
        if item is None:
            break
        text, out_path, speaker = item
        text = Clean_Text_LMMH(text)
        language = Detect_Language_LMMH(text)
        try:
            tts_engine.tts_to_file(
                text=text,
                speaker=speaker,
                language=language,
                file_path=out_path,
                speed=1.0
            )
        except Exception as e:
            print(f"TTS error: {e}")
        tts_queue.task_done()

tts_thread = threading.Thread(target=TTS_Worker_LMMH, daemon=True)
tts_thread.start()

def Speak_Locally_Sync_LMMH(text, speaker="male-pt-3\n"):



    #tts_engine = TTS(TTS_MODEL_NAME).to(device)
    #tts_engine = TTS(model_name=TTS_MODEL_NAME, gpu=device == "cuda")  # ✅ CORRECT
    tts_engine = TTS(model_name=TTS_MODEL_NAME, gpu=False)  # ✅ CORRECT

    tts_queue = queue.Queue()

    text = Clean_Text_LMMH(text)
    language = Detect_Language_LMMH(text)
    try:
        buffer = io.BytesIO()
        tts_engine.tts_to_file(text=text, speaker=speaker, language=language, file_path=buffer)
        buffer.seek(0)
        audio = AudioSegment.from_file(buffer, format="wav")
        mp3_buffer = io.BytesIO()
        audio.export(mp3_buffer, format="mp3")
        mp3_buffer.seek(0)
        return mp3_buffer
    except Exception as e:
        print(f"TTS error: {e}")
        return None

