from openai import OpenAI

from typing import Union, Literal
from app.configs import settings

def openai_client(api_key: str | None = None):
    if not api_key:
        api_key = settings.OPENAI_KEY
    return OpenAI(
        api_key=api_key
    )

class ChatGPT:
    
    def __init__(self, 
            model="gpt-4-vision-preview",
            max_token=500
        ) -> None:
        self.model = model
        self.max_token = max_token
        self.client = openai_client()
    
    def chat(self, messages):
        response = self.client.chat.completions.create(
            messages=messages,
            model=self.model,
            max_tokens=self.max_token
        )
        return response.choices[0].message.content

class Voice:
    def __init__(
        self,
        model: Union[str, Literal["tts-1", "tts-1-hd"]] = "tts-1-hd",
        voice: Literal["alloy", "echo", "fable", "onyx", "nova", "shimmer"] = "echo",
        response_format: Literal["mp3", "opus", "aac", "flac", "pcm", "wav"] = "aac",
        speed: float = 1.1,
    ) -> None:
        self.client = openai_client()
        self.model = model
        self.voice = voice
        self.speed = speed
        self.response_format = response_format
        
    def text_to_speech(self, input: str, speech_file_path: str) -> None:
        response = self.client.audio.speech.create(
            input = input,
            model = self.model,
            voice = self.voice,
            speed = self.speed,
            response_format = self.response_format
        )
        response.stream_to_file(speech_file_path)
        
        
        