# ==== CREATED AND OWNED BY askme360 (HIPL) ====
import os
from openai import OpenAI

from ..askme_base import AskmeBase

from app.services.llm_service import LLMService


class OpenAI_Embeddings(AskmeBase):
    def __init__(self, client=None, config=None):
        AskmeBase.__init__(self, config=config)

        if client is not None:
            self.client = client
            return

        if self.client is not None:
            return

        self.client = OpenAI()

        if config is None:
            return

        if "api_type" in config:
            self.client.api_type = config["api_type"]

        if "api_base" in config:
            self.client.api_base = config["api_base"]

        if "api_version" in config:
            self.client.api_version = config["api_version"]

        if "api_key" in config:
            self.client.api_key = config["api_key"]

    def generate_embedding(self, data: str, **kwargs) -> list[float]:
        api_key = None
        if self.config:
            api_key = self.config.get("api_key") or self.config.get("open_ai")
        if not api_key:
            api_key = os.getenv("OPENAI_API_KEY", "")
        if not api_key:
            raise ValueError("API key required for embeddings")
        ckey = ""
        if self.config:
            ckey = (self.config.get("claude_api_key") or "").strip()
        return LLMService(api_key=api_key, claude_api_key=ckey).create_embedding(data)
