from collections import deque
from hashlib import sha512
from pathlib import Path

from gtts import gTTS
from loguru import logger
from pydantic import BaseModel

from src.huesoporro.settings import Settings


class GTTS(BaseModel):
    s: Settings
    chunk_size: int = 128
    text_max_length: int = 100
    queue: deque = deque()

    async def generate(self, text: str, lang: str = "pt", tld="com.br") -> Path:
        text = text[: self.text_max_length]
        raw_filename = f"{text.lower()}_{lang}_{tld}"
        logger.info(f"Generating TTS for {raw_filename}")
        filepath = (
            self.s.tts_cache_path / f"{sha512(raw_filename.encode()).hexdigest()}.mp3"
        )
        tts = gTTS(text=text, lang=lang, tld=tld)
        logger.info(f"Saving TTS to {filepath}")
        tts.save(str(filepath))
        self.queue.append(filepath)
        return filepath

    async def consume(self):
        """If there are items in the queue, return a generator
        that reads the file's bytes by chunks of self.chunk_size"""
        while self.queue:
            filepath = self.queue.popleft()
            if not filepath.exists():
                logger.warning(f"File {filepath} does not exist, skipping")
                continue

            logger.info(f"Reading file {filepath}")
            try:
                with filepath.open("rb") as f:
                    while chunk := f.read(self.chunk_size):
                        yield chunk
                logger.info(f"Finished reading {filepath}")
            except Exception as e:  # noqa: BLE001
                logger.error(f"Error reading file {filepath}: {e}")
                continue
