"""Master orchestrator synthesis logic."""

import anthropic
from ..config import Config


async def synthesize_team_results(team_results, master_task, api_key):
    """Synthesize team results into a comprehensive plan.
    
    Args:
        team_results: List of team result dicts
        master_task: Original master task description
        api_key: API key for the orchestrator
        
    Returns:
        Synthesized final plan as a string
    """
    print("\n" + "=" * 80)
    print("🎯 MASTER ORCHESTRATOR: Synthesizing Team Results")
    print("=" * 80 + "\n")
    
    print("All teams have completed their work. Now synthesizing results...\n")
    
    # Collect all team outputs
    synthesis_prompt = f"""You are the Master Orchestrator for the ServiceBot AI product launch.

All specialized teams have completed their work. Your job is to synthesize their outputs into a comprehensive, cohesive product launch plan.

ORIGINAL MISSION:
{master_task}

TEAM OUTPUTS:

"""
    
    for i, team_result in enumerate(team_results, 1):
        synthesis_prompt += f"""
{'=' * 80}
TEAM {i}: {team_result['team_name']}
{'=' * 80}

{team_result['result']}

"""
    
    synthesis_prompt += """

YOUR TASK:
Synthesize all team outputs into a comprehensive, executive-ready product launch plan.

Structure your synthesis as follows:
1. EXECUTIVE SUMMARY
2. MARKET OPPORTUNITY (from Market Research Team)
3. PRODUCT SPECIFICATIONS (from Product Development Team)
4. MARKETING STRATEGY (from Marketing Team)
5. OPERATIONAL READINESS (from Operations Team)
6. INTEGRATED TIMELINE & MILESTONES
7. RISKS & MITIGATION STRATEGIES
8. SUCCESS METRICS & KPIs

Ensure the plan is cohesive, actionable, and ready for executive presentation.
Highlight any conflicts or gaps between team outputs and provide recommendations."""
    
    print("🤖 Master Orchestrator is synthesizing all team outputs...\n")
    
    orchestrator_client = anthropic.Anthropic(api_key=api_key)
    
    synthesis_response = orchestrator_client.messages.create(
        model=Config.MODEL,
        max_tokens=Config.SYNTHESIS_MAX_TOKENS,
        temperature=Config.SYNTHESIS_TEMPERATURE,
        system="You are a Master Orchestrator specializing in synthesizing multi-team outputs into cohesive strategic plans.",
        messages=[
            {
                "role": "user",
                "content": synthesis_prompt
            }
        ]
    )
    
    return synthesis_response.content[0].text

