//! Unified Event System - Single Source of Truth for All Events
//!
//! This module provides the comprehensive event types that power the entire
//! Foxhunt event-driven trading system. ALL services use these canonical events
//! for real-time coordination, state management, and communication.
//!
//! # Architecture Principles
//! - **Single Source of Truth**: All events defined here, nowhere else
//! - **Event Sourcing**: All state changes captured as immutable events  
//! - **CQRS Integration**: Events flow between command and query sides
//! - **Real-time Processing**: Events enable sub-microsecond coordination
//! - **Audit Trail**: Complete trading activity history
//! - **Type Safety**: Strong typing prevents event misuse

#![deny(
    clippy::unwrap_used,
    clippy::expect_used,
    clippy::panic,
    clippy::unimplemented,
    clippy::unreachable
)]
//! # Core Event Types
//! - **MarketEvent**: Market data updates (quotes, trades, order book)
//! - **OrderEvent**: Order lifecycle events (placement, modification, cancellation)
//! - **FillEvent**: Trade execution and settlement events
//! - **SystemEvent**: Infrastructure events (heartbeats, progress, errors)
//! - **RiskEvent**: Risk management notifications and alerts
//! - **PositionEvent**: Portfolio position updates and reconciliation
//!
//! # Usage
//! ``rust
//! use types::events::*;
//! use types::prelude::*;
//!
//! // Create market data event
//! let market_event = Event::Market(MarketEvent::Quote {
//!     symbol: Symbol::new("BTCUSD".to_string()),
//!     bid_price: Price::from_f64(50000.0)?,
//!     bid_size: Quantity::from_f64(1.0)?,
//!     ask_price: Price::from_f64(50005.0)?,
//!     ask_size: Quantity::from_f64(1.0)?,
//!     timestamp: Utc::now(),
//!     venue: Some("Binance".to_string()),
//! });
//!
//! // Process events chronologically
//! let mut queue = EventQueue::new(Utc::now());
//! queue.push(market_event, Utc::now());
//! ``

use std::cmp::Ordering;
use std::collections::BinaryHeap;

use chrono::{DateTime, Utc};
// CANONICAL TYPE IMPORTS - Import directly from common types
use common::{OrderId, OrderSide, OrderType, Price, Quantity, Symbol};
use rust_decimal::Decimal;
use serde::{Deserialize, Serialize};

/// Main event enum that encompasses all types of events in the unified system
///
/// This is the canonical event type used throughout the Foxhunt trading system.
/// All services MUST use this enum - no duplicate event definitions allowed.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "type", content = "data")]
/// Main event type that encompasses all trading system events
///
/// This is the canonical event type used throughout the Foxhunt trading system
/// for event-driven architecture, state management, and real-time coordination.
pub enum Event {
    /// Market data events (quotes, trades, order book updates)
    Market(MarketEvent),
    /// Order-related events (submissions, modifications, cancellations)
    Order(OrderEvent),
    /// Fill/execution events for trade settlements
    Fill(FillEvent),
    /// System events (heartbeats, progress updates, errors)
    System(SystemEvent),
    /// Risk management events and alerts
    Risk(RiskEvent),
    /// Portfolio position updates
    Position(PositionEvent),
}

/// Market data events for all market information updates
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "market_event_type")]
/// Market data events for all market information updates
///
/// Represents various types of market data including quotes, trades, order books,
/// bars, sentiment analysis, and control messages from market data providers.
pub enum MarketEvent {
    /// Best bid/offer quote update
    Quote {
        /// Trading symbol for this quote
        symbol: Symbol,
        /// Current best bid price
        bid_price: Price,
        /// Size available at the best bid
        bid_size: Quantity,
        /// Current best ask/offer price
        ask_price: Price,
        /// Size available at the best ask
        ask_size: Quantity,
        /// Timestamp when quote was received
        timestamp: DateTime<Utc>,
        /// Exchange or venue identifier
        venue: Option<String>,
    },
    /// Trade execution on the market
    Trade {
        /// Trading symbol for this trade
        symbol: Symbol,
        /// Execution price of the trade
        price: Price,
        /// Quantity traded
        size: Quantity,
        /// Timestamp when trade occurred
        timestamp: DateTime<Utc>,
        /// Trade direction if known
        side: Option<OrderSide>,
        /// Exchange or venue identifier
        venue: Option<String>,
        /// Trade identifier
        trade_id: Option<String>,
    },
    /// Full order book snapshot
    OrderBook {
        /// Trading symbol for this order book
        symbol: Symbol,
        /// Bid price/quantity pairs, ordered by best first
        bids: Vec<(Price, Quantity)>,
        /// Ask price/quantity pairs, ordered by best first
        asks: Vec<(Price, Quantity)>,
        /// Timestamp when snapshot was taken
        timestamp: DateTime<Utc>,
        /// Venue identifier
        venue: Option<String>,
        /// Sequence number for ordering
        sequence: Option<u64>,
    },
    /// Order book update (incremental)
    OrderBookUpdate {
        /// Trading symbol for this order book update
        symbol: Symbol,
        /// Updated bid price/quantity pairs
        bids: Vec<(Price, Quantity)>,
        /// Updated ask price/quantity pairs
        asks: Vec<(Price, Quantity)>,
        /// Timestamp when update occurred
        timestamp: DateTime<Utc>,
        /// Venue identifier
        venue: Option<String>,
        /// Sequence number for ordering
        sequence: Option<u64>,
    },
    /// Market bar/candlestick data
    Bar {
        /// Trading symbol for this bar
        symbol: Symbol,
        /// Opening price for the bar period
        open: Price,
        /// Highest price during the bar period
        high: Price,
        /// Lowest price during the bar period
        low: Price,
        /// Closing price for the bar period
        close: Price,
        /// Total volume traded during the bar period
        volume: Quantity,
        /// Timestamp of the bar (typically the close time)
        timestamp: DateTime<Utc>,
        /// Bar interval (e.g., "1m", "5m", "1h")
        interval: String,
        /// Venue identifier
        venue: Option<String>,
    },
    /// Market sentiment event (from NLP analysis)
    Sentiment {
        /// Type of event (e.g., "`earnings_beat`", "`merger_announcement`")
        event_type: String,
        /// Human-readable description of the event
        description: String,
        /// Entities involved in the event (companies, tickers, etc.)
        entities: Vec<String>,
        /// Estimated market impact score [-1.0 to 1.0]
        impact_score: f32,
        /// Confidence in event detection [0.0, 1.0]
        confidence: f32,
        /// Timestamp of the event
        timestamp: DateTime<Utc>,
    },
    /// Control event for managing streams
    Control {
        /// Control command
        command: String,
        /// Optional parameters
        parameters: std::collections::HashMap<String, String>,
        /// Timestamp of the control event
        timestamp: DateTime<Utc>,
    },
}

impl MarketEvent {
    /// Get the symbol from the market event
    #[must_use]
    pub const fn symbol(&self) -> Option<&Symbol> {
        match self {
            Self::Quote { symbol, .. }
            | Self::Trade { symbol, .. }
            | Self::OrderBook { symbol, .. }
            | Self::OrderBookUpdate { symbol, .. }
            | Self::Bar { symbol, .. } => Some(symbol),
            Self::Sentiment { .. } | Self::Control { .. } => None,
        }
    }

    /// Get the timestamp from the market event
    #[must_use]
    pub const fn timestamp(&self) -> DateTime<Utc> {
        match self {
            Self::Quote { timestamp, .. }
            | Self::Trade { timestamp, .. }
            | Self::OrderBook { timestamp, .. }
            | Self::OrderBookUpdate { timestamp, .. }
            | Self::Bar { timestamp, .. }
            | Self::Sentiment { timestamp, .. }
            | Self::Control { timestamp, .. } => *timestamp,
        }
    }

    /// Get the venue/exchange from the market event
    #[must_use]
    pub fn exchange(&self) -> Option<&str> {
        self.venue()
    }

    /// Get the venue from the market event
    #[must_use]
    pub fn venue(&self) -> Option<&str> {
        match self {
            Self::Quote { venue, .. }
            | Self::Trade { venue, .. }
            | Self::OrderBook { venue, .. }
            | Self::OrderBookUpdate { venue, .. }
            | Self::Bar { venue, .. } => venue.as_deref(),
            Self::Sentiment { .. } | Self::Control { .. } => None,
        }
    }
}

/// Order events for the complete order lifecycle
#[derive(Debug, Clone, Serialize, Deserialize)]
/// Order lifecycle event
///
/// Represents all order-related events throughout the complete order lifecycle
/// including placement, modification, cancellation, rejection, and expiration.
pub struct OrderEvent {
    /// Unique identifier for the order
    pub order_id: OrderId,
    /// Trading symbol for the order
    pub symbol: Symbol,
    /// Type of order (market, limit, stop, etc.)
    pub order_type: OrderType,
    /// Order side (buy or sell)
    pub side: OrderSide,
    /// Order quantity
    pub quantity: Quantity,
    /// Order price (`None` for market orders)
    pub price: Option<Price>,
    /// Timestamp when the event occurred
    pub timestamp: DateTime<Utc>,
    /// Strategy or client identifier
    pub strategy_id: String,
    /// Order event type (placed, modified, cancelled)
    pub event_type: OrderEventType,
    /// Previous quantity for modifications
    pub previous_quantity: Option<Quantity>,
    /// Previous price for modifications
    pub previous_price: Option<Price>,
    /// Reason for cancellation or modification
    pub reason: Option<String>,
}

/// Types of order events
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
/// Types of order lifecycle events
///
/// Enumeration of all possible order event types that can occur during
/// the order lifecycle from placement to completion or cancellation.
pub enum OrderEventType {
    /// Order was placed
    Placed,
    /// Order was modified
    Modified,
    /// Order was cancelled
    Cancelled,
    /// Order was rejected
    Rejected,
    /// Order expired
    Expired,
}

/// Fill/execution events for trade settlements
#[derive(Debug, Clone, Serialize, Deserialize)]
/// Trade execution and settlement event
///
/// Represents the execution of an order, including fill details such as
/// quantity, price, commission, slippage, and settlement information.
pub struct FillEvent {
    /// Unique fill identifier
    pub fill_id: String,
    /// Associated order identifier
    pub order_id: OrderId,
    /// Trading symbol
    pub symbol: Symbol,
    /// Order side (buy/sell)
    pub side: OrderSide,
    /// Filled quantity
    pub quantity: Quantity,
    /// Fill price
    pub price: Price,
    /// Execution timestamp
    pub timestamp: DateTime<Utc>,
    /// Commission paid
    pub commission: Decimal,
    /// Slippage in basis points
    pub slippage_bps: Decimal,
    /// Execution venue
    pub venue: Option<String>,
    /// Strategy identifier
    pub strategy_id: Option<String>,
    /// Counterparty information
    pub counterparty: Option<String>,
    /// Settlement date
    pub settlement_date: Option<DateTime<Utc>>,
}

/// System events for infrastructure coordination and monitoring
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "system_event_type")]
/// System infrastructure events
///
/// Events for system coordination, health monitoring, progress tracking,
/// error notifications, and service lifecycle management.
pub enum SystemEvent {
    /// Periodic heartbeat for time advancement and health checks
    Heartbeat {
        timestamp: DateTime<Utc>,
        /// Service name sending the heartbeat
        service: String,
        /// Health status
        status: SystemStatus,
    },
    /// Progress update notifications
    Progress {
        timestamp: DateTime<Utc>,
        message: String,
        /// Progress percentage (0-100)
        progress: Option<u8>,
        /// Service generating the progress
        service: String,
    },
    /// Error notifications
    Error {
        timestamp: DateTime<Utc>,
        message: String,
        /// Error severity level
        severity: ErrorSeverity,
        /// Service that encountered the error
        service: String,
        /// Error code if applicable
        error_code: Option<String>,
    },
    /// Service startup notification
    ServiceStarted {
        timestamp: DateTime<Utc>,
        service: String,
        version: String,
    },
    /// Service shutdown notification
    ServiceStopped {
        timestamp: DateTime<Utc>,
        service: String,
        reason: Option<String>,
    },
}

/// System health status
///
/// Represents the operational health state of a service or system component.
/// Used for health monitoring, alerting, and operational dashboards.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
/// System health status levels
///
/// Hierarchical health status classification for system monitoring,
/// alerting, and operational dashboards.
pub enum SystemStatus {
    /// System is operating normally
    ///
    /// All components functioning within normal parameters.
    /// No immediate action required.
    Healthy,

    /// System has minor issues
    ///
    /// Operating with reduced performance or non-critical issues.
    /// Monitoring recommended but no immediate action required.
    Warning,

    /// System has serious issues
    ///
    /// Critical functionality affected, immediate attention required.
    /// May impact trading operations or system reliability.
    Critical,

    /// System performance is degraded
    ///
    /// Operating below normal performance levels but still functional.
    /// May require resource reallocation or optimization.
    Degraded,
}

/// Error severity levels
///
/// Hierarchical error classification for logging, alerting, and incident response.
/// Severity levels help prioritize error handling and determine appropriate responses.
#[derive(Debug, Clone, Serialize, Deserialize)]
/// Error severity classification
///
/// Hierarchical error severity levels for logging, alerting,
/// and incident response prioritization.
pub enum ErrorSeverity {
    /// Informational message
    ///
    /// General information that doesn't indicate a problem.
    /// Used for audit trails and debugging.
    Info,

    /// Warning condition
    ///
    /// Potentially problematic situation that doesn't affect functionality.
    /// Monitoring recommended but no immediate action required.
    Warning,

    /// Error condition
    ///
    /// Error that affects functionality but system can continue operating.
    /// May require investigation and corrective action.
    Error,

    /// Critical error
    ///
    /// Severe error that significantly impacts system functionality.
    /// Immediate attention required to prevent system failure.
    Critical,

    /// Fatal error
    ///
    /// Unrecoverable error that causes system or component failure.
    /// Immediate emergency response required.
    Fatal,
}
impl std::fmt::Display for ErrorSeverity {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Info => write!(f, "INFO"),
            Self::Warning => write!(f, "WARNING"),
            Self::Error => write!(f, "ERROR"),
            Self::Critical => write!(f, "CRITICAL"),
            Self::Fatal => write!(f, "FATAL"),
        }
    }
}

/// Risk management events and alerts
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "risk_event_type")]
/// Risk management events and alerts
///
/// Events related to risk management including position limits,
/// drawdown alerts, exposure breaches, and margin calls.
pub enum RiskEvent {
    /// Position limit breach
    PositionLimitBreach {
        /// Symbol where position limit was breached
        symbol: Symbol,
        /// Current position size that breached the limit
        current_position: Quantity,
        /// Position limit that was exceeded
        limit: Quantity,
        /// Timestamp when the breach occurred
        timestamp: DateTime<Utc>,
        /// Strategy that caused the breach
        strategy_id: String,
    },
    /// Drawdown alert
    DrawdownAlert {
        /// Current drawdown percentage or amount
        current_drawdown: Decimal,
        /// Maximum allowable drawdown limit
        max_drawdown_limit: Decimal,
        /// Timestamp when drawdown limit was breached
        timestamp: DateTime<Utc>,
        /// Strategy experiencing the drawdown
        strategy_id: String,
    },
    /// Exposure limit breach
    ExposureLimitBreach {
        /// Current exposure amount that breached the limit
        current_exposure: Decimal,
        /// Maximum exposure limit that was exceeded
        limit: Decimal,
        /// Timestamp when the exposure breach occurred
        timestamp: DateTime<Utc>,
        /// Strategy that caused the exposure breach
        strategy_id: String,
    },
    /// Margin call
    MarginCall {
        required_margin: Decimal,
        available_margin: Decimal,
        timestamp: DateTime<Utc>,
        account_id: String,
    },
}
/// Safety system events for emergency controls and kill switches
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "safety_event_type")]
/// Safety system control events
///
/// Emergency control events for kill switches, emergency stops,
/// and other safety system operations.
pub enum SafetySystemEvent {
    /// Kill switch engaged
    KillSwitchEngaged {
        scope: String,
        reason: String,
        timestamp: DateTime<Utc>,
    },
    /// Kill switch disengaged
    KillSwitchDisengaged {
        scope: String,
        timestamp: DateTime<Utc>,
    },
    /// Emergency stop
    EmergencyStop {
        reason: String,
        timestamp: DateTime<Utc>,
    },
}

/// Portfolio position events
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "position_event_type")]
/// Portfolio position events
///
/// Events tracking portfolio position changes including opening,
/// updating, closing, and reconciliation of positions.
pub enum PositionEvent {
    /// Position opened
    PositionOpened {
        symbol: Symbol,
        quantity: Quantity,
        average_price: Price,
        timestamp: DateTime<Utc>,
        strategy_id: String,
        account_id: String,
    },
    /// Position updated (partial fill)
    PositionUpdated {
        symbol: Symbol,
        old_quantity: Quantity,
        new_quantity: Quantity,
        old_average_price: Price,
        new_average_price: Price,
        timestamp: DateTime<Utc>,
        strategy_id: String,
        account_id: String,
    },
    /// Position closed
    PositionClosed {
        symbol: Symbol,
        final_quantity: Quantity,
        average_price: Price,
        realized_pnl: Decimal,
        timestamp: DateTime<Utc>,
        strategy_id: String,
        account_id: String,
    },
    /// Position reconciled (correcting discrepancies)
    PositionReconciled {
        symbol: Symbol,
        old_quantity: Quantity,
        new_quantity: Quantity,
        reason: String,
        timestamp: DateTime<Utc>,
        account_id: String,
    },
}

/// Time-ordered event queue for chronological processing
///
/// This is the canonical event queue implementation used throughout the system.
/// All services should use this for event ordering and processing.
#[derive(Debug)]
/// Time-ordered event queue for chronological processing
///
/// Priority queue that maintains events in chronological order for
/// deterministic event processing and backtesting.
pub struct EventQueue {
    queue: BinaryHeap<TimestampedEvent>,
    current_time: DateTime<Utc>,
}

/// Internal wrapper for events with timestamps and ordering
#[derive(Debug, Clone)]
struct TimestampedEvent {
    event: Event,
    timestamp: DateTime<Utc>,
}

impl PartialEq for TimestampedEvent {
    fn eq(&self, other: &Self) -> bool {
        self.timestamp == other.timestamp
    }
}

impl Eq for TimestampedEvent {}

impl PartialOrd for TimestampedEvent {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        Some(self.cmp(other))
    }
}

impl Ord for TimestampedEvent {
    fn cmp(&self, other: &Self) -> Ordering {
        // Reverse ordering for min-heap behavior (earliest timestamp first)
        other.timestamp.cmp(&self.timestamp)
    }
}

impl EventQueue {
    /// Create a new event queue with starting time
    #[must_use]
    pub fn new(start_time: DateTime<Utc>) -> Self {
        Self {
            queue: BinaryHeap::new(),
            current_time: start_time,
        }
    }

    /// Add an event to the queue with timestamp
    pub fn push(&mut self, event: Event, timestamp: DateTime<Utc>) {
        self.queue.push(TimestampedEvent { event, timestamp });
    }

    /// Get the next event in chronological order
    pub fn pop(&mut self) -> Option<(Event, DateTime<Utc>)> {
        self.queue.pop().map(|te| {
            self.current_time = te.timestamp;
            (te.event, te.timestamp)
        })
    }

    /// Peek at the next event without removing it
    #[must_use]
    pub fn peek(&self) -> Option<&Event> {
        self.queue.peek().map(|te| &te.event)
    }

    /// Check if the queue is empty
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.queue.is_empty()
    }

    /// Get the current time
    #[must_use]
    pub const fn current_time(&self) -> DateTime<Utc> {
        self.current_time
    }

    /// Get the number of pending events
    #[must_use]
    pub fn len(&self) -> usize {
        self.queue.len()
    }

    /// Clear all events from the queue
    pub fn clear(&mut self) {
        self.queue.clear();
    }

    /// Drain all events into a vector
    pub fn drain(&mut self) -> Vec<(Event, DateTime<Utc>)> {
        let mut events = Vec::new();
        while let Some(event) = self.pop() {
            events.push(event);
        }
        events
    }
}

/// Event filtering utilities for processing specific event types
#[derive(Debug)]
/// Event filtering utilities
///
/// Utility struct providing static methods for filtering events
/// by symbol, type, time range, and other criteria.
pub struct EventFilter;

impl EventFilter {
    /// Filter events by symbol
    #[must_use]
    pub fn by_symbol(events: &[Event], symbol: &Symbol) -> Vec<Event> {
        events
            .iter()
            .filter(|event| Self::event_matches_symbol(event, symbol))
            .cloned()
            .collect()
    }

    /// Filter events by event type
    #[must_use]
    pub fn by_type(events: &[Event], event_type: EventType) -> Vec<Event> {
        events
            .iter()
            .filter(|event| Self::event_matches_type(event, event_type))
            .cloned()
            .collect()
    }

    /// Filter events by time range
    #[must_use]
    pub fn by_time_range(
        events: &[(Event, DateTime<Utc>)],
        start: DateTime<Utc>,
        end: DateTime<Utc>,
    ) -> Vec<(Event, DateTime<Utc>)> {
        events
            .iter()
            .filter(|(_, timestamp)| *timestamp >= start && *timestamp <= end)
            .cloned()
            .collect()
    }

    /// Check if an event matches a specific symbol
    fn event_matches_symbol(event: &Event, symbol: &Symbol) -> bool {
        match event {
            Event::Market(market_event) => match market_event {
                MarketEvent::Quote { symbol: s, .. }
                | MarketEvent::Trade { symbol: s, .. }
                | MarketEvent::OrderBook { symbol: s, .. }
                | MarketEvent::OrderBookUpdate { symbol: s, .. }
                | MarketEvent::Bar { symbol: s, .. } => s == symbol,
                MarketEvent::Control { .. } => false, // Control events don't match specific symbols
                MarketEvent::Sentiment { entities, .. } => {
                    entities.iter().any(|entity| entity == symbol.as_str())
                },
            },
            Event::Order(order_event) => &order_event.symbol == symbol,
            Event::Fill(fill_event) => &fill_event.symbol == symbol,
            Event::Risk(risk_event) => match risk_event {
                RiskEvent::PositionLimitBreach { symbol: s, .. } => s == symbol,
                RiskEvent::DrawdownAlert { .. }
                | RiskEvent::ExposureLimitBreach { .. }
                | RiskEvent::MarginCall { .. } => false,
            },
            Event::Position(position_event) => match position_event {
                PositionEvent::PositionOpened { symbol: s, .. }
                | PositionEvent::PositionUpdated { symbol: s, .. }
                | PositionEvent::PositionClosed { symbol: s, .. }
                | PositionEvent::PositionReconciled { symbol: s, .. } => s == symbol,
            },
            Event::System(_) => false, // System events don't belong to specific symbols
        }
    }

    /// Check if an event matches a specific event type
    const fn event_matches_type(event: &Event, event_type: EventType) -> bool {
        matches!(
            (event, event_type),
            (Event::Market(_), EventType::Market)
                | (Event::Order(_), EventType::Order)
                | (Event::Fill(_), EventType::Fill)
                | (Event::System(_), EventType::System)
                | (Event::Risk(_), EventType::Risk)
                | (Event::Position(_), EventType::Position)
        )
    }
}

/// Event type enumeration for filtering
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
/// Event type enumeration for filtering
///
/// High-level event type classification used for event filtering
/// and type-based event handling.
pub enum EventType {
    /// Market data events
    Market,
    /// Order lifecycle events
    Order,
    /// Trade execution events
    Fill,
    /// System infrastructure events
    System,
    /// Risk management events
    Risk,
    /// Portfolio position events
    Position,
}

impl Event {
    /// Get the event timestamp if available
    #[must_use]
    pub const fn timestamp(&self) -> Option<DateTime<Utc>> {
        match self {
            Self::Market(market_event) => match market_event {
                MarketEvent::Quote { timestamp, .. } => Some(*timestamp),
                MarketEvent::Trade { timestamp, .. } => Some(*timestamp),
                MarketEvent::OrderBook { timestamp, .. } => Some(*timestamp),
                MarketEvent::OrderBookUpdate { timestamp, .. } => Some(*timestamp),
                MarketEvent::Bar { timestamp, .. } => Some(*timestamp),
                MarketEvent::Control { timestamp, .. } => Some(*timestamp),
                MarketEvent::Sentiment { timestamp, .. } => Some(*timestamp),
            },
            Self::Order(order_event) => Some(order_event.timestamp),
            Self::Fill(fill_event) => Some(fill_event.timestamp),
            Self::System(system_event) => match system_event {
                SystemEvent::Heartbeat { timestamp, .. } => Some(*timestamp),
                SystemEvent::Progress { timestamp, .. } => Some(*timestamp),
                SystemEvent::Error { timestamp, .. } => Some(*timestamp),
                SystemEvent::ServiceStarted { timestamp, .. } => Some(*timestamp),
                SystemEvent::ServiceStopped { timestamp, .. } => Some(*timestamp),
            },
            Self::Risk(risk_event) => match risk_event {
                RiskEvent::PositionLimitBreach { timestamp, .. } => Some(*timestamp),
                RiskEvent::DrawdownAlert { timestamp, .. } => Some(*timestamp),
                RiskEvent::ExposureLimitBreach { timestamp, .. } => Some(*timestamp),
                RiskEvent::MarginCall { timestamp, .. } => Some(*timestamp),
            },
            Self::Position(position_event) => match position_event {
                PositionEvent::PositionOpened { timestamp, .. } => Some(*timestamp),
                PositionEvent::PositionUpdated { timestamp, .. } => Some(*timestamp),
                PositionEvent::PositionClosed { timestamp, .. } => Some(*timestamp),
                PositionEvent::PositionReconciled { timestamp, .. } => Some(*timestamp),
            },
        }
    }

    /// Get the symbol associated with this event if available
    #[must_use]
    pub const fn symbol(&self) -> Option<&Symbol> {
        match self {
            Self::Market(market_event) => match market_event {
                MarketEvent::Quote { symbol, .. } => Some(symbol),
                MarketEvent::Trade { symbol, .. } => Some(symbol),
                MarketEvent::OrderBook { symbol, .. } => Some(symbol),
                MarketEvent::OrderBookUpdate { symbol, .. } => Some(symbol),
                MarketEvent::Bar { symbol, .. } => Some(symbol),
                MarketEvent::Control { .. } => None, // Control events don't have specific symbols
                MarketEvent::Sentiment { .. } => None, // Multiple symbols possible
            },
            Self::Order(order_event) => Some(&order_event.symbol),
            Self::Fill(fill_event) => Some(&fill_event.symbol),
            Self::Risk(risk_event) => match risk_event {
                RiskEvent::PositionLimitBreach { symbol, .. } => Some(symbol),
                RiskEvent::DrawdownAlert { .. }
                | RiskEvent::ExposureLimitBreach { .. }
                | RiskEvent::MarginCall { .. } => None,
            },
            Self::Position(position_event) => match position_event {
                PositionEvent::PositionOpened { symbol, .. } => Some(symbol),
                PositionEvent::PositionUpdated { symbol, .. } => Some(symbol),
                PositionEvent::PositionClosed { symbol, .. } => Some(symbol),
                PositionEvent::PositionReconciled { symbol, .. } => Some(symbol),
            },
            Self::System(_) => None,
        }
    }

    /// Get the event type
    #[must_use]
    pub const fn event_type(&self) -> EventType {
        match self {
            Self::Market(_) => EventType::Market,
            Self::Order(_) => EventType::Order,
            Self::Fill(_) => EventType::Fill,
            Self::System(_) => EventType::System,
            Self::Risk(_) => EventType::Risk,
            Self::Position(_) => EventType::Position,
        }
    }

    /// Get a string representation of the specific event variant
    #[must_use]
    pub const fn event_variant(&self) -> &'static str {
        match self {
            Self::Market(market_event) => match market_event {
                MarketEvent::Quote { .. } => "MarketQuote",
                MarketEvent::Trade { .. } => "MarketTrade",
                MarketEvent::OrderBook { .. } => "MarketOrderBook",
                MarketEvent::OrderBookUpdate { .. } => "MarketOrderBookUpdate",
                MarketEvent::Bar { .. } => "MarketBar",
                MarketEvent::Control { .. } => "MarketControl",
                MarketEvent::Sentiment { .. } => "MarketSentiment",
            },
            Self::Order(order_event) => match order_event.event_type {
                OrderEventType::Placed => "OrderPlaced",
                OrderEventType::Modified => "OrderModified",
                OrderEventType::Cancelled => "OrderCancelled",
                OrderEventType::Rejected => "OrderRejected",
                OrderEventType::Expired => "OrderExpired",
            },
            Self::Fill(_) => "Fill",
            Self::System(system_event) => match system_event {
                SystemEvent::Heartbeat { .. } => "SystemHeartbeat",
                SystemEvent::Progress { .. } => "SystemProgress",
                SystemEvent::Error { .. } => "SystemError",
                SystemEvent::ServiceStarted { .. } => "SystemServiceStarted",
                SystemEvent::ServiceStopped { .. } => "SystemServiceStopped",
            },
            Self::Risk(risk_event) => match risk_event {
                RiskEvent::PositionLimitBreach { .. } => "RiskPositionLimitBreach",
                RiskEvent::DrawdownAlert { .. } => "RiskDrawdownAlert",
                RiskEvent::ExposureLimitBreach { .. } => "RiskExposureLimitBreach",
                RiskEvent::MarginCall { .. } => "RiskMarginCall",
            },
            Self::Position(position_event) => match position_event {
                PositionEvent::PositionOpened { .. } => "PositionOpened",
                PositionEvent::PositionUpdated { .. } => "PositionUpdated",
                PositionEvent::PositionClosed { .. } => "PositionClosed",
                PositionEvent::PositionReconciled { .. } => "PositionReconciled",
            },
        }
    }
}

impl std::fmt::Display for Event {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.event_variant())
    }
}

/// Helper functions for creating common events
pub mod builders {
    use super::{
        DateTime, Decimal, Event, FillEvent, MarketEvent, OrderEvent, OrderEventType, OrderId,
        OrderType, Price, Quantity, Symbol, SystemEvent, SystemStatus, Utc,
    };
    use common::OrderSide;

    /// Create a market quote event
    #[must_use]
    pub const fn market_quote(
        symbol: Symbol,
        bid_price: Price,
        bid_size: Quantity,
        ask_price: Price,
        ask_size: Quantity,
        timestamp: DateTime<Utc>,
        venue: Option<String>,
    ) -> Event {
        Event::Market(MarketEvent::Quote {
            symbol,
            bid_price,
            bid_size,
            ask_price,
            ask_size,
            timestamp,
            venue,
        })
    }

    /// Create a market trade event
    #[must_use]
    pub const fn market_trade(
        symbol: Symbol,
        price: Price,
        size: Quantity,
        timestamp: DateTime<Utc>,
        trade_side: Option<OrderSide>,
        venue: Option<String>,
        trade_id: Option<String>,
    ) -> Event {
        Event::Market(MarketEvent::Trade {
            symbol,
            price,
            size,
            timestamp,
            side: trade_side,
            venue,
            trade_id,
        })
    }

    /// Create an order placed event
    #[must_use]
    pub const fn order_placed(
        order_id: OrderId,
        symbol: Symbol,
        order_type: OrderType,
        side: OrderSide,
        quantity: Quantity,
        price: Option<Price>,
        timestamp: DateTime<Utc>,
        strategy_id: String,
    ) -> Event {
        Event::Order(OrderEvent {
            order_id,
            symbol,
            order_type,
            side,
            quantity,
            price,
            timestamp,
            strategy_id,
            event_type: OrderEventType::Placed,
            previous_quantity: None,
            previous_price: None,
            reason: None,
        })
    }

    /// Create a fill event
    #[must_use]
    pub const fn fill(
        fill_id: String,
        order_id: OrderId,
        symbol: Symbol,
        side: OrderSide,
        quantity: Quantity,
        price: Price,
        timestamp: DateTime<Utc>,
        commission: Decimal,
        slippage_bps: Decimal,
    ) -> Event {
        Event::Fill(FillEvent {
            fill_id,
            order_id,
            symbol,
            side,
            quantity,
            price,
            timestamp,
            commission,
            slippage_bps,
            venue: None,
            strategy_id: None,
            counterparty: None,
            settlement_date: None,
        })
    }

    /// Create a system heartbeat event
    #[must_use]
    pub const fn system_heartbeat(
        timestamp: DateTime<Utc>,
        service: String,
        status: SystemStatus,
    ) -> Event {
        Event::System(SystemEvent::Heartbeat {
            timestamp,
            service,
            status,
        })
    }
}

#[cfg(test)]
#[allow(clippy::redundant_clone)]
mod tests {
    use super::*;
    use chrono::{Duration, TimeZone};
    // CANONICAL TYPE IMPORTS - FromPrimitive available via types::prelude
    use crate::types::test_utils::test_symbols::*;
    use anyhow::anyhow;
    // use crate::operations; // Available if needed

    // Type alias for backward compatibility with tests
    type TradingEvent = Event;

    #[test]
    fn test_event_queue_ordering() -> Result<(), anyhow::Error> {
        let start_time = Utc
            .with_ymd_and_hms(2024, 1, 1, 0, 0, 0)
            .single()
            .ok_or_else(|| anyhow!("Failed to create start time"))?;
        let mut queue = EventQueue::new(start_time);

        let timestamp1 = Utc
            .with_ymd_and_hms(2024, 1, 1, 0, 0, 2)
            .single()
            .ok_or_else(|| anyhow!("Failed to create timestamp1"))?;
        let timestamp2 = Utc
            .with_ymd_and_hms(2024, 1, 1, 0, 0, 1)
            .single()
            .ok_or_else(|| anyhow!("Failed to create timestamp2"))?;

        let event1 = Event::System(SystemEvent::Heartbeat {
            timestamp: timestamp1,
            service: "test".to_string(),
            status: SystemStatus::Healthy,
        });
        let event2 = Event::System(SystemEvent::Heartbeat {
            timestamp: timestamp2,
            service: "test".to_string(),
            status: SystemStatus::Healthy,
        });

        let push_time1 = Utc
            .with_ymd_and_hms(2024, 1, 1, 0, 0, 2)
            .single()
            .ok_or_else(|| anyhow!("Failed to create push time1"))?;
        let push_time2 = Utc
            .with_ymd_and_hms(2024, 1, 1, 0, 0, 1)
            .single()
            .ok_or_else(|| anyhow!("Failed to create push time2"))?;

        queue.push(event1, push_time1);
        queue.push(event2, push_time2);

        let (_, timestamp1) = queue.pop().ok_or_else(|| anyhow!("Expected event 1"))?;
        let (_, timestamp2) = queue.pop().ok_or_else(|| anyhow!("Expected event 2"))?;

        assert!(timestamp1 < timestamp2);
        Ok(())
    }

    #[test]
    fn test_event_filtering_by_symbol() -> Result<(), Box<dyn std::error::Error>> {
        let symbol = test_symbol_1();
        let other_symbol = test_symbol_2();

        let events = vec![
            Event::Market(MarketEvent::Quote {
                symbol: symbol.clone(),
                bid_price: Price::from_f64(150.00)?,
                bid_size: Quantity::try_from(100_u64)?,
                ask_price: Price::from_f64(150.05)?,
                ask_size: Quantity::try_from(100_u64)?,
                timestamp: Utc::now(),
                venue: None,
            }),
            Event::Market(MarketEvent::Quote {
                symbol: other_symbol,
                bid_price: Price::from_f64(300.00)?,
                bid_size: Quantity::try_from(100_u64)?,
                ask_price: Price::from_f64(300.05)?,
                ask_size: Quantity::try_from(100_u64)?,
                timestamp: Utc::now(),
                venue: None,
            }),
        ];

        let filtered = EventFilter::by_symbol(&events, &symbol);
        assert_eq!(filtered.len(), 1);
        Ok(())
    }

    #[test]
    fn test_event_queue_empty() {
        let queue = EventQueue::new(Utc::now());
        assert!(queue.is_empty());
        assert_eq!(queue.len(), 0);
    }

    #[test]
    fn test_fill_event_creation() -> Result<(), Box<dyn std::error::Error>> {
        let fill = FillEvent {
            fill_id: "fill_123".to_string(),
            order_id: OrderId::new(),
            symbol: test_symbol_1(),
            side: OrderSide::Buy,
            quantity: Quantity::try_from(100_u64)?,
            price: Price::from_f64(150.25)?,
            timestamp: Utc::now(),
            commission: Decimal::try_from(1.00_f64)?,
            slippage_bps: Decimal::try_from(2.5_f64)?,
            venue: None,
            strategy_id: None,
            counterparty: None,
            settlement_date: None,
        };

        assert_eq!(fill.fill_id, "fill_123");
        assert_eq!(fill.side, OrderSide::Buy);
        Ok(())
    }

    #[test]
    fn test_event_builders() -> Result<(), Box<dyn std::error::Error>> {
        let timestamp = Utc::now();
        let symbol = Symbol::new("BTCUSD".to_string());

        // Test market quote builder
        let quote_event = builders::market_quote(
            symbol.clone(),
            Price::from_f64(50000.0)?,
            Quantity::try_from(1_u64)?,
            Price::from_f64(50005.0)?,
            Quantity::try_from(1_u64)?,
            timestamp,
            Some("Binance".to_string()),
        );

        assert!(matches!(
            quote_event,
            Event::Market(MarketEvent::Quote { .. })
        ));
        assert_eq!(quote_event.symbol(), Some(&symbol));

        // Test order placed builder
        let order_event = builders::order_placed(
            OrderId::new(),
            symbol.clone(),
            OrderType::Limit,
            OrderSide::Buy,
            Quantity::try_from(1_u64)?,
            Some(Price::from_f64(50000.0)?),
            timestamp,
            "strategy_1".to_string(),
        );

        assert!(matches!(order_event, Event::Order(_)));
        assert_eq!(order_event.event_variant(), "OrderPlaced");
        Ok(())
    }

    #[test]
    fn test_event_filtering_by_type() -> Result<(), Box<dyn std::error::Error>> {
        let events = vec![
            Event::Market(MarketEvent::Quote {
                symbol: test_symbol_1(),
                bid_price: Price::from_f64(150.00)?,
                bid_size: Quantity::try_from(100_u64)?,
                ask_price: Price::from_f64(150.05)?,
                ask_size: Quantity::try_from(100_u64)?,
                timestamp: Utc::now(),
                venue: None,
            }),
            Event::System(SystemEvent::Heartbeat {
                timestamp: Utc::now(),
                service: "test".to_string(),
                status: SystemStatus::Healthy,
            }),
        ];

        let market_events = EventFilter::by_type(&events, EventType::Market);
        let system_events = EventFilter::by_type(&events, EventType::System);

        assert_eq!(market_events.len(), 1);
        assert_eq!(system_events.len(), 1);
        Ok(())
    }

    #[test]
    fn test_event_display() -> Result<(), Box<dyn std::error::Error>> {
        let event = Event::Market(MarketEvent::Quote {
            symbol: test_symbol_1(),
            bid_price: Price::from_f64(150.00)?,
            bid_size: Quantity::try_from(100_u64)?,
            ask_price: Price::from_f64(150.05)?,
            ask_size: Quantity::try_from(100_u64)?,
            timestamp: Utc::now(),
            venue: None,
        });

        assert_eq!(format!("{}", event), "MarketQuote");
        assert_eq!(event.event_variant(), "MarketQuote");
        assert_eq!(event.event_type(), EventType::Market);
        Ok(())
    }

    #[test]
    fn test_all_market_event_variants() -> Result<(), Box<dyn std::error::Error>> {
        let symbol = Symbol::new("BTCUSD".to_string());
        let timestamp = Utc::now();
        let venue = Some("Binance".to_string());

        // Test Quote variant
        let quote_event = Event::Market(MarketEvent::Quote {
            symbol: symbol.clone(),
            bid_price: Price::from_f64(50000.0)?,
            bid_size: Quantity::from_f64(1.0)?,
            ask_price: Price::from_f64(50005.0)?,
            ask_size: Quantity::from_f64(1.0)?,
            timestamp,
            venue: venue.clone(),
        });
        assert_eq!(quote_event.event_variant(), "MarketQuote");
        assert_eq!(quote_event.symbol(), Some(&symbol));

        // Test Trade variant
        let trade_event = Event::Market(MarketEvent::Trade {
            symbol: symbol.clone(),
            price: Price::from_f64(50002.5)?,
            size: Quantity::from_f64(0.5)?,
            timestamp,
            side: Some(OrderSide::Buy),
            venue: venue.clone(),
            trade_id: Some("trade_123".to_string()),
        });
        assert_eq!(trade_event.event_variant(), "MarketTrade");

        // Test OrderBook variant
        let order_book_event = Event::Market(MarketEvent::OrderBook {
            symbol: symbol.clone(),
            bids: vec![
                (Price::from_f64(50000.0)?, Quantity::from_f64(1.0)?),
                (Price::from_f64(49995.0)?, Quantity::from_f64(2.0)?),
            ],
            asks: vec![
                (Price::from_f64(50005.0)?, Quantity::from_f64(1.0)?),
                (Price::from_f64(50010.0)?, Quantity::from_f64(2.0)?),
            ],
            timestamp,
            venue: venue.clone(),
            sequence: Some(12345),
        });
        assert_eq!(order_book_event.event_variant(), "MarketOrderBook");

        // Test Sentiment variant
        let sentiment_event = Event::Market(MarketEvent::Sentiment {
            event_type: "earnings_beat".to_string(),
            description: "Company exceeded earnings expectations".to_string(),
            entities: vec![test_symbol_1().to_string(), "Apple Inc.".to_string()],
            impact_score: 0.75,
            confidence: 0.85,
            timestamp,
        });
        assert_eq!(sentiment_event.event_variant(), "MarketSentiment");
        assert_eq!(sentiment_event.symbol(), None); // Sentiment events don't have a single symbol
        Ok(())
    }

    #[test]
    fn test_all_order_event_types() -> Result<(), Box<dyn std::error::Error>> {
        let order_id = OrderId::new();
        let symbol = test_symbol_2();
        let timestamp = Utc::now();
        let quantity = Quantity::from_f64(100.0)?;
        let price = Some(Price::from_f64(300.0)?);

        let order_event_types = vec![
            OrderEventType::Placed,
            OrderEventType::Modified,
            OrderEventType::Cancelled,
            OrderEventType::Rejected,
            OrderEventType::Expired,
        ];

        for event_type in order_event_types {
            let order_event = Event::Order(OrderEvent {
                order_id: order_id.clone(),
                symbol: symbol.clone(),
                order_type: OrderType::Limit,
                side: OrderSide::Buy,
                quantity,
                price,
                timestamp,
                strategy_id: "test_strategy".to_string(),
                event_type: event_type.clone(),
                previous_quantity: None,
                previous_price: None,
                reason: None,
            });

            match event_type {
                OrderEventType::Placed => assert_eq!(order_event.event_variant(), "OrderPlaced"),
                OrderEventType::Modified => {
                    assert_eq!(order_event.event_variant(), "OrderModified")
                },
                OrderEventType::Cancelled => {
                    assert_eq!(order_event.event_variant(), "OrderCancelled")
                },
                OrderEventType::Rejected => {
                    assert_eq!(order_event.event_variant(), "OrderRejected")
                },
                OrderEventType::Expired => assert_eq!(order_event.event_variant(), "OrderExpired"),
            }

            assert_eq!(order_event.event_type(), EventType::Order);
            assert_eq!(order_event.symbol(), Some(&symbol));
        }
        Ok(())
    }

    #[test]
    fn test_system_event_variants() {
        let timestamp = Utc::now();
        let service = "trading-engine".to_string();

        // Test Heartbeat
        let heartbeat_event = Event::System(SystemEvent::Heartbeat {
            timestamp,
            service: service.clone(),
            status: SystemStatus::Healthy,
        });
        assert_eq!(heartbeat_event.event_variant(), "SystemHeartbeat");

        // Test Progress
        let progress_event = Event::System(SystemEvent::Progress {
            timestamp,
            message: "Processing market data".to_string(),
            progress: Some(75),
            service: service.clone(),
        });
        assert_eq!(progress_event.event_variant(), "SystemProgress");

        // Test Error
        let error_event = Event::System(SystemEvent::Error {
            timestamp,
            message: "Connection timeout".to_string(),
            severity: ErrorSeverity::Warning,
            service: service.clone(),
            error_code: Some("CONN_TIMEOUT".to_string()),
        });
        assert_eq!(error_event.event_variant(), "SystemError");

        // Test ServiceStarted
        let started_event = Event::System(SystemEvent::ServiceStarted {
            timestamp,
            service: service.clone(),
            version: "1.2.3".to_string(),
        });
        assert_eq!(started_event.event_variant(), "SystemServiceStarted");

        // Test ServiceStopped
        let stopped_event = Event::System(SystemEvent::ServiceStopped {
            timestamp,
            service: service.clone(),
            reason: Some("Scheduled maintenance".to_string()),
        });
        assert_eq!(stopped_event.event_variant(), "SystemServiceStopped");
    }

    #[test]
    fn test_system_status_and_error_severity() {
        // Test all SystemStatus variants
        let statuses = vec![
            SystemStatus::Healthy,
            SystemStatus::Warning,
            SystemStatus::Critical,
            SystemStatus::Degraded,
        ];

        for status in statuses {
            let debug_str = format!("{:?}", status);
            assert!(!debug_str.is_empty());
        }

        // Test all ErrorSeverity variants with Display trait
        let severities = vec![
            (ErrorSeverity::Info, "INFO"),
            (ErrorSeverity::Warning, "WARNING"),
            (ErrorSeverity::Error, "ERROR"),
            (ErrorSeverity::Critical, "CRITICAL"),
            (ErrorSeverity::Fatal, "FATAL"),
        ];

        for (severity, expected_str) in severities {
            assert_eq!(severity.to_string(), expected_str);
            assert_eq!(format!("{}", severity), expected_str);
        }
    }

    #[test]
    fn test_risk_event_variants() -> Result<(), Box<dyn std::error::Error>> {
        let symbol = Symbol::new("TSLA".to_string());
        let timestamp = Utc::now();
        let strategy_id = "aggressive_momentum".to_string();

        // Test PositionLimitBreach
        let position_limit_event = Event::Risk(RiskEvent::PositionLimitBreach {
            symbol: symbol.clone(),
            current_position: Quantity::from_f64(1500.0)?,
            limit: Quantity::from_f64(1000.0)?,
            timestamp,
            strategy_id: strategy_id.clone(),
        });
        assert_eq!(
            position_limit_event.event_variant(),
            "RiskPositionLimitBreach"
        );
        assert_eq!(position_limit_event.symbol(), Some(&symbol));

        // Test DrawdownAlert
        let drawdown_event = Event::Risk(RiskEvent::DrawdownAlert {
            current_drawdown: Decimal::try_from(-0.15).unwrap_or(Decimal::ZERO),
            max_drawdown_limit: Decimal::try_from(-0.10).unwrap_or(Decimal::ZERO),
            timestamp,
            strategy_id: strategy_id.clone(),
        });
        assert_eq!(drawdown_event.event_variant(), "RiskDrawdownAlert");

        // Test ExposureLimitBreach
        let exposure_event = Event::Risk(RiskEvent::ExposureLimitBreach {
            current_exposure: Decimal::try_from(150_000.0).unwrap_or(Decimal::ZERO),
            limit: Decimal::try_from(100_000.0).unwrap_or(Decimal::ZERO),
            timestamp,
            strategy_id: strategy_id.clone(),
        });
        assert_eq!(exposure_event.event_variant(), "RiskExposureLimitBreach");

        // Test MarginCall
        let margin_call_event = Event::Risk(RiskEvent::MarginCall {
            required_margin: Decimal::try_from(50000.0).unwrap_or(Decimal::ZERO),
            available_margin: Decimal::try_from(30000.0).unwrap_or(Decimal::ZERO),
            timestamp,
            account_id: "acc_123".to_string(),
        });
        assert_eq!(margin_call_event.event_variant(), "RiskMarginCall");

        Ok(())
    }

    #[test]
    fn test_position_event_variants() -> Result<(), Box<dyn std::error::Error>> {
        let symbol = Symbol::new("NVDA".to_string());
        let timestamp = Utc::now();
        let strategy_id = "ai_trend".to_string();
        let account_id = "account_456".to_string();

        // Test PositionOpened
        let opened_event = Event::Position(PositionEvent::PositionOpened {
            symbol: symbol.clone(),
            quantity: Quantity::from_f64(200.0)?,
            average_price: Price::from_f64(800.0)?,
            timestamp,
            strategy_id: strategy_id.clone(),
            account_id: account_id.clone(),
        });
        assert_eq!(opened_event.event_variant(), "PositionOpened");

        // Test PositionUpdated
        let updated_event = Event::Position(PositionEvent::PositionUpdated {
            symbol: symbol.clone(),
            old_quantity: Quantity::from_f64(200.0)?,
            new_quantity: Quantity::from_f64(300.0)?,
            old_average_price: Price::from_f64(800.0)?,
            new_average_price: Price::from_f64(810.0)?,
            timestamp,
            strategy_id: strategy_id.clone(),
            account_id: account_id.clone(),
        });
        assert_eq!(updated_event.event_variant(), "PositionUpdated");

        // Test PositionClosed
        let closed_event = Event::Position(PositionEvent::PositionClosed {
            symbol: symbol.clone(),
            final_quantity: Quantity::from_f64(0.0)?,
            average_price: Price::from_f64(820.0)?,
            realized_pnl: Decimal::try_from(6000.0).unwrap_or(Decimal::ZERO),
            timestamp,
            strategy_id: strategy_id.clone(),
            account_id: account_id.clone(),
        });
        assert_eq!(closed_event.event_variant(), "PositionClosed");

        // Test PositionReconciled
        let reconciled_event = Event::Position(PositionEvent::PositionReconciled {
            symbol: symbol.clone(),
            old_quantity: Quantity::from_f64(100.0)?,
            new_quantity: Quantity::from_f64(95.0)?,
            reason: "Corporate action adjustment".to_string(),
            timestamp,
            account_id: account_id.clone(),
        });
        assert_eq!(reconciled_event.event_variant(), "PositionReconciled");
        Ok(())
    }

    #[test]
    fn test_event_queue_comprehensive() -> Result<(), Box<dyn std::error::Error>> {
        let start_time = Utc.with_ymd_and_hms(2024, 1, 1, 0, 0, 0).unwrap();
        let mut queue = EventQueue::new(start_time);

        // Test initial state
        assert!(queue.is_empty());
        assert_eq!(queue.len(), 0);
        assert_eq!(queue.current_time(), start_time);
        assert!(queue.peek().is_none());

        // Create events with different timestamps
        let t1 = start_time + Duration::seconds(10);
        let t2 = start_time + Duration::seconds(5);
        let t3 = start_time + Duration::seconds(15);

        let event1 = Event::System(SystemEvent::Heartbeat {
            timestamp: t1,
            service: "service1".to_string(),
            status: SystemStatus::Healthy,
        });

        let event2 = Event::System(SystemEvent::Heartbeat {
            timestamp: t2,
            service: "service2".to_string(),
            status: SystemStatus::Healthy,
        });

        let event3 = Event::System(SystemEvent::Heartbeat {
            timestamp: t3,
            service: "service3".to_string(),
            status: SystemStatus::Healthy,
        });

        // Add events out of order
        queue.push(event1.clone(), t1);
        queue.push(event3.clone(), t3);
        queue.push(event2.clone(), t2);

        // Queue should have 3 events
        assert!(!queue.is_empty());
        assert_eq!(queue.len(), 3);

        // Peek should show earliest event (t2)
        let peeked = queue.peek();
        assert!(peeked.is_some());

        // Pop events in chronological order
        let (_popped_event1, popped_time1) = queue.pop().ok_or("Queue is empty")?;
        assert_eq!(popped_time1, t2);
        assert_eq!(queue.current_time(), t2);

        let (_popped_event2, popped_time2) = queue.pop().ok_or("Queue is empty")?;
        assert_eq!(popped_time2, t1);
        assert_eq!(queue.current_time(), t1);

        let (_popped_event3, popped_time3) = queue.pop().ok_or("Queue is empty")?;
        assert_eq!(popped_time3, t3);
        assert_eq!(queue.current_time(), t3);

        // Queue should be empty now
        assert!(queue.is_empty());
        assert_eq!(queue.len(), 0);
        assert!(queue.pop().is_none());
        Ok(())
    }

    #[test]
    fn test_event_queue_drain_and_clear() -> Result<(), Box<dyn std::error::Error>> {
        let start_time = Utc::now();
        let mut queue = EventQueue::new(start_time);

        // Add multiple events
        for i in 0..10 {
            let event = Event::System(SystemEvent::Progress {
                timestamp: start_time + Duration::seconds(i),
                message: format!("Progress {}", i),
                progress: Some((i * 10) as u8),
                service: "test_service".to_string(),
            });
            queue.push(event, start_time + Duration::seconds(i));
        }

        assert_eq!(queue.len(), 10);

        // Test drain
        let drained_events = queue.drain();
        assert_eq!(drained_events.len(), 10);
        assert!(queue.is_empty());

        // Verify events were drained in chronological order
        for (i, (_event, timestamp)) in drained_events.into_iter().enumerate() {
            assert_eq!(timestamp, start_time + Duration::seconds(i as i64));
        }

        // Add events again
        for i in 0..5 {
            let event = Event::System(SystemEvent::Heartbeat {
                timestamp: start_time + Duration::seconds(i),
                service: format!("service_{}", i),
                status: SystemStatus::Healthy,
            });
            queue.push(event, start_time + Duration::seconds(i));
        }

        assert_eq!(queue.len(), 5);

        // Test clear
        queue.clear();
        assert!(queue.is_empty());
        assert_eq!(queue.len(), 0);
        Ok(())
    }

    #[test]
    fn test_event_filter_comprehensive() -> Result<(), Box<dyn std::error::Error>> {
        let symbol1 = test_symbol_1();
        let symbol2 = test_symbol_3();
        let timestamp = Utc::now();

        let events = vec![
            Event::Market(MarketEvent::Quote {
                symbol: symbol1.clone(),
                bid_price: Price::from_f64(150.0)?,
                bid_size: Quantity::from_f64(100.0)?,
                ask_price: Price::from_f64(150.05)?,
                ask_size: Quantity::from_f64(100.0)?,
                timestamp,
                venue: None,
            }),
            Event::Order(OrderEvent {
                order_id: OrderId::new(),
                symbol: symbol1.clone(),
                order_type: OrderType::Limit,
                side: OrderSide::Buy,
                quantity: Quantity::from_f64(100.0)?,
                price: Some(Price::from_f64(149.95)?),
                timestamp,
                strategy_id: "strategy1".to_string(),
                event_type: OrderEventType::Placed,
                previous_quantity: None,
                previous_price: None,
                reason: None,
            }),
            Event::Fill(FillEvent {
                fill_id: "fill_123".to_string(),
                order_id: OrderId::new(),
                symbol: symbol2.clone(),
                side: OrderSide::Sell,
                quantity: Quantity::from_f64(50.0)?,
                price: Price::from_f64(2800.0)?,
                timestamp,
                commission: Decimal::try_from(2.50).unwrap_or(Decimal::ZERO),
                slippage_bps: Decimal::try_from(1.0).unwrap_or(Decimal::ZERO),
                venue: Some("NASDAQ".to_string()),
                strategy_id: Some("strategy2".to_string()),
                counterparty: None,
                settlement_date: None,
            }),
            Event::System(SystemEvent::Heartbeat {
                timestamp,
                service: "market_data".to_string(),
                status: SystemStatus::Healthy,
            }),
            Event::Risk(RiskEvent::PositionLimitBreach {
                symbol: symbol1.clone(),
                current_position: Quantity::from_i64(1500)
                    .map_err(|e| format!("Failed to create position quantity: {}", e))
                    .unwrap(),
                limit: Quantity::from_i64(1000)
                    .map_err(|e| format!("Failed to create limit quantity: {}", e))
                    .unwrap(),
                timestamp,
                strategy_id: "strategy1".to_string(),
            }),
            Event::Position(PositionEvent::PositionOpened {
                symbol: symbol2.clone(),
                quantity: Quantity::from_i64(100)
                    .map_err(|e| format!("Failed to create position quantity: {}", e))
                    .unwrap(),
                average_price: Price::from_f64(2795.0)?,
                timestamp,
                strategy_id: "strategy2".to_string(),
                account_id: "account1".to_string(),
            }),
        ];

        // Test filtering by symbol1
        let symbol1_events = EventFilter::by_symbol(&events, &symbol1);
        assert_eq!(symbol1_events.len(), 3); // Quote, Order, Risk

        // Test filtering by symbol2
        let symbol2_events = EventFilter::by_symbol(&events, &symbol2);
        assert_eq!(symbol2_events.len(), 2); // Fill, Position

        // Test filtering by event types
        let market_events = EventFilter::by_type(&events, EventType::Market);
        assert_eq!(market_events.len(), 1);

        let order_events = EventFilter::by_type(&events, EventType::Order);
        assert_eq!(order_events.len(), 1);

        let fill_events = EventFilter::by_type(&events, EventType::Fill);
        assert_eq!(fill_events.len(), 1);

        let system_events = EventFilter::by_type(&events, EventType::System);
        assert_eq!(system_events.len(), 1);

        let risk_events = EventFilter::by_type(&events, EventType::Risk);
        assert_eq!(risk_events.len(), 1);

        let position_events = EventFilter::by_type(&events, EventType::Position);
        assert_eq!(position_events.len(), 1);

        // Test time range filtering
        let start_range = timestamp - Duration::minutes(1);
        let end_range = timestamp + Duration::minutes(1);

        let events_with_time: Vec<(Event, DateTime<Utc>)> =
            events.into_iter().map(|e| (e, timestamp)).collect();

        let filtered_by_time =
            EventFilter::by_time_range(&events_with_time, start_range, end_range);
        assert_eq!(filtered_by_time.len(), 6); // All events within range

        // Test filtering outside range
        let future_start = timestamp + Duration::hours(1);
        let future_end = timestamp + Duration::hours(2);
        let future_filtered =
            EventFilter::by_time_range(&events_with_time, future_start, future_end);
        assert_eq!(future_filtered.len(), 0); // No events in future range
        Ok(())
    }

    #[test]
    fn test_event_builders_comprehensive() -> Result<(), Box<dyn std::error::Error>> {
        let symbol = Symbol::new("BTC-USD".to_string());
        let timestamp = Utc::now();

        // Test market_quote builder
        let quote = builders::market_quote(
            symbol.clone(),
            Price::from_f64(45000.0)?,
            Quantity::from_f64(2.0)?,
            Price::from_f64(45050.0)?,
            Quantity::from_f64(1.5)?,
            timestamp,
            Some("Coinbase".to_string()),
        );

        if let Event::Market(MarketEvent::Quote {
            bid_price,
            ask_price,
            venue,
            ..
        }) = quote
        {
            assert_eq!(bid_price.to_f64(), 45000.0);
            assert_eq!(ask_price.to_f64(), 45050.0);
            assert_eq!(venue, Some("Coinbase".to_string()));
        } else {
            return Err(anyhow!("Expected MarketEvent::Quote").into());
        }

        // Test market_trade builder
        let trade = builders::market_trade(
            symbol.clone(),
            Price::from_f64(45025.0)?,
            Quantity::from_f64(0.5)?,
            timestamp,
            // Some variant
            Some(OrderSide::Buy),
            Some("Coinbase".to_string()),
            Some("trade_456".to_string()),
        );

        if let Event::Market(MarketEvent::Trade {
            price,
            size,
            side,
            trade_id,
            ..
        }) = trade
        {
            assert_eq!(price.to_f64(), 45025.0);
            assert_eq!(size.to_f64(), 0.5);
            assert_eq!(side, Some(OrderSide::Buy));
            assert_eq!(trade_id, Some("trade_456".to_string()));
        } else {
            return Err(anyhow!("Expected MarketEvent::Trade").into());
        }

        // Test order_placed builder
        let order = builders::order_placed(
            OrderId::new(),
            symbol.clone(),
            OrderType::Market,
            OrderSide::Sell,
            Quantity::from_f64(1.0)?,
            // None variant
            None,
            timestamp,
            "crypto_strategy".to_string(),
        );

        if let Event::Order(order_event) = order {
            assert_eq!(order_event.order_type, OrderType::Market);
            assert_eq!(order_event.side, OrderSide::Sell);
            assert_eq!(order_event.event_type, OrderEventType::Placed);
            assert_eq!(order_event.strategy_id, "crypto_strategy");
        } else {
            return Err(anyhow!("Expected OrderEvent").into());
        }

        // Test fill builder
        let fill = builders::fill(
            "fill_789".to_string(),
            OrderId::new(),
            symbol.clone(),
            OrderSide::Buy,
            Quantity::from_f64(0.25)?,
            Price::from_f64(45030.0)?,
            timestamp,
            Decimal::try_from(5.0).unwrap_or(Decimal::ZERO),
            Decimal::try_from(2.5).unwrap_or(Decimal::ZERO),
        );

        if let Event::Fill(fill_event) = fill {
            assert_eq!(fill_event.fill_id, "fill_789");
            assert_eq!(fill_event.quantity.to_f64(), 0.25);
            assert_eq!(
                fill_event.commission,
                Decimal::try_from(5.0).unwrap_or(Decimal::ZERO)
            );
        } else {
            return Err(anyhow!("Expected FillEvent").into());
        }

        // Test system_heartbeat builder
        let heartbeat = builders::system_heartbeat(
            timestamp,
            "order_management".to_string(),
            SystemStatus::Warning,
        );

        if let Event::System(SystemEvent::Heartbeat {
            service, status, ..
        }) = heartbeat
        {
            assert_eq!(service, "order_management");
            assert_eq!(status, SystemStatus::Warning);
        } else {
            return Err(anyhow!("Expected SystemEvent::Heartbeat").into());
        }

        Ok(())
    }

    #[test]
    fn test_event_type_enum_properties() {
        let event_types = vec![
            EventType::Market,
            EventType::Order,
            EventType::Fill,
            EventType::System,
            EventType::Risk,
            EventType::Position,
        ];

        // Test Debug trait
        for event_type in &event_types {
            let debug_str = format!("{:?}", event_type);
            assert!(!debug_str.is_empty());
        }

        // Test Copy trait
        for event_type in &event_types {
            let copied = *event_type;
            assert_eq!(copied, *event_type);
        }

        // Test PartialEq
        assert_eq!(EventType::Market, EventType::Market);
        assert_ne!(EventType::Market, EventType::Order);

        // Test Eq
        assert!(EventType::Market.eq(&EventType::Market));
        assert!(!EventType::Market.eq(&EventType::Order));
    }

    #[test]
    fn test_order_side_alias() {
        // Test that OrderSide is properly aliased to Side
        let buy_side: OrderSide = OrderSide::Buy;
        let sell_side: OrderSide = OrderSide::Sell;

        assert_eq!(buy_side, OrderSide::Buy);
        assert_eq!(sell_side, OrderSide::Sell);
        assert_ne!(buy_side, sell_side);
    }

    #[test]
    fn test_trading_event_alias() {
        // Test that TradingEvent is properly aliased to Event
        let event: TradingEvent = Event::System(SystemEvent::Heartbeat {
            timestamp: Utc::now(),
            service: "test".to_string(),
            status: SystemStatus::Healthy,
        });

        assert_eq!(event.event_variant(), "SystemHeartbeat");
    }

    #[test]
    fn test_fill_event_comprehensive() -> Result<(), Box<dyn std::error::Error>> {
        let timestamp = Utc::now();
        let settlement_date = timestamp + Duration::days(2);

        let fill = FillEvent {
            fill_id: "comprehensive_fill".to_string(),
            order_id: OrderId::new(),
            symbol: Symbol::new("ETH-USD".to_string()),
            side: OrderSide::Buy,
            quantity: Quantity::from_f64(10.5)?,
            price: Price::from_f64(3200.0)?,
            timestamp,
            commission: Decimal::try_from(8.50).unwrap_or(Decimal::ZERO),
            slippage_bps: Decimal::try_from(0.5).unwrap_or(Decimal::ZERO),
            venue: Some("Kraken".to_string()),
            strategy_id: Some("defi_arbitrage".to_string()),
            counterparty: Some("market_maker_123".to_string()),
            settlement_date: Some(settlement_date),
        };

        assert_eq!(fill.fill_id, "comprehensive_fill");
        assert_eq!(fill.side, OrderSide::Buy);
        assert_eq!(fill.quantity.to_f64(), 10.5);
        assert_eq!(fill.price.to_f64(), 3200.0);
        assert_eq!(
            fill.commission,
            Decimal::try_from(8.50).unwrap_or(Decimal::ZERO)
        );
        assert_eq!(fill.venue, Some("Kraken".to_string()));
        assert_eq!(fill.strategy_id, Some("defi_arbitrage".to_string()));
        assert_eq!(fill.counterparty, Some("market_maker_123".to_string()));
        assert_eq!(fill.settlement_date, Some(settlement_date));
        Ok(())
    }

    #[test]
    fn test_event_serialization_deserialization() -> Result<(), Box<dyn std::error::Error>> {
        let timestamp = Utc::now();

        // Test Market event serialization
        let market_event = Event::Market(MarketEvent::Quote {
            symbol: test_symbol_1(),
            bid_price: Price::from_f64(150.0)?,
            bid_size: Quantity::from_f64(100.0)?,
            ask_price: Price::from_f64(150.05)?,
            ask_size: Quantity::from_f64(100.0)?,
            timestamp,
            venue: Some("NASDAQ".to_string()),
        });

        let json_str = serde_json::to_string(&market_event)
            .map_err(|e| anyhow!("Should serialize: {:?}", e))?;
        assert!(!json_str.is_empty());
        assert!(json_str.contains("Market"));
        assert!(json_str.contains("Quote"));

        let deserialized: Event =
            serde_json::from_str(&json_str).map_err(|e| anyhow!("Should deserialize: {:?}", e))?;
        assert_eq!(deserialized.event_type(), EventType::Market);

        // Test System event serialization
        let system_event = Event::System(SystemEvent::Error {
            timestamp,
            message: "Test error message".to_string(),
            severity: ErrorSeverity::Critical,
            service: "test_service".to_string(),
            error_code: Some("ERR_001".to_string()),
        });

        let json_str = serde_json::to_string(&system_event)
            .map_err(|e| anyhow!("Should serialize: {:?}", e))?;
        let deserialized: Event =
            serde_json::from_str(&json_str).map_err(|e| anyhow!("Should deserialize: {:?}", e))?;
        assert_eq!(deserialized.event_type(), EventType::System);

        // Test Order event serialization
        let order_event = Event::Order(OrderEvent {
            order_id: OrderId::new(),
            symbol: test_symbol_2(),
            order_type: OrderType::Limit,
            side: OrderSide::Buy,
            quantity: Quantity::from_f64(100.0)?,
            price: Some(Price::from_f64(300.0)?),
            timestamp,
            strategy_id: "value_strategy".to_string(),
            event_type: OrderEventType::Placed,
            previous_quantity: None,
            previous_price: None,
            reason: None,
        });

        let json_str = serde_json::to_string(&order_event)
            .map_err(|e| anyhow!("Should serialize: {:?}", e))?;
        let deserialized: Event =
            serde_json::from_str(&json_str).map_err(|e| anyhow!("Should deserialize: {:?}", e))?;
        assert_eq!(deserialized.event_type(), EventType::Order);
        Ok(())
    }

    #[test]
    fn test_event_queue_stress() -> Result<(), Box<dyn std::error::Error>> {
        let start_time = Utc::now();
        let mut queue = EventQueue::new(start_time);

        // Add many events
        let num_events = 10000;
        for i in 0..num_events {
            let event = Event::System(SystemEvent::Progress {
                timestamp: start_time + Duration::milliseconds(i),
                message: format!("Event {}", i),
                progress: Some((i % 101) as u8),
                service: "stress_test".to_string(),
            });
            queue.push(event, start_time + Duration::milliseconds(i));
        }

        assert_eq!(queue.len(), num_events as usize);

        // Pop all events and verify they come out in order
        let mut last_timestamp = start_time - Duration::seconds(1);
        let mut count = 0;

        while !queue.is_empty() {
            let (_event, timestamp) = queue.pop().ok_or("Queue empty during stress test")?;
            assert!(
                timestamp >= last_timestamp,
                "Events not in chronological order"
            );
            last_timestamp = timestamp;
            count += 1;
        }

        assert_eq!(count, num_events);
        assert!(queue.is_empty());
        Ok(())
    }

    #[test]
    fn test_complex_event_filtering_scenarios() {
        let symbol1 = Symbol::new(TEST_SYMBOL_3.to_string());
        let symbol2 = Symbol::new("META".to_string());
        let timestamp = Utc::now();

        // Create complex scenario with sentiment events
        let events = vec![
            Event::Market(MarketEvent::Sentiment {
                event_type: "merger_announcement".to_string(),
                description: "Amazon to acquire small tech company".to_string(),
                entities: vec![
                    TEST_SYMBOL_3.to_string(),
                    "Amazon".to_string(),
                    "TechCorp".to_string(),
                ],
                impact_score: 0.8,
                confidence: 0.9,
                timestamp,
            }),
            Event::Market(MarketEvent::Sentiment {
                event_type: "earnings_miss".to_string(),
                description: "Meta misses earnings expectations".to_string(),
                entities: vec!["META".to_string(), "Facebook".to_string()],
                impact_score: -0.6,
                confidence: 0.85,
                timestamp,
            }),
            Event::Risk(RiskEvent::ExposureLimitBreach {
                current_exposure: Decimal::try_from(500_000.0).unwrap_or(Decimal::ZERO),
                limit: Decimal::try_from(400_000.0).unwrap_or(Decimal::ZERO),
                timestamp,
                strategy_id: "multi_asset_momentum".to_string(),
            }),
        ];

        // Test symbol filtering with sentiment events (should match by entity)
        let symbol3_events = EventFilter::by_symbol(&events, &symbol1);
        assert_eq!(symbol3_events.len(), 1); // Sentiment event mentioning TEST_SYMBOL_3

        let meta_events = EventFilter::by_symbol(&events, &symbol2);
        assert_eq!(meta_events.len(), 1); // Sentiment event mentioning META

        // Test symbol filtering for non-mentioned symbol
        let other_symbol = Symbol::new("GOOG".to_string());
        let goog_events = EventFilter::by_symbol(&events, &other_symbol);
        assert_eq!(goog_events.len(), 0); // No events for GOOG
    }

    #[test]
    fn test_edge_cases_and_boundary_conditions() -> Result<(), Box<dyn std::error::Error>> {
        let timestamp = Utc::now();

        // Test empty strings and edge values
        let edge_fill = FillEvent {
            fill_id: "".to_string(), // Empty fill ID
            order_id: OrderId::new(),
            symbol: Symbol::new("".to_string()), // Empty symbol
            side: OrderSide::Buy,
            quantity: Quantity::from_f64(0.0)?, // Zero quantity
            price: Price::from_f64(0.0)?,       // Zero price
            timestamp,
            commission: Decimal::ZERO,
            slippage_bps: Decimal::ZERO,
            venue: Some("".to_string()),       // Empty venue
            strategy_id: Some("".to_string()), // Empty strategy
            counterparty: None,
            settlement_date: None,
        };

        assert_eq!(edge_fill.fill_id, "");
        assert_eq!(edge_fill.quantity.to_f64(), 0.0);
        assert_eq!(edge_fill.price.to_f64(), 0.0);

        // Test very large values
        let large_fill = FillEvent {
            fill_id: "a".repeat(1000), // Very long ID
            order_id: OrderId::new(),
            symbol: Symbol::new("SYMBOL".to_string()),
            side: OrderSide::Sell,
            quantity: Quantity::from_f64(1_000_000.0)?, // Use large but valid value instead of MAX
            price: Price::from_f64(f64::MAX)?,
            timestamp,
            commission: Decimal::MAX,
            slippage_bps: Decimal::MAX,
            venue: None,
            strategy_id: None,
            counterparty: None,
            settlement_date: None,
        };

        assert_eq!(large_fill.fill_id.len(), 1000);
        assert!(large_fill.quantity.to_f64() > 0.0);
        assert!(large_fill.price.to_f64() > 0.0);

        // Test very distant timestamps
        let distant_past = Utc
            .with_ymd_and_hms(1970, 1, 1, 0, 0, 0)
            .single()
            .ok_or("Invalid date")?;
        let distant_future = Utc
            .with_ymd_and_hms(2100, 12, 31, 23, 59, 59)
            .single()
            .ok_or("Invalid date")?;

        let past_event = Event::System(SystemEvent::Heartbeat {
            timestamp: distant_past,
            service: "ancient_service".to_string(),
            status: SystemStatus::Healthy,
        });

        let future_event = Event::System(SystemEvent::Heartbeat {
            timestamp: distant_future,
            service: "future_service".to_string(),
            status: SystemStatus::Healthy,
        });

        assert_eq!(past_event.timestamp(), Some(distant_past));
        assert_eq!(future_event.timestamp(), Some(distant_future));
        Ok(())
    }

    #[test]
    fn test_event_queue_with_identical_timestamps() -> Result<(), Box<dyn std::error::Error>> {
        let start_time = Utc::now();
        let mut queue = EventQueue::new(start_time);

        // Add multiple events with identical timestamps
        let same_timestamp = start_time + Duration::seconds(10);

        for i in 0..5 {
            let event = Event::System(SystemEvent::Progress {
                timestamp: same_timestamp,
                message: format!("Same time event {}", i),
                progress: Some(i as u8 * 20),
                service: format!("service_{}", i),
            });
            queue.push(event, same_timestamp);
        }

        assert_eq!(queue.len(), 5);

        // All events should have the same timestamp when popped
        let mut popped_count = 0;
        while !queue.is_empty() {
            let (_, timestamp) = queue.pop().ok_or("Queue empty during ordering test")?;
            assert_eq!(timestamp, same_timestamp);
            popped_count += 1;
        }

        assert_eq!(popped_count, 5);
        Ok(())
    }
}
