"""Tests for Agent session management."""
import pytest

from logos_adk.agent import Agent
from logos_adk.providers import provider_registry
from logos_adk.providers.mock import MockProvider
from logos_adk.runtime import _default_runtime_holder


@pytest.fixture(autouse=True)
def _reset_runtime_and_registry():
    _default_runtime_holder.reset()
    provider_registry._entries.clear()
    yield
    _default_runtime_holder.reset()
    provider_registry._entries.clear()


@pytest.mark.asyncio
async def test_session_preserves_context():
    provider = MockProvider(responses=["Hi!", "Your name is Alex"])
    agent = Agent("bot").model(provider)

    await agent.run("My name is Alex", session_id="s1")
    await agent.run("What is my name?", session_id="s1")

    second_call_messages = provider.call_history[1]["messages"]
    contents = [message.content for message in second_call_messages]
    assert "My name is Alex" in contents
    assert "Hi!" in contents


@pytest.mark.asyncio
async def test_sessions_are_isolated():
    provider = MockProvider(responses=["I'm A", "I'm B", "dunno"])
    agent = Agent("bot").model(provider)

    await agent.run("I am session A", session_id="a")
    await agent.run("I am session B", session_id="b")
    await agent.run("Who am I?", session_id="a")

    third_call_messages = provider.call_history[2]["messages"]
    contents = [message.content for message in third_call_messages]
    assert "I am session A" in contents
    assert "I am session B" not in contents


@pytest.mark.asyncio
async def test_no_session_id_independent():
    provider = MockProvider(responses=["first", "second"])
    agent = Agent("bot").model(provider)

    await agent.run("msg 1")
    await agent.run("msg 2")

    second_messages = provider.call_history[1]["messages"]
    contents = [message.content for message in second_messages]
    assert "msg 1" in contents


@pytest.mark.asyncio
async def test_session_state_accessible():
    provider = MockProvider(responses=["ok"])
    agent = Agent("bot").model(provider)

    await agent.run("hello", session_id="s1")
    state = agent._get_state("s1")
    assert state.session_id == "s1"
    assert len(state.messages) == 2
