"""Round-robin orchestration pattern."""

from __future__ import annotations

from typing import Any

from agentbyte.agents.base import BaseAgent
from agentbyte.agents.types import AgentResponse
from agentbyte.messages import Message, UserMessage
from agentbyte.termination import BaseTermination
from .base import BaseOrchestrator
from .policies import AgentHistoryPolicy, FinalResultPolicy, HistoryContextPolicy


class RoundRobinOrchestrator(BaseOrchestrator):
    """
    Round-robin orchestration pattern.

    Cycles through agents in fixed order, giving each agent access to
    the complete shared conversation history.

    Use cases:
        - Collaborative tasks where all agents contribute equally
        - Iterative refinement (e.g., poet → critic → poet → critic)
        - Balanced participation from all agents
    """

    def __init__(
        self,
        agents: list[BaseAgent],
        termination: BaseTermination,
        max_iterations: int = 50,
        history_policy: HistoryContextPolicy | None = None,
        final_result_policy: FinalResultPolicy | None = None,
    ):
        super().__init__(
            agents,
            termination,
            max_iterations,
            history_policy=history_policy,
            final_result_policy=final_result_policy,
        )
        self.current_agent_index = 0

    async def select_next_agent(self) -> BaseAgent:
        """Select next agent in round-robin order."""
        agent = self.agents[self.current_agent_index]
        self.current_agent_index = (self.current_agent_index + 1) % len(self.agents)
        return agent

    async def prepare_context_for_agent(
        self, agent: BaseAgent
    ) -> UserMessage | list[Message]:
        """Build execution context from the configured history policy."""
        return self._build_agent_context_from_history(agent)

    async def update_shared_state(self, result: AgentResponse) -> None:
        """Add new messages to the shared conversation."""
        if self._last_context_was_text:
            new_messages = result.messages[1:] if len(result.messages) > 1 else []
        else:
            new_messages = result.messages[self._last_context_size :]
        self.shared_messages.extend(new_messages)

    def _get_pattern_metadata(self) -> dict[str, Any]:
        """Get round-robin specific metadata."""
        base_metadata = super()._get_pattern_metadata()
        base_metadata.update(
            {
                "cycles_completed": self.iteration_count // len(self.agents),
                "current_agent_index": self.current_agent_index,
                "agents_order": [agent.name for agent in self.agents],
            }
        )
        return base_metadata

    def _reset_for_run(self) -> None:
        """Reset round-robin state for a new run."""
        super()._reset_for_run()
        self.current_agent_index = 0

    def _default_history_policy(self) -> HistoryContextPolicy:
        """Use full conversation text by default for round-robin agents."""
        return HistoryContextPolicy(
            default=AgentHistoryPolicy(window="full", format="text")
        )
