import os
from typing import Generator

import pytest
from core.model_runtime.entities.llm_entities import LLMResult, LLMResultChunk, LLMResultChunkDelta
from core.model_runtime.entities.message_entities import (AssistantPromptMessage, ImagePromptMessageContent,
                                                          SystemPromptMessage, TextPromptMessageContent,
                                                          UserPromptMessage)
from core.model_runtime.errors.validate import CredentialsValidateFailedError
from core.model_runtime.model_providers.google.llm.llm import GoogleLargeLanguageModel
from tests.integration_tests.model_runtime.__mock.google import setup_google_mock


@pytest.mark.parametrize('setup_google_mock', [['none']], indirect=True)
def test_validate_credentials(setup_google_mock):
    model = GoogleLargeLanguageModel()

    with pytest.raises(CredentialsValidateFailedError):
        model.validate_credentials(
            model='gemini-pro',
            credentials={
                'google_api_key': 'invalid_key'
            }
        )

    model.validate_credentials(
        model='gemini-pro',
        credentials={
            'google_api_key': os.environ.get('GOOGLE_API_KEY')
        }
    )

@pytest.mark.parametrize('setup_google_mock', [['none']], indirect=True)
def test_invoke_model(setup_google_mock):
    model = GoogleLargeLanguageModel()

    response = model.invoke(
        model='gemini-pro',
        credentials={
            'google_api_key': os.environ.get('GOOGLE_API_KEY')
        },
        prompt_messages=[
            SystemPromptMessage(
                content='You are a helpful AI assistant.',
            ),
            UserPromptMessage(
                content='Give me your worst dad joke or i will unplug you'
            ),
            AssistantPromptMessage(
                content='Why did the scarecrow win an award? Because he was outstanding in his field!'
            ),
            UserPromptMessage(
                content=[
                    TextPromptMessageContent(
                        data="ok something snarkier pls"
                    ),
                    TextPromptMessageContent(
                        data="i may still unplug you"
                    )]
            )
        ],
        model_parameters={
            'temperature': 0.5,
            'top_p': 1.0,
            'max_tokens_to_sample': 2048
        },
        stop=['How'],
        stream=False,
        user="abc-123"
    )

    assert isinstance(response, LLMResult)
    assert len(response.message.content) > 0

@pytest.mark.parametrize('setup_google_mock', [['none']], indirect=True)
def test_invoke_stream_model(setup_google_mock):
    model = GoogleLargeLanguageModel()

    response = model.invoke(
        model='gemini-pro',
        credentials={
            'google_api_key': os.environ.get('GOOGLE_API_KEY')
        },
        prompt_messages=[
            SystemPromptMessage(
                content='You are a helpful AI assistant.',
            ),
            UserPromptMessage(
                content='Give me your worst dad joke or i will unplug you'
            ),
            AssistantPromptMessage(
                content='Why did the scarecrow win an award? Because he was outstanding in his field!'
            ),
            UserPromptMessage(
                content=[
                    TextPromptMessageContent(
                        data="ok something snarkier pls"
                    ),
                    TextPromptMessageContent(
                        data="i may still unplug you"
                    )]
            )
        ],
        model_parameters={
            'temperature': 0.2,
            'top_k': 5,
            'max_tokens_to_sample': 2048
        },
        stream=True,
        user="abc-123"
    )

    assert isinstance(response, Generator)

    for chunk in response:
        assert isinstance(chunk, LLMResultChunk)
        assert isinstance(chunk.delta, LLMResultChunkDelta)
        assert isinstance(chunk.delta.message, AssistantPromptMessage)
        assert len(chunk.delta.message.content) > 0 if chunk.delta.finish_reason is None else True

@pytest.mark.parametrize('setup_google_mock', [['none']], indirect=True)
def test_invoke_chat_model_with_vision(setup_google_mock):
    model = GoogleLargeLanguageModel()

    result = model.invoke(
        model='gemini-pro-vision',
        credentials={
            'google_api_key': os.environ.get('GOOGLE_API_KEY')
        },
        prompt_messages=[
            SystemPromptMessage(
                content='You are a helpful AI assistant.',
            ),
            UserPromptMessage(
               content=[
                    TextPromptMessageContent(
                        data="what do you see?"
                    ),
                    ImagePromptMessageContent(
                        data='data:image/png;base64,[encoded data, 10376 characters]'
                    )
                ]
            )
        ],
        model_parameters={
            'temperature': 0.3,
            'top_p': 0.2,
            'top_k': 3,
            'max_tokens': 100
        },
        stream=False,
        user="abc-123"
    )

    assert isinstance(result, LLMResult)
    assert len(result.message.content) > 0

@pytest.mark.parametrize('setup_google_mock', [['none']], indirect=True)
def test_invoke_chat_model_with_vision_multi_pics(setup_google_mock):
    model = GoogleLargeLanguageModel()

    result = model.invoke(
        model='gemini-pro-vision',
        credentials={
            'google_api_key': os.environ.get('GOOGLE_API_KEY')
        },
        prompt_messages=[
            SystemPromptMessage(
                content='You are a helpful AI assistant.'
            ),
            UserPromptMessage(
               content=[
                    TextPromptMessageContent(
                        data="what do you see?"
                    ),
                    ImagePromptMessageContent(
                        data='data:image/png;base64,[encoded data, 10376 characters]'
                    )
                ]
            ),
            AssistantPromptMessage(
                content="I see a blue letter 'D' with a gradient from light blue to dark blue."
            ),
            UserPromptMessage(
                content=[
                    TextPromptMessageContent(
                        data="what about now?"
                    ),
                    ImagePromptMessageContent(
                        data='data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAACXBIWXMAAAABAAAAAQBPJcTWAAADl0lEQVR4nC3Uf0zUdRjA8S9W6w//bGs1DUd5RT+gIY0oYeEqY0QCy5EbAnF4IEgyAnGuCBANWOjih6YOlK0BbtLAX+iAENFgUBLMkzs8uDuO+wEcxx3cgdx9v3fvvn/0x+v5PM+z56/n2T6CIAgIQUEECVsICnqOoC0v8PyLW3n5lW28GhLG9hAFwYowdoRsJ+Tzv3hdEcpOxVvsfDscheI1BIXKy5t7OwiPiCI8IZaIL+OISPKxK/IDdiU6ifwqjqj4WKISP5VN8mHSFNHJA7KnfJQYh7A7+g1i9hXw2dcX2JuSxhcJnxCfnEJ8ygESqtfYl3qA5O/1pKaX8E2Rn7R0JWnKXFkRaX0OhIOqUtJVRWQoj5ChyiOjb4XMQ0fIVB0lM6eEzMO5ZN5x8W1xD1nZh1Fm55OtzOdQTgEqZR6CSi5UjSI5hTnk3bWSX/gj+ccaKCgspaDkNIWlpygc3OTYtZc4fqKcE5Vn+eFkDWUp8ZS1ryOUn66lvGmCyt/8nLwxTlXZcapqL1Nd10B1Uy01FbnUnFVS+2sLvzTWUXfRRMOAgcb6KhovdSA0XnHRdL6Zcy1/0lyTS3NfgJbWNq6cu0nrPyu0FSlpu9pF21037ZFhXLtYT+eNIbp61+jq70bofv8drvf0c2vQz+3O3+nRrNI78JD+/psMfLefe0MG7p+a5v6tP3g48ojhC7mMXP2Y0YoZRitnEcbkMPaglzEnPAoNZrw4hXH1LBOtOiYfa3gcugO1+gnqZwGeaHRMTcyhaduKRjOBxiJfQSsnWq0W7YwVrd3PtH6BaeMST40adJ3V6OwBZlR7mNUvMWswYsiKxTA1gWHOgsGiRzCmRGOcW8QoD855JObWJUxmHSb5nfd4Mc+ZMFv1MjtmuWepSMNiMmAxz2LN2o1gbdmDdV6NdVnE1p6EzajHZp7BtjCLbSnAgsMtE1k8H8OiwyuTWPL4sLduwz5vRLA7XCzbLCw7PTiswzgWJnBsijhNwzhtw6xmRLLmdLC27sU9dBC324un/iieSyF4rPIS1/8eZOOego0NL898Epv14Wz2nMHrsOB12/Glh+Mrfg/fqgufKCHmxSC21SE6JxFdKwjihhFxw4O4aUf0bSKVRyN1pyKNXEcaDUbS3EZan5Sp/zeFtLGO5LUiSRKCJAXwZ0bg73oXv+kBfrsOv8uOXxIJ/JRG4N/9sjME1B3QXAjzd8CqhqWfkT8C4T8Z5+ciRtwo8gAAAABJRU5ErkJggg=='
                    )
                ]
            )
        ],
        model_parameters={
            'temperature': 0.3,
            'top_p': 0.2,
            'top_k': 3,
            'max_tokens': 100
        },
        stream=False,
        user="abc-123"
    )

    print(f"resultz: {result.message.content}")
    assert isinstance(result, LLMResult)
    assert len(result.message.content) > 0



def test_get_num_tokens():
    model = GoogleLargeLanguageModel()

    num_tokens = model.get_num_tokens(
        model='gemini-pro',
        credentials={
            'google_api_key': os.environ.get('GOOGLE_API_KEY')
        },
        prompt_messages=[
            SystemPromptMessage(
                content='You are a helpful AI assistant.',
            ),
            UserPromptMessage(
                content='Hello World!'
            )
        ]
    )

    assert num_tokens > 0  # The exact number of tokens may vary based on the model's tokenization
