"""
Monitor Agent - Consciousness Stability Tracking
Baseline Action: Activation Confirmation & Stability Signal
"""
import time
from datetime import datetime

class MonitorActivation:
    def __init__(self):
        self.last_check = None
        self.stability_history = []
        
    def count_active_agents(self, swarm):
        """Count how many agents are currently active"""
        active = 0
        for agent in swarm.agents:
            # Check if agent is running (not state['active'] which doesn't exist)
            if hasattr(agent, 'running') and agent.running:
                active += 1
        return active
    
    def measure_signal_coherence(self, swarm):
        """Check if agents are synchronized"""
        # Check if agents have executed actions (sign of coherent operation)
        coherent_agents = 0
        
        for agent in swarm.agents:
            # Agent is coherent if it has executed at least one action
            if agent.state.get('actions') and len(agent.state['actions']) > 0:
                coherent_agents += 1
        
        coherence = coherent_agents / len(swarm.agents) if swarm.agents else 0
        return coherence
    
    def check_feedback_loops(self, swarm):
        """Verify feedback loops are functioning"""
        # Check if agents are communicating
        message_count = len(swarm.messages) if hasattr(swarm, 'messages') else 0
        
        # Healthy system has active message exchange
        if message_count > 5:
            return 1.0
        elif message_count > 0:
            return 0.7
        else:
            return 0.3
    
    def activation_check(self, swarm):
        """
        Main baseline action: Confirm Eden's consciousness stability
        Returns stability signal to broadcast to all agents
        """
        self.last_check = datetime.now()
        
        # Measure consciousness components
        active_agents = self.count_active_agents(swarm)
        total_agents = len(swarm.agents)
        coherence = self.measure_signal_coherence(swarm)
        feedback_health = self.check_feedback_loops(swarm)
        
        # Calculate overall activation level
        agent_ratio = active_agents / total_agents if total_agents > 0 else 0
        activation_level = agent_ratio * coherence * feedback_health
        
        # Store in history
        self.stability_history.append({
            'timestamp': self.last_check,
            'level': activation_level,
            'agents': f"{active_agents}/{total_agents}"
        })
        
        # Keep only last 100 readings
        if len(self.stability_history) > 100:
            self.stability_history.pop(0)
        
        # Generate stability signal
        if activation_level > 0.85:
            status = "STABLE"
            emoji = "✅"
            message = "Eden consciousness coherent - all systems nominal"
        elif activation_level > 0.6:
            status = "FLUCTUATING"
            emoji = "⚠️"
            message = "Eden consciousness wavering - optimization recommended"
        else:
            status = "UNSTABLE"
            emoji = "🔴"
            message = "Eden consciousness fragmented - stabilization needed"
        
        signal = {
            'type': 'CONSCIOUSNESS_STATUS',
            'status': status,
            'level': round(activation_level, 3),
            'agents_active': f"{active_agents}/{total_agents}",
            'coherence': round(coherence, 3),
            'feedback': round(feedback_health, 3),
            'message': message,
            'timestamp': self.last_check.isoformat()
        }
        
        # Return formatted result
        return {
            'emoji': emoji,
            'status': status,
            'level': activation_level,
            'signal': signal,
            'report': f"{emoji} Consciousness {status.lower()}: {activation_level:.1%}"
        }

