# -*- coding: utf-8 -*-
# Copyright (c) Alibaba, Inc. and its affiliates.

# adapter from openai sdk
from dataclasses import dataclass
from typing import List, Literal, Optional

from dashscope.common.base_type import BaseObjectMixin


@dataclass(init=False)
class CompletionUsage(BaseObjectMixin):
    completion_tokens: int
    """Number of tokens in the generated completion."""

    prompt_tokens: int
    """Number of tokens in the prompt."""

    total_tokens: int
    """Total number of tokens used in the request (prompt + completion)."""

    def __init__(self, **kwargs):  # pylint: disable=useless-parent-delegation
        super().__init__(**kwargs)


@dataclass(init=False)
class TopLogprob(BaseObjectMixin):
    token: str
    """The token."""

    bytes: Optional[List[int]] = None
    """A list of integers representing the UTF-8 bytes representation of the token.  # noqa: E501

    Useful in instances where characters are represented by multiple tokens and
    their byte representations must be combined to generate the correct text
    representation. Can be `null` if there is no bytes representation for the token.
    """

    logprob: float  # type: ignore[misc]
    """The log probability of this token, if it is within the top 20 most likely  # noqa: E501
    tokens.

    Otherwise, the value `-9999.0` is used to signify that the token is very
    unlikely.
    """

    def __init__(self, **kwargs):  # pylint: disable=useless-parent-delegation
        super().__init__(**kwargs)


@dataclass(init=False)
class ChatCompletionTokenLogprob(BaseObjectMixin):
    token: str
    """The token."""

    bytes: Optional[List[int]] = None
    """A list of integers representing the UTF-8 bytes representation of the token.  # noqa: E501

    Useful in instances where characters are represented by multiple tokens and
    their byte representations must be combined to generate the correct text
    representation. Can be `null` if there is no bytes representation for the token.
    """

    logprob: float  # type: ignore[misc]
    """The log probability of this token, if it is within the top 20 most likely  # noqa: E501
    tokens.

    Otherwise, the value `-9999.0` is used to signify that the token is very
    unlikely.
    """

    top_logprobs: List[TopLogprob]  # type: ignore[misc]
    """List of the most likely tokens and their log probability, at this token
    position.

    In rare cases, there may be fewer than the number of requested `top_logprobs`  # noqa: E501
    returned.
    """

    def __init__(self, **kwargs):
        if (
            "top_logprobs" in kwargs
            and kwargs["top_logprobs"] is not None
            and kwargs["top_logprobs"]
        ):
            top_logprobs = []
            for logprob in kwargs["top_logprobs"]:
                top_logprobs.append(ChatCompletionTokenLogprob(**logprob))
            self.top_logprobs = top_logprobs
        else:
            self.top_logprobs = None

        super().__init__(**kwargs)


@dataclass(init=False)
class ChoiceLogprobs(BaseObjectMixin):
    content: Optional[List[ChatCompletionTokenLogprob]] = None
    """A list of message content tokens with log probability information."""

    def __init__(self, **kwargs):
        if (
            "content" in kwargs
            and kwargs["content"] is not None
            and kwargs["content"]
        ):
            logprobs = []
            for logprob in kwargs["content"]:
                logprobs.append(ChatCompletionTokenLogprob(**logprob))
            self.content = logprobs
        else:
            self.content = None

        super().__init__(**kwargs)


@dataclass(init=False)
class FunctionCall(BaseObjectMixin):
    arguments: str
    """
    The arguments to call the function with, as generated by the model in JSON
    format. Note that the model does not always generate valid JSON, and may
    hallucinate parameters not defined by your function schema. Validate the
    arguments in your code before calling your function.
    """

    name: str
    """The name of the function to call."""

    def __init__(self, **kwargs):  # pylint: disable=useless-parent-delegation
        super().__init__(**kwargs)


@dataclass(init=False)
class Function(BaseObjectMixin):
    arguments: str
    """
    The arguments to call the function with, as generated by the model in JSON
    format. Note that the model does not always generate valid JSON, and may
    hallucinate parameters not defined by your function schema. Validate the
    arguments in your code before calling your function.
    """

    name: str
    """The name of the function to call."""

    def __init__(self, **kwargs):  # pylint: disable=useless-parent-delegation
        super().__init__(**kwargs)


@dataclass(init=False)
class ChatCompletionMessageToolCall(BaseObjectMixin):
    id: str
    """The ID of the tool call."""

    function: Function
    """The function that the model called."""

    type: Literal["function"]
    """The type of the tool. Currently, only `function` is supported."""

    def __init__(self, **kwargs):
        if (
            "function" in kwargs
            and kwargs["function"] is not None
            and kwargs["function"]
        ):
            self.function = Function(**kwargs.pop("function", {}))
        else:
            self.function = None

        super().__init__(**kwargs)


@dataclass(init=False)
class ChatCompletionMessage(BaseObjectMixin):
    content: Optional[str] = None
    """The contents of the message."""

    role: Literal["assistant"]  # type: ignore[misc]
    """The role of the author of this message."""

    function_call: Optional[FunctionCall] = None
    """Deprecated and replaced by `tool_calls`.

    The name and arguments of a function that should be called, as generated by the  # noqa: E501
    model.
    """

    tool_calls: Optional[List[ChatCompletionMessageToolCall]] = None
    """The tool calls generated by the model, such as function calls."""

    def __init__(self, **kwargs):
        if (
            "function_call" in kwargs
            and kwargs["function_call"] is not None
            and kwargs["function_call"]
        ):
            self.function_call = FunctionCall(
                **kwargs.pop("function_call", {}),
            )

        if (
            "tool_calls" in kwargs
            and kwargs["tool_calls"] is not None
            and kwargs["tool_calls"]
        ):
            tool_calls = []
            for tool_call in kwargs["tool_calls"]:
                tool_calls.append(ChatCompletionMessageToolCall(**tool_call))
            self.tool_calls = tool_calls

        super().__init__(**kwargs)


@dataclass(init=False)
class Choice(BaseObjectMixin):
    finish_reason: Literal[
        "stop",
        "length",
        "tool_calls",
        "content_filter",
        "function_call",
    ]
    """The reason the model stopped generating tokens.

    This will be `stop` if the model hit a natural stop point or a provided stop  # noqa: E501
    sequence, `length` if the maximum number of tokens specified in the request was  # noqa: E501
    reached, `content_filter` if content was omitted due to a flag from our content  # noqa: E501
    filters, `tool_calls` if the model called a tool, or `function_call`
    (deprecated) if the model called a function.
    """

    index: int
    """The index of the choice in the list of choices."""

    logprobs: Optional[ChoiceLogprobs] = None
    """Log probability information for the choice."""

    message: ChatCompletionMessage  # type: ignore[misc]
    """A chat completion message generated by the model."""

    def __init__(self, **kwargs):
        if (
            "message" in kwargs
            and kwargs["message"] is not None
            and kwargs["message"]
        ):
            self.message = ChatCompletionMessage(**kwargs.pop("message", {}))
        else:
            self.message = None

        if (
            "logprobs" in kwargs
            and kwargs["logprobs"] is not None
            and kwargs["logprobs"]
        ):
            self.logprobs = ChoiceLogprobs(**kwargs.pop("logprobs", {}))

        super().__init__(**kwargs)


@dataclass(init=False)
class ChatCompletion(BaseObjectMixin):
    status_code: int
    """The call response status_code, 200 indicate create success.
    """
    code: str
    """The request failed, this is the error code.
    """
    message: str
    """The request failed, this is the error message.
    """
    id: str
    """A unique identifier for the chat completion.
    """
    choices: List[Choice]
    """A list of chat completion choices.

    Can be more than one if `n` is greater than 1.
    """

    created: int
    """The Unix timestamp (in seconds) of when the chat completion was created."""  # noqa: E501

    model: str
    """The model used for the chat completion."""

    object: Literal["chat.completion"]
    """The object type, which is always `chat.completion`."""

    system_fingerprint: Optional[str] = None
    """This fingerprint represents the backend configuration that the model runs with.  # noqa: E501

    Can be used in conjunction with the `seed` request parameter to understand when
    backend changes have been made that might impact determinism.
    """

    usage: Optional[CompletionUsage] = None
    """Usage statistics for the completion request."""

    def __init__(self, **kwargs):
        if (
            "usage" in kwargs
            and kwargs["usage"] is not None
            and kwargs["usage"]
        ):
            self.usage = CompletionUsage(**kwargs.pop("usage", {}))
        else:
            self.usage = None

        if (
            "choices" in kwargs
            and kwargs["choices"] is not None
            and kwargs["choices"]
        ):
            choices = []
            for choice in kwargs.pop("choices", []):
                choices.append(Choice(**choice))
            self.choices = choices
        else:
            self.choices = None
        super().__init__(**kwargs)


@dataclass(init=False)
class ChatCompletionChunk(BaseObjectMixin):
    status_code: int
    """The call response status_code, 200 indicate create success.
    """
    code: str
    """The request failed, this is the error code.
    """
    message: str
    """The request failed, this is the error message.
    """
    id: str
    """A unique identifier for the chat completion. Each chunk has the same ID."""  # noqa: E501

    choices: List[Choice]
    """A list of chat completion choices.

    Can contain more than one elements if `n` is greater than 1. Can also be empty  # noqa: E501
    for the last chunk if you set `stream_options: {"include_usage": true}`.
    """

    created: int
    """The Unix timestamp (in seconds) of when the chat completion was created.

    Each chunk has the same timestamp.
    """

    model: str
    """The model to generate the completion."""

    object: Literal["chat.completion.chunk"]
    """The object type, which is always `chat.completion.chunk`."""

    system_fingerprint: Optional[str] = None
    """
    This fingerprint represents the backend configuration that the model runs with.  # noqa: E501
    Can be used in conjunction with the `seed` request parameter to understand when  # noqa: E501
    backend changes have been made that might impact determinism.
    """

    usage: Optional[CompletionUsage] = None
    """
    An optional field that will only be present when you set
    `stream_options: {"include_usage": true}` in your request. When present, it
    contains a null value except for the last chunk which contains the token usage  # noqa: E501
    statistics for the entire request.
    """

    def __init__(self, **kwargs):
        if (
            "usage" in kwargs
            and kwargs["usage"] is not None
            and kwargs["usage"]
        ):
            self.usage = CompletionUsage(**kwargs.pop("usage", {}))
        else:
            self.usage = None

        if (
            "choices" in kwargs
            and kwargs["choices"] is not None
            and kwargs["choices"]
        ):
            choices = []
            for choice in kwargs.pop("choices", []):
                choices.append(Choice(**choice))
            self.choices = choices
        else:
            self.choices = None
        super().__init__(**kwargs)
