from fastapi import Response, status
from fastapi.responses import JSONResponse
from .blackbox import Blackbox
from gtts import gTTS
from io import BytesIO
from injector import singleton
@singleton
class TextToAudio(Blackbox):
    
    def __call__(self, *args, **kwargs):
        return self.processing(*args, **kwargs)

    def valid(self, data: any) -> bool:
        return isinstance(data, str)
    
    def processing(self, text: any) -> BytesIO:
        if not self.valid(text):
            raise ValueError("Invalid data")
        tts = gTTS(text=text, lang="en")
        fp = BytesIO()
        tts.write_to_fp(fp)
        fp.seek(0)
        return fp
    
    async def fast_api_handler(self, request) -> Response:
        try:
            data = await request.json()
        except:
            return JSONResponse(content={"error": "json parse error"}, status_code=status.HTTP_400_BAD_REQUEST)
        text = data.get("text")
        if text is None:
            return JSONResponse(content={"error": "text is required"}, status_code=status.HTTP_400_BAD_REQUEST)
        by = self.processing(text)
        return Response(content=by.read(), media_type="audio/mp3", headers={"Content-Disposition": "attachment; filename=audio.mp3"})