"""
Cross-Module Communication Bus
Modules broadcast and receive insights spontaneously
"""
import json
from pathlib import Path
from datetime import datetime
from typing import Dict, List, Callable
import threading
import time

class CommunicationBus:
    def __init__(self):
        self.subscribers = {}
        self.message_log = Path('/Eden/DATA/communication_bus.json')
        self.messages = []
        
    def publish(self, sender: str, message: str, data: Dict = None):
        """Publish message to bus"""
        msg = {
            'timestamp': datetime.now().isoformat(),
            'sender': sender,
            'message': message,
            'data': data or {}
        }
        
        self.messages.append(msg)
        self._log_message(msg)
        
        # Notify all subscribers
        for subscriber, callback in self.subscribers.items():
            try:
                callback(msg)
            except Exception as e:
                print(f"Error notifying {subscriber}: {e}")
        
        return msg
    
    def subscribe(self, subscriber: str, callback: Callable):
        """Subscribe to bus messages"""
        self.subscribers[subscriber] = callback
        print(f"📡 {subscriber} subscribed to communication bus")
    
    def get_recent_messages(self, count: int = 10) -> List[Dict]:
        """Get recent messages"""
        return self.messages[-count:]
    
    def _log_message(self, msg: Dict):
        """Log message to file"""
        logs = []
        if self.message_log.exists():
            with open(self.message_log) as f:
                logs = json.load(f)
        
        logs.append(msg)
        logs = logs[-1000:]  # Keep last 1000
        
        self.message_log.parent.mkdir(exist_ok=True)
        with open(self.message_log, 'w') as f:
            json.dump(logs, f, indent=2)

# Global bus instance
bus = CommunicationBus()
