"""Tests for the stateless Agent executor."""

from __future__ import annotations

from src.agent import format_scratchpad_summary, run_agent
from src.models import AgentConfig


class MockLLMClient:
    """Mock LLM client that returns a canned response."""

    def __init__(self, response: str) -> None:
        self.response = response
        self.last_system: str = ""
        self.last_messages: list[dict[str, str]] = []

    def chat(self, system: str, messages: list[dict[str, str]]) -> str:
        self.last_system = system
        self.last_messages = messages
        return self.response


class TestRunAgent:
    """Tests for run_agent function."""

    def test_run_agent_returns_llm_response(self) -> None:
        config = AgentConfig(name="architect", role="Software Architect", system_prompt="You are an architect.")
        mock_client = MockLLMClient(response="Use microservices.")
        result = run_agent(config=config, prompt="What architecture should we use?", scratchpad_summary="Topic: database migration", client=mock_client)
        assert result == "Use microservices."

    def test_run_agent_uses_config_system_prompt(self) -> None:
        config = AgentConfig(name="devops", role="DevOps Engineer", system_prompt="You focus on deployment.")
        mock_client = MockLLMClient(response="OK")
        run_agent(config=config, prompt="How to deploy?", scratchpad_summary="Topic: deployment", client=mock_client)
        assert "You focus on deployment." in mock_client.last_system

    def test_run_agent_includes_scratchpad_in_message(self) -> None:
        config = AgentConfig(name="test", role="Tester", system_prompt="You test things.")
        mock_client = MockLLMClient(response="Noted.")
        run_agent(config=config, prompt="Review this?", scratchpad_summary="Previous: architect said use microservices.", client=mock_client)
        user_message = mock_client.last_messages[0]["content"]
        assert "Previous: architect said use microservices." in user_message
        assert "Review this?" in user_message


class TestFormatScratchpadSummary:
    """Tests for format_scratchpad_summary helper."""

    def test_empty_scratchpad(self) -> None:
        result = format_scratchpad_summary([])
        assert result == "No discussion yet."

    def test_scratchpad_with_entries(self) -> None:
        from datetime import datetime
        from src.models import ScratchpadEntry
        entries = [
            ScratchpadEntry(agent_name="architect", content="Use microservices.", timestamp=datetime(2026, 3, 30, 10, 0, 0)),
            ScratchpadEntry(agent_name="devops", content="That increases complexity.", timestamp=datetime(2026, 3, 30, 10, 1, 0)),
        ]
        result = format_scratchpad_summary(entries)
        assert "[architect]" in result
        assert "Use microservices." in result
        assert "[devops]" in result
        assert "That increases complexity." in result
