#!/usr/bin/env python3
"""
Hierarchical Multi-Team Orchestration Main Entry Point

Example Use Case:
A company needs to launch a new product. The master orchestrator breaks this into:
- Team 1 (Market Research): Market analysis + competitor research
- Team 2 (Product Development): Technical specs + design

Setup:
1. Install: pip install synqed anthropic python-dotenv
2. Create .env file with: ANTHROPIC_API_KEY='your-key-here'
   Optionally add: ANTHROPIC_API_KEY_2 and ANTHROPIC_API_KEY_3 for better rate limiting
3. Run: python main.py (from within hierarchical_teams directory)
   Or: python -m hierarchical_teams.main (from parent directory)
"""

import asyncio
import sys
from datetime import datetime
from pathlib import Path

import synqed

from .config import Config
from .utils import cleanup_ports, OutputLogger
from .agents import (
    create_key_rotator,
    create_market_research_agents,
    create_product_dev_agents,
)
from .orchestration import execute_team_workspace, synthesize_team_results


async def main():
    """Main execution function."""
    # Clean up any processes from previous runs
    print("🧹 Cleaning up ports from previous runs...")
    cleanup_ports(Config.PORTS)
    await asyncio.sleep(1)
    print("✓ Ports cleaned up\n")
    
    # Check for API keys
    api_keys = Config.get_api_keys()
    
    if not api_keys:
        print("❌ Please set ANTHROPIC_API_KEY in your .env file")
        print("   Optionally, set ANTHROPIC_API_KEY_2 and ANTHROPIC_API_KEY_3 for better rate limit handling")
        return
    
    print(f"✓ Using {len(api_keys)} Anthropic API key(s) to distribute load\n")
    
    # Create a key rotator
    get_next_api_key = create_key_rotator(api_keys)

    # Set up output logging
    Config.OUTPUTS_DIR.mkdir(exist_ok=True)
    timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
    log_file = Config.OUTPUTS_DIR / f"hierarchical_teams_run_{timestamp}.txt"
    sys.stdout = OutputLogger(log_file)

    print("\n" + "=" * 80)
    print("  HIERARCHICAL MULTI-TEAM ORCHESTRATION")
    print("  Master Orchestrator → Multiple Specialized Team Workspaces")
    print("=" * 80 + "\n")
    
    print("🎯 ARCHITECTURE OVERVIEW")
    print("-" * 80)
    print("Master Orchestrator breaks down complex tasks into subtasks")
    print("Each subtask is assigned to a SEPARATE TEAM WORKSPACE")
    print("Teams have multiple agents that collaborate in their workspace")
    print("Results are synthesized back to the master orchestrator\n")
    
    print("HIERARCHY:")
    print("    Master Orchestrator")
    print("           |")
    print("    -------+-------")
    print("    |             |")
    print("  Team 1       Team 2")
    print("  [WS 1]       [WS 2]")
    print("    |             |")
    print("  Agents       Agents\n")
    print("=" * 80 + "\n")

    # ====================================================================
    # STEP 1: CREATE TEAM AGENTS
    # ====================================================================
    print("🏗️  Creating Team Agent Functions...\n")
    print("=" * 80)
    print("Creating 2 teams with specialized agents:")
    print("  • Team 1: Market Research (Market Analyst + Competitor Researcher)")
    print("  • Team 2: Product Development (Tech Lead + UX Designer)")
    print("=" * 80 + "\n")

    # Create agent functions for each team
    market_research_agents = await create_market_research_agents(get_next_api_key)
    product_dev_agents = await create_product_dev_agents(get_next_api_key)
    
    print("✓ All agent functions created\n")

    # ====================================================================
    # STEP 2: SETUP REAL-TIME MESSAGE DISPLAY
    # ====================================================================
    print("🎨 Setting up real-time message display...\n")
    
    # Create colored printer for real-time agent communication
    colored_printer = synqed.create_colored_printer()
    
    print("✓ Real-time display ready - you'll see agent conversations as they happen!\n")

    # ====================================================================
    # STEP 3: DEFINE THE MASTER TASK
    # ====================================================================
    print("=" * 80)
    print("📋 MASTER TASK: Product Launch Planning")
    print("=" * 80 + "\n")
    
    master_task = """
We need to launch a new AI-powered customer service chatbot platform called "ServiceBot AI".

Context:
- Target market: Small to medium-sized e-commerce businesses
- Key differentiator: Extremely easy setup (under 5 minutes)
- Pricing: $49-199/month based on usage
- Timeline: Launch in 6 months

Please create a comprehensive product launch plan. Break this down into 2 major areas:
1. Market Research & Competitive Analysis
2. Product Specifications & Design

Each area should be handled by a specialized team that collaborates internally.
    """
    
    print(f"Master Task:\n{master_task}\n")
    print("=" * 80 + "\n")

    # ====================================================================
    # STEP 4: DEFINE TEAM CONFIGURATIONS
    # ====================================================================
    print("🚀 Creating Hierarchical Team Workspaces...\n")
    
    # Define subtasks for each team
    subtasks = [
        {
            "team_name": "Market Research Team",
            "task": """Conduct comprehensive market research and competitive analysis for ServiceBot AI.

Context: AI-powered customer service chatbot for small to medium e-commerce businesses.
Key differentiator: Easy 5-minute setup. Pricing: $49-199/month.

Deliverables needed:
1. Market size, growth trends, and target customer segments
2. Competitive landscape and SWOT analysis
3. Differentiation opportunities and market positioning
4. Market entry strategy and timing recommendations

Team members should collaborate to provide comprehensive market intelligence.""",
            "agents": market_research_agents,
        },
        {
            "team_name": "Product Development Team",
            "task": """Define product specifications and design for ServiceBot AI.

Context: AI-powered customer service chatbot for small to medium e-commerce businesses.
Key differentiator: Easy 5-minute setup. Pricing: $49-199/month.

Deliverables needed:
1. Technical architecture and technology stack
2. Key features and technical specifications
3. User experience design and interface mockups
4. Development roadmap and milestones

Team members should collaborate to create comprehensive product specifications.""",
            "agents": product_dev_agents,
        },
    ]
    
    # ====================================================================
    # STEP 5: EXECUTE TEAM WORKSPACES IN PARALLEL
    # ====================================================================
    print("🎬 Executing Team Workspaces in Parallel...\n")
    
    print("=" * 80)
    print("Executing both team workspaces in parallel...")
    print("Each team will collaborate internally to produce their deliverables")
    print("=" * 80 + "\n")
    
    team_results = await asyncio.gather(*[
        execute_team_workspace(team_config, colored_printer)
        for team_config in subtasks
    ])
    
    # ====================================================================
    # STEP 6: MASTER ORCHESTRATOR SYNTHESIS
    # ====================================================================
    final_plan = await synthesize_team_results(team_results, master_task, api_keys[0])
    
    # ====================================================================
    # STEP 7: DISPLAY RESULTS
    # ====================================================================
    print("\n" + "=" * 80)
    print("📊 HIERARCHICAL EXECUTION RESULTS")
    print("=" * 80 + "\n")
    
    print("=" * 80)
    print("TEAM DELIVERABLES")
    print("=" * 80 + "\n")
    
    for team_result in team_results:
        print(f"\n{'=' * 80}")
        print(f"Team: {team_result['team_name']}")
        print(f"{'=' * 80}")
        stats = team_result['statistics']
        print(f"Rounds: {stats.total_rounds}")
        print(f"Messages: {stats.total_messages}")
        print(f"Agents: {stats.participating_agents}")
        print(f"\nDeliverable:\n")
        print(team_result['result'])
        print()
    
    print("\n" + "=" * 80)
    print("🎯 FINAL SYNTHESIZED PRODUCT LAUNCH PLAN")
    print("=" * 80 + "\n")
    print(final_plan)
    
    print("\n" + "=" * 80)
    print("✅ HIERARCHICAL ORCHESTRATION COMPLETE")
    print("=" * 80 + "\n")
    
    print("Summary:")
    print(f"  • {len(subtasks)} teams executed in parallel")
    print(f"  • {sum(len(t['agents']) for t in subtasks)} total agents collaborated")
    print(f"  • {sum(tr['statistics'].total_messages for tr in team_results)} total messages exchanged")
    print(f"  • {sum(tr['statistics'].total_rounds for tr in team_results)} total collaboration rounds")
    
    print("\n📊 Architecture Highlights:")
    print("  ✓ Master orchestrator decomposed complex task into subtasks")
    print("  ✓ Each subtask assigned to a dedicated team workspace")
    print("  ✓ Teams collaborated internally using consensus protocol")
    print("  ✓ Results synthesized into cohesive final output")
    
    print("\n" + "=" * 80)
    print("📄 Full execution log saved to:")
    print(f"   {log_file}")
    print("=" * 80 + "\n")
    
    # Restore stdout
    if isinstance(sys.stdout, OutputLogger):
        sys.stdout.close()
        sys.stdout = sys.stdout.terminal


if __name__ == "__main__":
    asyncio.run(main())

