import re
from typing import Any, Literal, Union

from openai._types import NOT_GIVEN, NotGiven
from openai.resources.embeddings import Embeddings
from openai.types.create_embedding_response import CreateEmbeddingResponse, Usage
from openai.types.embedding import Embedding

from core.model_runtime.errors.invoke import InvokeAuthorizationError


class MockEmbeddingsClass:
    def create_embeddings(
        self: Embeddings,
        *,
        input: Union[str, list[str], list[int], list[list[int]]],
        model: Union[str, Literal["text-embedding-ada-002"]],
        encoding_format: Literal["float", "base64"] | NotGiven = NOT_GIVEN,
        **kwargs: Any,
    ) -> CreateEmbeddingResponse:
        if isinstance(input, str):
            input = [input]

        if not re.match(r"^(https?):\/\/[^\s\/$.?#].[^\s]*$", str(self._client.base_url)):
            raise InvokeAuthorizationError("Invalid base url")

        if len(self._client.api_key) < 18:
            raise InvokeAuthorizationError("Invalid API key")

        if encoding_format == "float":
            return CreateEmbeddingResponse(
                data=[
                    Embedding(embedding=[0.23333 for _ in range(233)], index=i, object="embedding")
                    for i in range(len(input))
                ],
                model=model,
                object="list",
                # marked: usage of embeddings should equal the number of testcase
                usage=Usage(prompt_tokens=2, total_tokens=2),
            )

        embeddings = "[encoded data, 8192 characters]"  # noqa: E501

        data = []
        for i, text in enumerate(input):
            obj = Embedding(embedding=[], index=i, object="embedding")
            obj.embedding = embeddings

            data.append(obj)

        return CreateEmbeddingResponse(
            data=data,
            model=model,
            object="list",
            # marked: usage of embeddings should equal the number of testcase
            usage=Usage(prompt_tokens=2, total_tokens=2),
        )
