"""Configuration 2: Unorchestrated round-robin.

Three agents take fixed turns with no scoring or gating.
Simulates naive multi-agent without orchestration intelligence --
comparable to McEntire's swarm condition (68% failure).
"""

from __future__ import annotations

import time

from cohort.benchmark.code_runner import extract_code
from cohort.benchmark.config import StrategyResult
from cohort.benchmark.strategies.base import Strategy

AGENTS = [
    {
        "id": "algorithm_designer",
        "system": (
            "You are an algorithm designer on a competitive programming team. "
            "Your job is to analyze the problem and propose an efficient algorithm approach. "
            "Explain the approach clearly so your teammates can implement it. "
            "If implementation code already exists, review it and suggest improvements."
        ),
    },
    {
        "id": "implementer",
        "system": (
            "You are a Python implementer on a competitive programming team. "
            "Your job is to write clean, correct Python code "
            "that reads from stdin and writes to stdout. "
            "Follow the algorithm approach proposed by your teammates. "
            "Always output a complete ```python ... ``` code block."
        ),
    },
    {
        "id": "debugger",
        "system": (
            "You are a debugger/tester on a competitive programming team. "
            "Your job is to review the current solution, trace through edge cases, "
            "and identify bugs. If you find issues, explain them clearly. "
            "If the code looks correct, say so and suggest optimizations."
        ),
    },
]

NUM_ROUNDS = 3  # 3 rounds * 3 agents = 9 turns


class RoundRobin(Strategy):
    """Round-robin: fixed rotation, no scoring, no gating."""

    NAME = "round_robin"

    def run(self) -> StrategyResult:
        t0 = time.time()
        failures: list[str] = []
        conversation: list[str] = []

        # Initial problem posting
        problem_text = self.task.to_prompt()
        conversation.append(f"[user]: {problem_text}")

        # Fixed rotation for NUM_ROUNDS rounds
        has_code = False
        for round_num in range(NUM_ROUNDS):
            for agent in AGENTS:
                # Build context: full conversation history
                history = "\n\n".join(conversation[-10:])  # last 10 messages
                user_msg = (
                    f"## Problem\n{problem_text}\n\n"
                    f"## Conversation So Far\n{history}\n\n"
                    f"Your turn. Contribute to solving this problem. "
                    f"Round {round_num + 1}/{NUM_ROUNDS}."
                )

                response = self._call_llm(
                    agent_id=agent["id"],
                    system=agent["system"],
                    user=user_msg,
                )
                conversation.append(f"[{agent['id']}]: {response}")

                # Check for code production
                if extract_code(response):
                    has_code = True

        # Detect failure modes
        if not has_code:
            failures.append("planning_paralysis")

        # Check for loops: consecutive messages with high keyword overlap
        loop_count = self._detect_loops(conversation)
        if loop_count > 0:
            failures.append(f"loops:{loop_count}")

        elapsed = time.time() - t0
        code = self._extract_latest_code()
        return self._build_result(code, elapsed, failures)

    def _detect_loops(self, conversation: list[str]) -> int:
        """Count conversational loops (high keyword overlap between turns)."""
        from cohort.meeting import extract_keywords

        loops = 0
        prev_keywords: set[str] = set()
        for msg in conversation:
            keywords = set(extract_keywords(msg))
            if prev_keywords and keywords:
                overlap = len(keywords & prev_keywords) / max(len(keywords), 1)
                if overlap > 0.8:
                    loops += 1
            prev_keywords = keywords
        return loops
