import subprocess
from ctypes import *


class Aques:
    @classmethod
    def main (cls, text: str, goatoh_mode: bool = False) -> bytearray | None:
        return cls.__synthe_utf8 (text, 100, './phont/ar_m5.phont' if goatoh_mode else './phont/ar_mf2.phont')

    @staticmethod
    def __synthe_utf8 (text, speed, phont_file = None) -> bytearray | None:
        if phont_file is None:
            phont = None
        else:
            with open (phont_file, 'rb') as f:
                phont = f.read ()

        p = subprocess.Popen ('./aques', stdin = subprocess.PIPE,
                              stdout = subprocess.PIPE)
        koe: str = p.communicate (text.encode ())[0].decode ()

        aqtk = cdll.LoadLibrary ('libAquesTalk2Eva.so')
        aqtk.AquesTalk2_Synthe_Utf8.restype = POINTER (ARRAY (c_ubyte, 0))
        size = c_int (0)
        wav_p = aqtk.AquesTalk2_Synthe_Utf8 (koe.encode ('utf-8'), speed,
                                             byref (size), phont)

        if not bool (wav_p):
            return None

        wav_p = cast (wav_p, POINTER (ARRAY (c_ubyte, size.value)))
        wav = bytearray (wav_p.contents)
        aqtk.AquesTalk2_FreeWave (wav_p)

        return wav

