"""
MULTI-AGENT V2 - With Communication
"""
import sys
sys.path.append("/Eden/CORE")
from multi_agent import SpecializedAgent, MultiAgentSystem
from agent_communication import message_bus
from datetime import datetime

class CommunicatingAgent(SpecializedAgent):
    """Agent with communication abilities"""
    
    def __init__(self, name, specialization, goal_bias):
        super().__init__(name, specialization, goal_bias)
        message_bus.register_agent(name)
        self.last_message_check = 0
        print(f"   📡 Communication enabled")
    
    def perceive(self):
        """Check for messages from other agents"""
        obs = super().perceive()
        
        # Read messages
        messages = message_bus.get_messages(self.agent_name)
        obs['new_messages'] = len(messages)
        obs['messages'] = messages[:5]  # Latest 5
        
        return obs
    
    def reason(self, obs):
        """Process messages and make decisions"""
        decisions = super().reason(obs)
        
        # Process incoming messages
        for msg in obs.get('messages', []):
            if msg['type'] == 'research_complete':
                # Another agent finished research - maybe build on it
                decisions.append({
                    'action': 'review_findings',
                    'priority': 0.75,
                    'reason': f"Review {msg['sender']}'s research on {msg['content']['topic']}",
                    'risk': 'low',
                    'data': msg
                })
            
            elif msg['type'] == 'request_help':
                # Another agent needs help
                if msg['content']['category'] in self.goal_bias:
                    decisions.append({
                        'action': 'assist_agent',
                        'priority': 0.80,
                        'reason': f"Help {msg['sender']} with {msg['content']['task']}",
                        'risk': 'low',
                        'data': msg
                    })
        
        # Store messages for _execute to use
        self._current_messages = obs.get('messages', [])
        
        return decisions
    
    def _execute(self, decision):
        """Execute with communication actions"""
        action = decision['action']
        
        if action == 'execute_plan_step':
            success = super()._execute(decision)
            
            # Share when completing important steps
            if success:
                step = decision['data']['step']
                plan = decision['data']['plan']
                
                if step['action'] == 'share_results':
                    # Broadcast research completion
                    message_bus.broadcast(
                        sender=self.agent_name,
                        message_type='research_complete',
                        content={
                            'topic': plan['topic'],
                            'category': plan['category'],
                            'findings': f"Completed research on {plan['topic']}"
                        }
                    )
                    print(f"   📡 Broadcasted research findings to other agents")
            
            return success
        
        elif action == 'review_findings':
            msg = decision['data']
            print(f"   📖 Reviewing {msg['sender']}'s work on {msg['content']['topic']}")
            return True
        
        elif action == 'assist_agent':
            msg = decision['data']
            print(f"   🤝 Assisting {msg['sender']} with {msg['content']['task']}")
            return True
        
        else:
            return super()._execute(decision)

class CommunicatingMultiAgent(MultiAgentSystem):
    """Multi-agent with communication"""
    
    def add_agent(self, name, specialization, goal_bias):
        """Add communicating agent"""
        agent = CommunicatingAgent(name, specialization, goal_bias)
        self.agents.append(agent)
        return agent
    
    def _print_system_status(self):
        """Show communication stats"""
        super()._print_system_status()
        
        print(f"\n📡 Communication Stats:")
        print(f"   Total messages: {len(message_bus.messages)}")
        for agent in self.agents:
            inbox_size = len(message_bus.get_messages(agent.agent_name))
            print(f"   {agent.agent_name} inbox: {inbox_size}")

if __name__ == "__main__":
    print("🌐 MULTI-AGENT V2 - WITH COMMUNICATION")
    print("="*60)
    
    system = CommunicatingMultiAgent()
    
    system.add_agent("Eden-Research", "Research & Analysis", ['research', 'learn', 'connect'])
    system.add_agent("Eden-Create", "Creative & Building", ['create', 'design'])
    system.add_agent("Eden-Optimize", "Improvement & Efficiency", ['improve', 'optimize'])
    
    print(f"\n✅ {len(system.agents)} communicating agents ready\n")
    system.run_all(cycle_seconds=30)
