"""Team workspace execution logic."""

import synqed
from ..config import Config


def create_team_message_handler(team_name, colored_printer):
    """Create a message handler for a specific team.
    
    Args:
        team_name: Name of the team
        colored_printer: Colored printer instance for formatting messages
        
    Returns:
        Message handler function
    """
    def handler(message):
        """Handle messages from team agents."""
        # The message is a StructuredMessage object
        # Add team prefix and use colored printer
        print(f"\n[{team_name}] ", end="")
        # Use the colored printer with the structured message
        colored_printer.print_message(message)
    return handler


async def execute_team_workspace(team_config, colored_printer):
    """Execute a single team workspace and return results.
    
    Args:
        team_config: Dict containing team configuration:
            - team_name: Name of the team
            - task: Task description for the team
            - agents: Dict mapping agent names to agent functions
        colored_printer: Colored printer instance for formatting messages
        
    Returns:
        Dict containing team results:
            - team_name: Name of the team
            - result: Final output from the team
            - statistics: Execution statistics
    """
    team_name = team_config["team_name"]
    task = team_config["task"]
    agents = team_config["agents"]
    
    print(f"▶️  Starting {team_name}...")
    print(f"   Team size: {len(agents)} agents")
    print(f"   Agents: {', '.join(agents.keys())}\n")
    
    # Convert agent functions to AgentInfo format for workspace
    agent_infos = []
    for agent_name, agent_func in agents.items():
        agent_info = synqed.AgentInfo(
            agent_id=agent_name.lower(),
            agent_name=agent_name,
            role=agent_name,
            executor=agent_func,
        )
        agent_infos.append(agent_info)
    
    # Create collaborative workspace for this team with real-time display
    workspace = synqed.create_workspace(
        name=team_name,
        protocol=synqed.ProtocolType.CONSENSUS,
        agents=agent_infos,
        task=task,
        max_rounds=Config.MAX_ROUNDS,
        convergence_threshold=Config.CONVERGENCE_THRESHOLD,
        display_messages=True,  # Enable real-time message display
        on_message=create_team_message_handler(team_name, colored_printer),
    )
    
    # Run the workspace
    print("\n" + "=" * 80)
    print(f"🔄 {team_name} is now collaborating in real-time...")
    print("=" * 80)
    result = await workspace.run()
    
    print("\n" + "=" * 80)
    print(f"✅ {team_name} completed!")
    print(f"   Status: {result.lifecycle_state.value}")
    print(f"   Rounds: {result.statistics.total_rounds}")
    print(f"   Messages: {result.statistics.total_messages}")
    print("=" * 80 + "\n")
    
    return {
        "team_name": team_name,
        "result": result.final_output,
        "statistics": result.statistics,
    }

