use crate::event::{Event, EventHandler, EventType, EventError};
use std::collections::HashMap;
use std::sync::Arc;
use tokio::sync::RwLock;
use tracing::{debug, error, info};

/// Central event bus implementing pub/sub pattern
pub struct EventBus {
    /// Handlers registered for specific event types
    handlers: Arc<RwLock<HashMap<EventType, Vec<Arc<dyn EventHandler>>>>>,
    
    /// Global handlers that receive all events
    global_handlers: Arc<RwLock<Vec<Arc<dyn EventHandler>>>>,
    
    /// Event history for replay/debugging
    event_history: Arc<RwLock<Vec<Event>>>,
    
    /// Maximum history size
    max_history_size: usize,
}

impl EventBus {
    pub fn new(max_history_size: usize) -> Self {
        Self {
            handlers: Arc::new(RwLock::new(HashMap::new())),
            global_handlers: Arc::new(RwLock::new(Vec::new())),
            event_history: Arc::new(RwLock::new(Vec::new())),
            max_history_size,
        }
    }
    
    /// Register a handler for specific event types
    pub async fn subscribe(&self, handler: Arc<dyn EventHandler>) {
        let event_types = handler.interested_events();
        let mut handlers = self.handlers.write().await;
        
        for event_type in event_types {
            handlers
                .entry(event_type.clone())
                .or_insert_with(Vec::new)
                .push(handler.clone());
            
            debug!("Registered handler for event type: {:?}", event_type);
        }
    }
    
    /// Register a global handler that receives all events
    pub async fn subscribe_global(&self, handler: Arc<dyn EventHandler>) {
        let mut global_handlers = self.global_handlers.write().await;
        global_handlers.push(handler);
        debug!("Registered global event handler");
    }
    
    /// Publish an event to all interested handlers
    pub async fn publish(&self, event: Event) -> Result<Vec<Event>, EventError> {
        // Store in history
        {
            let mut history = self.event_history.write().await;
            history.push(event.clone());
            
            // Trim history if needed
            if history.len() > self.max_history_size {
                history.remove(0);
            }
        }
        
        info!("Publishing event: {:?} from {}", event.event_type, event.source);
        
        let mut new_events = Vec::new();
        
        // Call global handlers first
        {
            let global_handlers = self.global_handlers.read().await;
            for handler in global_handlers.iter() {
                match handler.handle(&event).await {
                    Ok(mut events) => new_events.append(&mut events),
                    Err(e) => {
                        error!("Global handler error: {}", e);
                    }
                }
            }
        }
        
        // Call specific handlers for this event type
        {
            let handlers = self.handlers.read().await;
            if let Some(type_handlers) = handlers.get(&event.event_type) {
                for handler in type_handlers.iter() {
                    match handler.handle(&event).await {
                        Ok(mut events) => new_events.append(&mut events),
                        Err(e) => {
                            error!("Handler error for {:?}: {}", event.event_type, e);
                        }
                    }
                }
            }
        }
        
        // Also check for Custom event type handlers if this is a custom event
        if let EventType::Custom(ref custom_type) = event.event_type {
            let handlers = self.handlers.read().await;
            if let Some(type_handlers) = handlers.get(&EventType::Custom(custom_type.clone())) {
                for handler in type_handlers.iter() {
                    match handler.handle(&event).await {
                        Ok(mut events) => new_events.append(&mut events),
                        Err(e) => {
                            error!("Custom handler error: {}", e);
                        }
                    }
                }
            }
        }
        
        Ok(new_events)
    }
    
    /// Get event history (for replay/debugging)
    pub async fn get_history(&self, limit: Option<usize>) -> Vec<Event> {
        let history = self.event_history.read().await;
        let limit = limit.unwrap_or(history.len());
        history.iter().rev().take(limit).cloned().collect()
    }
    
    /// Clear event history
    pub async fn clear_history(&self) {
        let mut history = self.event_history.write().await;
        history.clear();
    }
    
    /// Get count of registered handlers
    pub async fn handler_count(&self) -> usize {
        let handlers = self.handlers.read().await;
        handlers.values().map(|v| v.len()).sum::<usize>() + 
        self.global_handlers.read().await.len()
    }
}

impl Default for EventBus {
    fn default() -> Self {
        Self::new(10000)
    }
}

