import json
import os
from typing import Any, Optional

from llama_index.embeddings.azure_openai import AzureOpenAIEmbedding
from llama_index.embeddings.base import BaseEmbedding
from unstract.adapters.embedding.embedding_adapter import EmbeddingAdapter


class Constants:
    ADAPTER_NAME = "adapter_name"
    MODEL = "model"
    EMBED_BATCH_SIZE = "embed_batch_size"
    API_KEY = "api_key"
    API_VERSION = "api_version"
    AZURE_ENDPOINT = "azure_endpoint"
    MAX_RETRIES = "max_retries"
    TIMEOUT = "timeout"
    VECTOR_SIZE = "vector_size"
    DEPLOYMENT_NAME = "engine"


class AzureOpenAI(EmbeddingAdapter):
    def __init__(self, settings: dict[str, Any]):
        super().__init__("AzureOpenAIEmbedding")
        self.config = settings
        self.json_credentials = json.loads(
            settings.get("json_credentials", "{}")
        )

    @staticmethod
    def get_id() -> str:
        return "azureopenai|9770f3f6-f8ba-4fa0-bb3a-bef48a00e66f"

    @staticmethod
    def get_name() -> str:
        return "AzureOpenAIEmbedding"

    @staticmethod
    def get_description() -> str:
        return "AzureOpenAI Embedding"

    @staticmethod
    def get_icon() -> str:
        return (
            "https://storage.googleapis.com/pandora-static/"
            "adapter-icons/AzureopenAI.png"
        )

    @staticmethod
    def get_json_schema() -> str:
        f = open(f"{os.path.dirname(__file__)}/static/json_schema.json")
        schema = f.read()
        f.close()
        return schema

    def get_embedding_instance(self) -> Optional[BaseEmbedding]:
        embedding = AzureOpenAIEmbedding(
            model=str(self.config.get(Constants.MODEL)),
            deployment_name=str(self.config.get(Constants.DEPLOYMENT_NAME)),
            api_key=str(self.config.get(Constants.API_KEY)),
            api_version=str(self.config.get(Constants.API_VERSION)),
            azure_endpoint=str(self.config.get(Constants.AZURE_ENDPOINT)),
            api_type="azure",
        )
        return embedding
