"""End-to-end agent tests — requires OPENAI_API_KEY."""

from __future__ import annotations

from typing import TYPE_CHECKING

import pytest

from koan.agents import AgentConfig, ReactAgent
from koan.tools import ToolRegistry, tool

from .conftest import skip_no_openai

if TYPE_CHECKING:
    from koan.llm.client import LLMClient

pytestmark = [pytest.mark.integration, skip_no_openai]


@tool
def add_numbers(a: int, b: int) -> int:
    """Add two numbers together."""
    return a + b


@tool
def get_greeting(name: str) -> str:
    """Get a greeting for a person."""
    return f"Hello, {name}! Welcome aboard."


class TestReactAgentE2E:
    async def test_simple_agent_no_tools(self, llm_client: LLMClient) -> None:
        agent = ReactAgent(
            "simple",
            client=llm_client,
            config=AgentConfig(
                provider="openai",
                model="gpt-4o-mini",
                system_prompt="You are a helpful assistant. Be concise.",
            ),
        )

        result = await agent.run("What is 2 + 2?")

        assert "4" in result.output
        assert result.agent_name == "simple"
        assert result.iterations >= 1

    async def test_agent_with_tools(self, llm_client: LLMClient) -> None:
        registry = ToolRegistry()
        registry.add(add_numbers)

        agent = ReactAgent(
            "calculator",
            client=llm_client,
            config=AgentConfig(
                provider="openai",
                model="gpt-4o-mini",
                system_prompt="Use tools to answer math questions. Always use the add_numbers tool.",
            ),
            tools=registry,
        )

        result = await agent.run("What is 17 + 28?")

        assert result.agent_name == "calculator"
        # The agent may or may not use tools depending on how the LLM responds
        assert result.output  # Should have some output

    async def test_multi_turn_agent(self, llm_client: LLMClient) -> None:
        agent = ReactAgent(
            "conversational",
            client=llm_client,
            config=AgentConfig(
                provider="openai",
                model="gpt-4o-mini",
                system_prompt="Be concise. Answer in one sentence.",
            ),
        )

        result1 = await agent.run("My name is Alice.")
        assert result1.output

        result2 = await agent.run("What did I just tell you?")
        # Note: Each run() is independent (no thread memory by default)
        assert result2.output
