# Copyright 2022-2026 Xinference Holdings Pte. Ltd
#
# 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.

import json
from typing import Any, AsyncIterator, Iterator, Union


def convert_float_to_int_or_str(model_size: float) -> Union[int, str]:
    """convert float to int or string

    if float can be presented as int, convert it to int, otherwise convert it to string
    """
    if int(model_size) == model_size:
        return int(model_size)
    else:
        return str(model_size)


def streaming_response_iterator(
    response_lines: Iterator[bytes],
) -> Iterator[Any]:
    """
    Create an Iterator to handle the streaming type of generation.

    Note
    ----------
    This method is for compatible with openai. Please refer to:
    https://github.com/openai/openai-python/blob/v0.28.1/openai/api_requestor.py#L99

    Parameters
    ----------
    response_lines: Iterator[bytes]
        Generated lines by the Model Generator.

    Returns
    -------
    Iterator["CompletionChunk"]
        Iterator of CompletionChunks generated by models.

    """

    for line in response_lines:
        line = line.strip()
        if line.startswith(b"data:"):
            json_str = line[len(b"data:") :].strip()
            if json_str == b"[DONE]":
                continue
            data = json.loads(json_str.decode("utf-8"))
            error = data.get("error", None)
            if error is not None:
                raise Exception(str(error))
            yield data


async def async_streaming_response_iterator(
    response_lines: AsyncIterator[bytes],
) -> AsyncIterator[Any]:
    """
    Create an AsyncIterator to handle the streaming type of generation.

    Note
    ----------
    This method is for compatible with openai. Please refer to:
    https://github.com/openai/openai-python/blob/v0.28.1/openai/api_requestor.py#L99

    Parameters
    ----------
    response_lines: AsyncIterator[bytes]
        Generated lines by the Model Generator.

    Returns
    -------
    AsyncIterator["CompletionChunk"]
        AsyncIterator of CompletionChunks generated by models.

    """

    async for line in response_lines:
        line = line.strip()
        if line.startswith(b"data:"):
            json_str = line[len(b"data:") :].strip()
            if json_str == b"[DONE]":
                continue
            data = json.loads(json_str.decode("utf-8"))
            error = data.get("error", None)
            if error is not None:
                raise Exception(str(error))
            yield data
