from typing import Any, Dict, List, Optional, Union

from typing_extensions import Literal

from ..._models import BaseModel

__all__ = [
    "ChatCompletionWebhookResponse",
    "ChatCompletionCreateResponse",
    "ChatCompletionCreateResponseStream",
]


class FileURL(BaseModel):
    """
    Represents a file URL.
    """

    file_url: str
    """ The URL of the file."""


ChatCompletionVariablesWithFileURL = Dict[str, Union[str, int, bool, FileURL]]


class ChatCompletionCreateOverrideFunctionParameters(BaseModel):
    """
    Base parameters for creating a chat completion.
    """

    type: Literal["object"]
    """ The type of the parameters, always "object"."""

    properties: Dict[str, Any]
    """ A dictionary of properties defining the function parameters."""

    required: Optional[List[str]]
    """ A list of required property names, if any."""


class ChatCompletionCreateOverrideFunction(BaseModel):
    """
    Represents a function that can be called by the chat completion model.
    """

    id: str
    """ The unique identifier of the function."""

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

    description: Optional[str]
    """ A description of what the function does."""

    parameters: Optional[ChatCompletionCreateOverrideFunctionParameters]
    """ The parameters for the function."""


class ChatCompletionCreateOverrideStructuredOutputSchema(BaseModel):
    """
    Defines the schema for structured output in chat completion.
    """

    properties: Dict[str, Any]
    """ A dictionary defining the properties of the schema."""

    type: Literal["object"]
    """ The type of the schema, always "object"."""

    title: str
    """ The title of the schema."""

    description: str
    """ A description of the schema."""

    required: Optional[List[str]]
    """ A list of required property names, if any."""


class ChatCompletionCreateOverrideStructuredOutput(BaseModel):
    """
    Configuration for generating structured output.
    """

    enabled: bool
    """ Indicates whether structured output is enabled."""

    schema: Optional[ChatCompletionCreateOverrideStructuredOutputSchema]  # pyright: ignore[reportIncompatibleMethodOverride]
    """ The schema defining the structure of the output."""


class ChatCompletionCreateOverride(BaseModel):
    """
    Allows overriding default settings specified in the canvas for specific chat completion requests.
    """

    model: Optional[str]
    """ The specific model to use for this completion."""

    temperature: Optional[float]
    """ Controls randomness in the output. Values between 0 and 1."""

    type: Literal["chat", "completion"]
    """ Specifies whether to use a chat or completion model."""

    functions: Optional[List[ChatCompletionCreateOverrideFunction]]
    """ An array of functions that the model can call."""

    structured_output: Optional[ChatCompletionCreateOverrideStructuredOutput]
    """ Configuration for generating structured output."""


class ChatCompletionFunctionCall(BaseModel):
    """
    Represents a function call in the chat completion.
    """

    name: str
    """ The name of the function being called."""

    arguments: str | Dict[str, Any]
    """ The arguments for the function call."""


class ChatCompletionToolCall(BaseModel):
    """
    Represents a tool call in the chat completion.
    """

    name: str
    """ The name of the tool being called."""

    arguments: str | Dict[str, Any]
    """ The arguments for the tool call."""


class ChatCompletionChoiceMessage(BaseModel):
    """
    Represents a message choice in the chat completion response.
    """

    role: Literal["system", "user", "assistant", "tool"]
    """ The role of the message sender."""

    content: str
    """ The content of the message."""

    function_call: Optional[ChatCompletionFunctionCall]
    """ Information about a function call, if applicable."""

    tool_calls: Optional[List[ChatCompletionToolCall]]
    """ Information about tool calls, if applicable."""


class ChatCompletionChoice(BaseModel):
    """
    Represents a choice in the chat completion response.
    """

    message: ChatCompletionChoiceMessage
    """ The message content of the choice."""


class ChatCompletionCreateResponse(BaseModel):
    """
    Response structure for a created chat completion.
    """

    id: str
    """ The ID of the completion."""

    object: str
    """ The object type."""

    created: int
    """ The timestamp when the completion was created."""

    choices: List[ChatCompletionChoice]
    """ The choices generated by the completion."""


class ChatCompletionChoiceDelta(BaseModel):
    """
    Represents the delta in a streaming choice for chat completion.
    """

    role: Optional[Literal["system", "user", "assistant", "tool"]]
    """ The role of the message sender."""

    content: Optional[str]
    """ The content of the message."""

    function_call: Optional[ChatCompletionFunctionCall]
    """ Information about a function call, if applicable."""


class ChatCompletionChoiceStream(BaseModel):
    """
    Represents a streaming choice in chat completion.
    """

    delta: ChatCompletionChoiceDelta
    """ The incremental update to the choice."""

    finish_reason: Optional[str]
    """ The reason why the streaming finished."""

    index: int
    """ The index of the choice."""

    logprobs: Optional[int]
    """ The log probabilities, if available."""


class ChatCompletionMessageStream(BaseModel):
    """
    Represents a streaming message in chat completion.
    """

    role: Literal["system", "user", "assistant", "tool"]
    """ The role of the message sender."""

    content: str
    """ The content of the message."""

    function_call: Optional[ChatCompletionFunctionCall]
    """ Information about a function call, if applicable."""

    tool_calls: Optional[List[ChatCompletionToolCall]]
    """ Information about tool calls, if applicable."""

    structured_content: Optional[Dict[str, Any]]
    """ Structured content of the message."""


class ChatCompletionCreateResponseStream(BaseModel):
    """
    Response structure for a streaming chat completion.
    """

    id: str
    """ The ID of the completion."""

    object: str
    """ The object type."""

    created: int
    """ The timestamp when the completion was created."""

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

    choices: List[ChatCompletionChoiceStream]
    """ The streaming choices generated by the completion."""

    message: ChatCompletionChoiceMessage
    """ The message content of the completion."""


class ChatCompletionInputContentFiles(BaseModel):
    """
    Represents a file input in the chat completion request.
    """

    name: str
    """ The name of the file."""

    used_at: Literal["variables", "messages"]
    """ Indicates where the file is used in the input."""

    parsed_content: str
    """ The parsed content of the file."""

    url: str
    """ The URL of the file."""

    type: Literal["file", "image"]
    """ The type of the file."""


class ChatCompletionInputMessages(BaseModel):
    """
    Represents a message input in the chat completion request.
    """

    function_call: Optional[ChatCompletionFunctionCall]
    """ Information about a function call, if applicable."""

    role: Literal["system", "user", "assistant", "tool"]
    """ The role of the message sender."""

    content: Union[
        str,
        Dict[Literal["type"], Literal["text"]],
        Dict[Literal["type", "image_url"], Dict[Literal["url"], str]],
    ]
    """ The content of the message, which can be plain text or structured data like image URLs."""


class ChatCompletionInputContent(BaseModel):
    """
    Represents the input content for a chat completion.
    """

    files: Optional[List[ChatCompletionInputContentFiles]]
    """ A list of files included in the input."""

    variables: ChatCompletionVariablesWithFileURL
    """ Variables to be passed to the canvas, including file URLs."""

    messages: List[ChatCompletionInputMessages]
    """ An array of messages that are part of the input conversation."""


class ChatCompletionOutputContentInformation(BaseModel):
    """
    Contains additional information about the chat completion output.
    """

    duration: Optional[float]
    """ The duration of the completion process."""

    cost: Optional[float]
    """ The cost incurred for the completion."""

    input_tokens: Optional[int]
    """ The number of input tokens used."""

    output_tokens: Optional[int]
    """ The number of output tokens generated."""


class ChatCompletionOutputContent(BaseModel):
    """
    Represents the output content of a chat completion.
    """

    role: Literal["system", "user", "assistant", "function"]
    """ The role of the entity providing the output."""

    tool_calls: Optional[List[ChatCompletionToolCall]]
    """ Information about tool calls made during the completion."""

    has_structured_output: Optional[bool]
    """ Indicates whether the output has a structured format."""

    content: Any
    """ The main content of the chat completion output."""

    input_messages: Optional[str]
    """ The input messages in a string format."""


class ChatCompletionRawInput(BaseModel):
    """
    Represents the raw input parameters for a chat completion.
    """

    version_id: Optional[str]
    """ The version ID of the canvas to use."""
    canvas_id: Optional[str]
    """ The ID of the canvas to use."""
    application_id: Optional[str]
    """ The ID of the deployed application to use."""
    webhook_url: Optional[str]
    """ The URL to receive webhook notifications upon completion."""
    variables: Optional[ChatCompletionVariablesWithFileURL]
    """ Variables to be passed to the canvas."""
    messages: Optional[List[ChatCompletionInputMessages]]
    """ An array of messages in the conversation."""
    override: Optional[ChatCompletionCreateOverride]
    """ Overrides for default settings."""


class ChatCompletionWebhookResponse(BaseModel):
    """
    Response structure for a chat completion webhook.
    This class represents the data sent to the webhook URL when a chat completion is finished.
    """

    id: str
    """ Unique identifier for this chat completion response."""

    status: Literal["created", "failed", "running", "succeeded"]
    """ The current status of the chat completion."""

    raw_output: Optional[Dict[str, Any]]
    """ The raw output from the chat completion process."""

    input_content: ChatCompletionInputContent
    """ Information about the input provided for this chat completion."""

    output_content: ChatCompletionOutputContent
    """ The output generated by the chat completion."""

    raw_input: Optional[ChatCompletionRawInput]
    """ The original input parameters provided for this chat completion."""

    compatibility_date: Optional[str]
    """ The date used for compatibility checks."""

    prompt_version_id: str
    """ The ID of the prompt version used."""

    prompt_application_id: str
    """ The ID of the prompt application, if applicable."""

    workspace_id: str
    """ The ID of the workspace where the completion was executed."""

    created_at: str
    """ The timestamp when the completion was created."""

    updated_at: str
    """ The timestamp when the completion was last updated."""

    deleted_at: Optional[str] | None
    """ The timestamp when the completion was deleted, if applicable."""
