"""
FusionHub - System integration and coordination
"""

import asyncio
from datetime import datetime
import logging

logger = logging.getLogger(__name__)


class FusionHub:
    """Central integration hub"""
    
    def __init__(self):
        self.connected_layers = {}
        self.message_queue = asyncio.Queue()
        self.is_running = False
        
    async def connect_layer(self, layer_name: str, layer_instance):
        self.connected_layers[layer_name] = {
            'instance': layer_instance,
            'connected_at': datetime.now(),
            'message_count': 0
        }
        logger.info(f"Layer connected: {layer_name}")
        
    async def send_message(self, from_layer: str, to_layer: str, message: dict):
        if to_layer not in self.connected_layers:
            logger.warning(f"Target layer not found: {to_layer}")
            return False
        
        message_data = {
            'from': from_layer,
            'to': to_layer,
            'timestamp': datetime.now().isoformat(),
            'data': message,
            'message_id': f"msg_{datetime.now().timestamp()}"
        }
        
        await self.message_queue.put(message_data)
        
        self.connected_layers[to_layer]['message_count'] += 1
        logger.debug(f"Message sent from {from_layer} to {to_layer}")
        
        return True
    
    async def start(self):
        self.is_running = True
        logger.info("FusionHub started")
        
        while self.is_running:
            try:
                # Process messages
                if not self.message_queue.empty():
                    message = await self.message_queue.get()
                    logger.debug(f"Processing message: {message['message_id']}")
                    self.message_queue.task_done()
                
                await asyncio.sleep(0.1)
                
            except Exception as e:
                logger.error(f"FusionHub error: {e}")
    
    async def stop(self):
        self.is_running = False
        logger.info("FusionHub stopped")
    
    def get_status(self) -> dict:
        return {
            'connected_layers': list(self.connected_layers.keys()),
            'queue_size': self.message_queue.qsize(),
            'is_running': self.is_running,
            'timestamp': datetime.now().isoformat()
        }
