# Copyright 2026 Google LLC
#
# 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.

"""Tests for basic LLM request processor."""

from unittest import mock

from google.adk.agents.invocation_context import InvocationContext
from google.adk.agents.llm_agent import LlmAgent
from google.adk.agents.run_config import RunConfig
from google.adk.flows.llm_flows.basic import _BasicLlmRequestProcessor
from google.adk.models.llm_request import LlmRequest
from google.adk.sessions.in_memory_session_service import InMemorySessionService
from google.adk.tools.function_tool import FunctionTool
from google.genai import types
from pydantic import BaseModel
from pydantic import Field
import pytest


class OutputSchema(BaseModel):
  """Test schema for output."""

  name: str = Field(description='A name')
  value: int = Field(description='A value')


def dummy_tool(query: str) -> str:
  """A dummy tool for testing."""
  return f'Result: {query}'


async def _create_invocation_context(agent: LlmAgent) -> InvocationContext:
  """Helper to create InvocationContext for testing."""
  session_service = InMemorySessionService()
  session = await session_service.create_session(
      app_name='test_app', user_id='test_user'
  )
  return InvocationContext(
      invocation_id='test-id',
      agent=agent,
      session=session,
      session_service=session_service,
      run_config=RunConfig(),
  )


class TestBasicLlmRequestProcessor:
  """Test class for _BasicLlmRequestProcessor."""

  @pytest.mark.asyncio
  async def test_sets_output_schema_when_no_tools(self):
    """Test that processor sets output_schema when agent has no tools."""
    agent = LlmAgent(
        name='test_agent',
        model='gemini-2.5-flash',
        output_schema=OutputSchema,
        tools=[],  # No tools
    )

    invocation_context = await _create_invocation_context(agent)
    llm_request = LlmRequest()
    processor = _BasicLlmRequestProcessor()

    # Process the request
    events = []
    async for event in processor.run_async(invocation_context, llm_request):
      events.append(event)

    # Should have set response_schema since agent has no tools
    assert llm_request.config.response_schema == OutputSchema
    assert llm_request.config.response_mime_type == 'application/json'

  @pytest.mark.asyncio
  async def test_skips_output_schema_when_tools_present(self, mocker):
    """Test that processor skips output_schema when agent has tools."""
    agent = LlmAgent(
        name='test_agent',
        model='gemini-2.5-flash',
        output_schema=OutputSchema,
        tools=[FunctionTool(func=dummy_tool)],  # Has tools
    )

    invocation_context = await _create_invocation_context(agent)
    llm_request = LlmRequest()
    processor = _BasicLlmRequestProcessor()

    can_use_output_schema_with_tools = mocker.patch(
        'google.adk.flows.llm_flows.basic.can_use_output_schema_with_tools',
        mock.MagicMock(return_value=False),
    )

    # Process the request
    events = []
    async for event in processor.run_async(invocation_context, llm_request):
      events.append(event)

    # Should NOT have set response_schema since agent has tools
    assert llm_request.config.response_schema is None
    assert llm_request.config.response_mime_type != 'application/json'

    # Should have checked if output schema can be used with tools
    can_use_output_schema_with_tools.assert_called_once_with(
        agent.canonical_model
    )

  @pytest.mark.asyncio
  async def test_sets_output_schema_when_tools_present(self, mocker):
    """Test that processor skips output_schema when agent has tools."""
    agent = LlmAgent(
        name='test_agent',
        model='gemini-2.5-flash',
        output_schema=OutputSchema,
        tools=[FunctionTool(func=dummy_tool)],  # Has tools
    )

    invocation_context = await _create_invocation_context(agent)
    llm_request = LlmRequest()
    processor = _BasicLlmRequestProcessor()

    can_use_output_schema_with_tools = mocker.patch(
        'google.adk.flows.llm_flows.basic.can_use_output_schema_with_tools',
        mock.MagicMock(return_value=True),
    )

    # Process the request
    events = []
    async for event in processor.run_async(invocation_context, llm_request):
      events.append(event)

    # Should have set response_schema since output schema can be used with tools
    assert llm_request.config.response_schema == OutputSchema
    assert llm_request.config.response_mime_type == 'application/json'

    # Should have checked if output schema can be used with tools
    can_use_output_schema_with_tools.assert_called_once_with(
        agent.canonical_model
    )

  @pytest.mark.asyncio
  async def test_no_output_schema_no_tools(self):
    """Test that processor works normally when agent has no output_schema or tools."""
    agent = LlmAgent(
        name='test_agent',
        model='gemini-2.5-flash',
        # No output_schema, no tools
    )

    invocation_context = await _create_invocation_context(agent)
    llm_request = LlmRequest()
    processor = _BasicLlmRequestProcessor()

    # Process the request
    events = []
    async for event in processor.run_async(invocation_context, llm_request):
      events.append(event)

    # Should not have set anything
    assert llm_request.config.response_schema is None
    assert llm_request.config.response_mime_type != 'application/json'

  @pytest.mark.asyncio
  async def test_sets_model_name(self):
    """Test that processor sets the model name correctly."""
    agent = LlmAgent(
        name='test_agent',
        model='gemini-2.5-flash',
    )

    invocation_context = await _create_invocation_context(agent)
    llm_request = LlmRequest()
    processor = _BasicLlmRequestProcessor()

    # Process the request
    events = []
    async for event in processor.run_async(invocation_context, llm_request):
      events.append(event)

    # Should have set the model name
    assert llm_request.model == 'gemini-2.5-flash'

  @pytest.mark.asyncio
  async def test_skips_output_schema_for_task_mode(self):
    """Test that processor skips output_schema when agent is in task mode."""
    agent = LlmAgent(
        name='test_agent',
        model='gemini-2.5-flash',
        mode='task',
        output_schema=OutputSchema,
    )

    invocation_context = await _create_invocation_context(agent)
    llm_request = LlmRequest()
    processor = _BasicLlmRequestProcessor()

    async for _ in processor.run_async(invocation_context, llm_request):
      pass

    assert llm_request.config.response_schema is None

  @pytest.mark.asyncio
  async def test_disables_affective_dialog_and_proactivity_for_gemini_3_x_live(
      self,
  ):
    """Gemini 3.x Live does not support affective_dialog/proactivity."""
    agent = LlmAgent(
        name='test_agent',
        model='gemini-3.5-flash-lite-live-preview',
    )
    invocation_context = await _create_invocation_context(agent)
    invocation_context.run_config = RunConfig(
        enable_affective_dialog=True,
        proactivity=types.ProactivityConfig(),
    )
    llm_request = LlmRequest()
    processor = _BasicLlmRequestProcessor()

    async for _ in processor.run_async(invocation_context, llm_request):
      pass

    assert llm_request.live_connect_config.enable_affective_dialog is None
    assert llm_request.live_connect_config.proactivity is None

  @pytest.mark.asyncio
  async def test_keeps_affective_dialog_and_proactivity_for_non_gemini_3_x_live(
      self,
  ):
    """Non-3.x live models keep the configured affective_dialog/proactivity."""
    agent = LlmAgent(
        name='test_agent',
        model='gemini-2.5-flash-live',
    )
    invocation_context = await _create_invocation_context(agent)
    invocation_context.run_config = RunConfig(
        enable_affective_dialog=True,
        proactivity=types.ProactivityConfig(),
    )
    llm_request = LlmRequest()
    processor = _BasicLlmRequestProcessor()

    async for _ in processor.run_async(invocation_context, llm_request):
      pass

    assert llm_request.live_connect_config.enable_affective_dialog is True
    assert llm_request.live_connect_config.proactivity is not None

  @pytest.mark.asyncio
  async def test_sets_translation_config(self):
    """Translation config is forwarded to the live connect config."""
    agent = LlmAgent(
        name='test_agent',
        model='gemini-3.5-live-translate-preview',
    )
    invocation_context = await _create_invocation_context(agent)
    invocation_context.run_config = RunConfig(
        translation_config=types.TranslationConfig(
            target_language_code='pl',
            echo_target_language=True,
        ),
    )
    llm_request = LlmRequest()
    processor = _BasicLlmRequestProcessor()

    async for _ in processor.run_async(invocation_context, llm_request):
      pass

    translation_config = llm_request.live_connect_config.translation_config
    assert translation_config.target_language_code == 'pl'
    assert translation_config.echo_target_language is True

  @pytest.mark.asyncio
  async def test_translation_config_defaults_to_none(self):
    """Without a translation config the live connect field stays None."""
    agent = LlmAgent(
        name='test_agent',
        model='gemini-2.5-flash-live',
    )
    invocation_context = await _create_invocation_context(agent)
    llm_request = LlmRequest()
    processor = _BasicLlmRequestProcessor()

    async for _ in processor.run_async(invocation_context, llm_request):
      pass

    assert llm_request.live_connect_config.translation_config is None

  @pytest.mark.asyncio
  async def test_preserves_merged_http_options(self):
    """Test that processor preserves and merges existing http_options."""
    agent = LlmAgent(
        name='test_agent',
        model='gemini-1.5-flash',
        generate_content_config=types.GenerateContentConfig(
            http_options=types.HttpOptions(
                timeout=1000,
                headers={'Agent-Header': 'agent-val'},
            )
        ),
    )

    invocation_context = await _create_invocation_context(agent)
    llm_request = LlmRequest()

    # Simulate http_options propagated from RunConfig.
    llm_request.config.http_options = types.HttpOptions(
        timeout=500,  # Should override agent.
        headers={
            'RunConfig-Header': 'run-val',
            'Agent-Header': 'run-val-override',
        },
    )

    processor = _BasicLlmRequestProcessor()

    async for _ in processor.run_async(invocation_context, llm_request):
      pass

    # RunConfig timeout wins.
    assert llm_request.config.http_options.timeout == 500

    # Headers merged, RunConfig wins on conflict.
    assert (
        llm_request.config.http_options.headers['RunConfig-Header'] == 'run-val'
    )
    assert (
        llm_request.config.http_options.headers['Agent-Header']
        == 'run-val-override'
    )

  @pytest.mark.asyncio
  async def test_merges_http_options_without_headers(self):
    """RunConfig timeout/extra_body merge even when no headers are set."""
    agent = LlmAgent(
        name='test_agent',
        model='gemini-1.5-flash',
        generate_content_config=types.GenerateContentConfig(
            http_options=types.HttpOptions(
                timeout=1000,
                headers={'Agent-Header': 'agent-val'},
            )
        ),
    )

    invocation_context = await _create_invocation_context(agent)
    llm_request = LlmRequest()

    # Propagated RunConfig http_options with no headers.
    llm_request.config.http_options = types.HttpOptions(
        timeout=500,
        extra_body={'priority': 'high'},
    )

    processor = _BasicLlmRequestProcessor()

    async for _ in processor.run_async(invocation_context, llm_request):
      pass

    # timeout and extra_body still merge despite empty headers.
    assert llm_request.config.http_options.timeout == 500
    assert llm_request.config.http_options.extra_body == {'priority': 'high'}
    # Agent headers are untouched.
    assert (
        llm_request.config.http_options.headers['Agent-Header'] == 'agent-val'
    )
