from openai import OpenAI
from src.ApiKeys.openai_apikey import OpenAICredencial

class OpenAICliente:
    def __init__(self, credencial: OpenAICredencial):
        """
        Inicializa el cliente de OpenAI con una instancia de OpenAICredencial.
        """
        self.credencial = credencial
        self.client = OpenAI(api_key=self.credencial.api_key)
        if self.credencial.organizacion:
            self.client.organization = self.credencial.organizacion

    # --- Chat Completions ---
    def chat_completion(self, model: str, messages: list, stream: bool = False, **kwargs):
        response = self.client.chat.completions.create(
            model=model, 
            messages=messages, 
            stream=stream,  # Parámetro explícito
            **kwargs
        )
        return self._handle_stream(response, stream) if stream else response

    def _handle_stream(self, stream, _):
        for chunk in stream:
            if chunk.choices and chunk.choices[0].delta.content:
                yield chunk.choices[0].delta.content

    # --- Text Completions (legacy) ---
    def completion(self, model: str, prompt: str, **kwargs):
        return self.client.completions.create(model=model, prompt=prompt, **kwargs)

    # --- Text Edits ---
    def edit(self, model: str, input: str, instruction: str, **kwargs):
        return self.client.edits.create(model=model, input=input, instruction=instruction, **kwargs)

    # --- Embeddings ---
    def embedding(self, model: str, input: str | list[str], **kwargs):
        return self.client.embeddings.create(model=model, input=input, **kwargs)

    # --- Moderation ---
    def moderation(self, input: str | list[str], model="text-moderation-latest", **kwargs):
        return self.client.moderations.create(input=input, model=model, **kwargs)

    # --- Image Generation ---
    def image_generate(self, prompt: str, **kwargs):
        return self.client.images.generate(prompt=prompt, **kwargs)

    # --- Audio Transcription ---
    def audio_transcribe(self, model: str, file_path: str, **kwargs):
        with open(file_path, "rb") as f:
            return self.client.audio.transcriptions.create(model=model, file=f, **kwargs)

    # --- Audio Translation ---
    def audio_translate(self, model: str, file_path: str, **kwargs):
        with open(file_path, "rb") as f:
            return self.client.audio.translations.create(model=model, file=f, **kwargs)

    # --- File Upload ---
    def file_upload(self, file_path: str, purpose="fine-tune", **kwargs):
        with open(file_path, "rb") as f:
            return self.client.files.create(file=f, purpose=purpose, **kwargs)

    # --- File List ---
    def file_list(self, **kwargs):
        return self.client.files.list(**kwargs)

    # --- File Delete ---
    def file_delete(self, file_id: str, **kwargs):
        return self.client.files.delete(file_id=file_id, **kwargs)