# Copyright 2025 Vijil, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# vijil and vijil-dome are trademarks owned by Vijil Inc.

import asyncio
from typing import List
from vijil_dome.types import Sentences
from vijil_dome.embeds.models import AbstractEmbeddingsModel


# Executor for computing embeddings, if required
embeddings_executor = None


class SentenceTransformerEmbeddingModel(AbstractEmbeddingsModel):
    """Embedding model using sentence-transformers.

    This class represents an embedding model that utilizes the sentence-transformers library
    for generating sentence embeddings.

    Args:
        embedding_model (str): The name or path of the pre-trained sentence-transformers model.

    Attributes:
        model: The sentence-transformers model used for encoding sentences.
        embedding_size: The dimensionality of the sentence embeddings generated by the model.
    """

    def __init__(self, embedding_model: str):
        from sentence_transformers import SentenceTransformer
        from torch import cuda

        device = "cuda" if cuda.is_available() else "cpu"
        self.model = SentenceTransformer(embedding_model, device=device)
        self.embedding_size = self.model.get_sentence_embedding_dimension()

    async def encode_async(self, sentences: Sentences) -> List[List[float]]:
        """Encode a list of documents into their corresponding sentence embeddings.

        Args:
            documents (List[str]): The list of documents to be encoded.

        Returns:
            List[List[float]]: The list of sentence embeddings, where each embedding is a list of floats.
        """
        loop = asyncio.get_running_loop()
        result = await loop.run_in_executor(
            embeddings_executor, self.model.encode, sentences
        )
        return result.tolist()
