//! Comprehensive Performance Metrics - CANONICAL SINGLE SOURCE OF TRUTH
//!
//! This module provides the unified performance metrics for the entire Foxhunt system.
//! ALL services, crates, and components MUST use these consolidated types.
//!
//! # Architecture
//! - **Comprehensive Coverage**: Financial, ML, System, and Risk metrics
//! - **Domain Flexibility**: Optional fields for domain-specific metrics
//! - **Type Safety**: Consistent types across all usage patterns
//! - **Serialization**: Full serde support for API and storage
//!
//! # Usage
//! ``rust
//! use types::performance::*;
//!
//! let metrics = PerformanceMetrics {
//!     // Basic financial metrics
//!     total_return: Some(0.15),
//!     sharpe_ratio: Some(1.8),
//!     
//!     // ML metrics (when applicable)
//!     ml_confidence: Some(0.85),
//!     prediction_accuracy: Some(0.92),
//!     
//!     // System metrics (when applicable)
//!     average_latency_us: Some(150),
//!     throughput_pps: Some(10000),
//!     
//!     ..Default::default()
//! };
//! ``

use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;

// ============================================================================
// COMPREHENSIVE PERFORMANCE METRICS - SINGLE SOURCE OF TRUTH
// ============================================================================

/// Comprehensive performance metrics covering all domains in Foxhunt
///
/// This `struct` unifies metrics from:
/// - Financial Trading: Returns, ratios, drawdown, trading statistics
/// - `ML` Models: Accuracy, confidence, feature importance, model performance
/// - System Performance: Latency, throughput, resource utilization
/// - Risk Management: `VaR`, `CVaR`, correlations, factor exposures
///
/// All fields are optional to allow domain-specific usage without bloating
/// individual use cases. Services should populate only relevant fields.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[allow(missing_docs)]
#[derive(Default)]
/// `PerformanceMetrics` component.
pub struct PerformanceMetrics {
    // ========================================================================
    // BASIC PERFORMANCE METRICS - Core Financial Performance
    // ========================================================================
    /// Total return as a decimal (0.15 = 15% return)
    pub total_return: Option<f64>,

    /// Annualized return as a decimal
    pub annualized_return: Option<f64>,

    /// Total number of trades executed
    pub total_trades: Option<usize>,

    /// Number of winning/profitable trades
    pub winning_trades: Option<usize>,

    /// Number of losing trades
    pub losing_trades: Option<usize>,

    // ========================================================================
    // RISK METRICS - Risk Analysis and Drawdown
    // ========================================================================
    /// Maximum drawdown as negative decimal (-0.15 = 15% drawdown)
    pub maximum_drawdown: Option<f64>,

    /// `Duration` of maximum drawdown period in days
    pub max_drawdown_duration_days: Option<u64>,

    /// Annualized volatility (standard deviation of returns)
    pub volatility: Option<f64>,

    /// Downside volatility (volatility of negative returns only)
    pub downside_deviation: Option<f64>,

    /// Value at Risk at 95% confidence level
    pub value_at_risk: Option<f64>,

    /// Conditional Value at Risk (Expected Shortfall) at 95%
    pub conditional_value_at_risk: Option<f64>,

    // ========================================================================
    // RATIO METRICS - Risk-Adjusted Performance Ratios
    // ========================================================================
    /// Sharpe ratio (excess return / volatility)
    pub sharpe_ratio: Option<f64>,

    /// Sortino ratio (excess return / downside deviation)
    pub sortino_ratio: Option<f64>,

    /// Calmar ratio (annual return / max drawdown)
    pub calmar_ratio: Option<f64>,

    /// Information ratio (active return / tracking error)
    pub information_ratio: Option<f64>,

    /// Treynor ratio (excess return / beta)
    pub treynor_ratio: Option<f64>,

    // ========================================================================
    // TRADING METRICS - Trade-Level Performance Analysis
    // ========================================================================
    /// Win rate as decimal (0.55 = 55% win rate)
    pub win_rate: Option<f64>,

    /// Profit factor (gross profit / gross loss)
    pub profit_factor: Option<f64>,

    /// Average winning trade amount
    pub average_win: Option<f64>,

    /// Average losing trade amount (negative value)
    pub average_loss: Option<f64>,

    /// Mathematical expectancy per trade
    pub expectancy: Option<f64>,

    /// Kelly Criterion optimal position size
    pub kelly_criterion: Option<f64>,

    // ========================================================================
    // ML-SPECIFIC METRICS - Machine Learning Model Performance
    // ========================================================================
    /// Overall model confidence (0.0 to 1.0)
    pub ml_confidence: Option<f64>,

    /// Prediction accuracy rate (0.0 to 1.0)
    pub prediction_accuracy: Option<f64>,

    /// Feature importance scores by feature name
    pub feature_importance: Option<HashMap<String, f64>>,

    /// Cross-validation scores from model training
    pub cross_validation_scores: Option<Vec<f64>>,

    /// Model inference statistics
    pub total_inferences: Option<u64>,

    /// Average model inference time in microseconds
    pub average_inference_latency_us: Option<u64>,

    /// Model error rate (errors per inference)
    pub model_error_rate: Option<f64>,

    // ========================================================================
    // SYSTEM PERFORMANCE METRICS - Infrastructure and Latency
    // ========================================================================
    /// Average system latency in microseconds
    pub average_latency_us: Option<u64>,

    /// Maximum observed latency in microseconds
    pub max_latency_us: Option<u64>,

    /// Minimum observed latency in microseconds
    pub min_latency_us: Option<u64>,

    /// System throughput in operations per second
    pub throughput_pps: Option<u64>,

    /// Current memory usage in bytes
    pub memory_usage_bytes: Option<u64>,

    /// `CPU` utilization as percentage (0.0 to 100.0)
    pub cpu_utilization_percent: Option<f64>,

    /// System error rate (errors per operation)
    pub error_rate: Option<f64>,

    /// System uptime in seconds
    pub uptime_seconds: Option<u64>,

    // ========================================================================
    // EXTENDED FINANCIAL METRICS - Advanced Financial Analysis
    // ========================================================================
    /// Beta coefficient (systematic risk measure)
    pub beta: Option<f64>,

    /// Alpha coefficient (excess return measure)
    pub alpha: Option<f64>,

    /// Correlation with benchmark (-1.0 to 1.0)
    pub correlation: Option<f64>,

    /// Tracking error (standard deviation of excess returns)
    pub tracking_error: Option<f64>,

    /// Statistical significance of performance
    pub statistical_significance: Option<f64>,

    /// Recovery factor (total return / max drawdown)
    pub recovery_factor: Option<f64>,

    // ========================================================================
    // ADVANCED RISK METRICS - Sophisticated Risk Analysis
    // ========================================================================
    /// Value at Risk at 99% confidence level
    pub var_99: Option<f64>,

    /// Conditional `VaR` at 99% confidence level
    pub cvar_99: Option<f64>,

    /// Return distribution skewness
    pub skewness: Option<f64>,

    /// Return distribution kurtosis (tail heaviness)
    pub kurtosis: Option<f64>,

    /// Tail ratio (95th percentile / 5th percentile)
    pub tail_ratio: Option<f64>,

    /// Portfolio concentration risk (Herfindahl index)
    pub concentration_risk: Option<f64>,

    // ========================================================================
    // OPERATIONAL METRICS - Trading Operations and Execution
    // ========================================================================
    /// Average trade duration in seconds
    pub average_trade_duration_seconds: Option<f64>,

    /// Largest winning trade
    pub largest_win: Option<f64>,

    /// Largest losing trade
    pub largest_loss: Option<f64>,

    /// Trade frequency (trades per day)
    pub trades_per_day: Option<f64>,

    /// Total commission costs
    pub total_commission: Option<f64>,

    /// Total slippage costs
    pub total_slippage: Option<f64>,

    /// Average market impact per trade
    pub average_market_impact: Option<f64>,

    // ========================================================================
    // METADATA - Tracking and Context Information
    // ========================================================================
    /// When these metrics were calculated
    pub calculation_timestamp: Option<DateTime<Utc>>,

    /// Time period these metrics cover (start)
    pub period_start: Option<DateTime<Utc>>,

    /// Time period these metrics cover (end)
    pub period_end: Option<DateTime<Utc>>,

    /// Identifier for the strategy/model that produced these metrics
    pub source_identifier: Option<String>,

    /// Number of data points used in calculations
    pub data_points_count: Option<usize>,

    /// Any warnings generated during calculation
    pub calculation_warnings: Option<Vec<String>>,
}

// ============================================================================
// SPECIALIZED METRICS STRUCTS - Domain-Specific Convenience
// ============================================================================

/// Financial performance metrics subset for trading and backtesting
#[derive(Debug, Clone, Serialize, Deserialize)]
#[allow(missing_docs)]
/// `FinancialMetrics` component.
pub struct FinancialMetrics {
    /// Total Return
    pub total_return: f64,
    /// Annualized Return
    pub annualized_return: f64,
    /// Sharpe Ratio
    pub sharpe_ratio: f64,
    /// Maximum Drawdown
    pub maximum_drawdown: f64,
    /// Win Rate
    pub win_rate: f64,
    /// Total Trades
    pub total_trades: usize,
    /// Profit Factor
    pub profit_factor: f64,
    /// Volatility
    pub volatility: f64,
}

/// `ML` model performance metrics subset
#[derive(Debug, Clone, Serialize, Deserialize)]
#[allow(missing_docs)]
/// `MLMetrics` component.
pub struct MLMetrics {
    /// Prediction Accuracy
    pub prediction_accuracy: f64,
    /// Ml Confidence
    pub ml_confidence: f64,
    /// Feature Importance
    pub feature_importance: HashMap<String, f64>,
    /// Total Inferences
    pub total_inferences: u64,
    /// Average Inference Latency Us
    pub average_inference_latency_us: u64,
    /// Model Error Rate
    pub model_error_rate: f64,
}

/// System performance metrics subset for infrastructure monitoring
#[derive(Debug, Clone, Serialize, Deserialize)]
#[allow(missing_docs)]
/// `SystemMetrics` component.
pub struct SystemMetrics {
    /// Average Latency Us
    pub average_latency_us: u64,
    /// Throughput Pps
    pub throughput_pps: u64,
    /// Memory Usage Bytes
    pub memory_usage_bytes: u64,
    /// Cpu Utilization Percent
    pub cpu_utilization_percent: f64,
    /// Error Rate
    pub error_rate: f64,
    /// Uptime Seconds
    pub uptime_seconds: u64,
}

impl SystemMetrics {
    /// Creates a new SystemMetrics instance with default values
    pub fn new() -> Self {
        Self {
            average_latency_us: 0,
            throughput_pps: 0,
            memory_usage_bytes: 0,
            cpu_utilization_percent: 0.0,
            error_rate: 0.0,
            uptime_seconds: 0,
        }
    }
}

/// Risk management metrics subset
#[derive(Debug, Clone, Serialize, Deserialize)]
#[allow(missing_docs)]
/// `RiskMetrics` component.
pub struct RiskMetrics {
    /// Value At Risk
    pub value_at_risk: f64,
    /// Conditional Value At Risk
    pub conditional_value_at_risk: f64,
    /// Maximum Drawdown
    pub maximum_drawdown: f64,
    /// Volatility
    pub volatility: f64,
    /// Beta
    pub beta: Option<f64>,
    /// Correlation
    pub correlation: Option<f64>,
}

// ============================================================================
// CONVERSION IMPLEMENTATIONS - Easy Migration from Legacy Types
// ============================================================================

impl From<FinancialMetrics> for PerformanceMetrics {
    fn from(financial: FinancialMetrics) -> Self {
        Self {
            total_return: Some(financial.total_return),
            annualized_return: Some(financial.annualized_return),
            sharpe_ratio: Some(financial.sharpe_ratio),
            maximum_drawdown: Some(financial.maximum_drawdown),
            win_rate: Some(financial.win_rate),
            total_trades: Some(financial.total_trades),
            profit_factor: Some(financial.profit_factor),
            volatility: Some(financial.volatility),
            ..Default::default()
        }
    }
}

impl From<MLMetrics> for PerformanceMetrics {
    fn from(ml: MLMetrics) -> Self {
        Self {
            prediction_accuracy: Some(ml.prediction_accuracy),
            ml_confidence: Some(ml.ml_confidence),
            feature_importance: Some(ml.feature_importance),
            total_inferences: Some(ml.total_inferences),
            average_inference_latency_us: Some(ml.average_inference_latency_us),
            model_error_rate: Some(ml.model_error_rate),
            ..Default::default()
        }
    }
}

impl From<SystemMetrics> for PerformanceMetrics {
    fn from(system: SystemMetrics) -> Self {
        Self {
            average_latency_us: Some(system.average_latency_us),
            throughput_pps: Some(system.throughput_pps),
            memory_usage_bytes: Some(system.memory_usage_bytes),
            cpu_utilization_percent: Some(system.cpu_utilization_percent),
            error_rate: Some(system.error_rate),
            uptime_seconds: Some(system.uptime_seconds),
            ..Default::default()
        }
    }
}

impl From<RiskMetrics> for PerformanceMetrics {
    fn from(risk: RiskMetrics) -> Self {
        Self {
            value_at_risk: Some(risk.value_at_risk),
            conditional_value_at_risk: Some(risk.conditional_value_at_risk),
            maximum_drawdown: Some(risk.maximum_drawdown),
            volatility: Some(risk.volatility),
            beta: risk.beta,
            correlation: risk.correlation,
            ..Default::default()
        }
    }
}

// ============================================================================
// DEFAULT IMPLEMENTATIONS
// ============================================================================

// ============================================================================
// UTILITY IMPLEMENTATIONS
// ============================================================================

impl PerformanceMetrics {
    /// Create a new `PerformanceMetrics` with `timestamp`
    #[must_use]
    pub fn new() -> Self {
        Self {
            calculation_timestamp: Some(Utc::now()),
            ..Default::default()
        }
    }

    /// Create metrics with a specific source identifier
    #[must_use]
    pub fn with_source(source: String) -> Self {
        Self {
            calculation_timestamp: Some(Utc::now()),
            source_identifier: Some(source),
            ..Default::default()
        }
    }

    /// Add a warning message to the metrics
    pub fn add_warning(&mut self, warning: String) {
        self.calculation_warnings
            .get_or_insert_with(Vec::new)
            .push(warning);
    }

    /// Set the period these metrics cover
    pub fn set_period(&mut self, start: DateTime<Utc>, end: DateTime<Utc>) {
        self.period_start = Some(start);
        self.period_end = Some(end);
    }

    /// Extract financial metrics subset
    #[must_use]
    pub fn to_financial_metrics(&self) -> Option<FinancialMetrics> {
        Some(FinancialMetrics {
            total_return: self.total_return?,
            annualized_return: self.annualized_return?,
            sharpe_ratio: self.sharpe_ratio?,
            maximum_drawdown: self.maximum_drawdown?,
            win_rate: self.win_rate?,
            total_trades: self.total_trades?,
            profit_factor: self.profit_factor?,
            volatility: self.volatility?,
        })
    }

    /// Extract `ML` metrics subset
    #[must_use]
    pub fn to_ml_metrics(&self) -> Option<MLMetrics> {
        Some(MLMetrics {
            prediction_accuracy: self.prediction_accuracy?,
            ml_confidence: self.ml_confidence?,
            feature_importance: self.feature_importance.clone()?,
            total_inferences: self.total_inferences?,
            average_inference_latency_us: self.average_inference_latency_us?,
            model_error_rate: self.model_error_rate?,
        })
    }

    /// Extract system metrics subset
    #[must_use]
    pub fn to_system_metrics(&self) -> Option<SystemMetrics> {
        Some(SystemMetrics {
            average_latency_us: self.average_latency_us?,
            throughput_pps: self.throughput_pps?,
            memory_usage_bytes: self.memory_usage_bytes?,
            cpu_utilization_percent: self.cpu_utilization_percent?,
            error_rate: self.error_rate?,
            uptime_seconds: self.uptime_seconds?,
        })
    }

    /// Check if this metrics instance contains financial data
    #[must_use]
    pub const fn has_financial_metrics(&self) -> bool {
        self.total_return.is_some() || self.sharpe_ratio.is_some() || self.win_rate.is_some()
    }

    /// Check if this metrics instance contains `ML` data
    #[must_use]
    pub const fn has_ml_metrics(&self) -> bool {
        self.prediction_accuracy.is_some()
            || self.ml_confidence.is_some()
            || self.feature_importance.is_some()
    }

    /// Check if this metrics instance contains system performance data
    #[must_use]
    pub const fn has_system_metrics(&self) -> bool {
        self.average_latency_us.is_some()
            || self.throughput_pps.is_some()
            || self.memory_usage_bytes.is_some()
    }
}

// Use PerformanceMetrics directly

impl PerformanceMetrics {
    // ========================================================================
    // Core Performance Metrics Implementation
    // ========================================================================

    /// Get `total_return` with default value of 0.0
    #[must_use]
    pub fn total_return_or_zero(&self) -> f64 {
        self.total_return.unwrap_or(0.0)
    }

    /// Get `annualized_return` with default value of 0.0
    #[must_use]
    pub fn annualized_return_or_zero(&self) -> f64 {
        self.annualized_return.unwrap_or(0.0)
    }

    /// Get `sharpe_ratio` with default value of 0.0
    #[must_use]
    pub fn sharpe_ratio_or_zero(&self) -> f64 {
        self.sharpe_ratio.unwrap_or(0.0)
    }

    /// Get `sortino_ratio` with default value of 0.0
    #[must_use]
    pub fn sortino_ratio_or_zero(&self) -> f64 {
        self.sortino_ratio.unwrap_or(0.0)
    }

    /// Get `calmar_ratio` with default value of 0.0
    #[must_use]
    pub fn calmar_ratio_or_zero(&self) -> f64 {
        self.calmar_ratio.unwrap_or(0.0)
    }

    /// Get `maximum_drawdown` with default value of 0.0
    #[must_use]
    pub fn max_drawdown(&self) -> f64 {
        self.maximum_drawdown.unwrap_or(0.0)
    }

    /// Get `maximum_drawdown_duration_days` as `u32` with default value of 0
    #[must_use]
    pub fn max_drawdown_duration_days(&self) -> u32 {
        self.max_drawdown_duration_days.map_or(0, |d| d as u32)
    }

    /// Get `win_rate` with default value of 0.0
    #[must_use]
    pub fn win_rate_or_zero(&self) -> f64 {
        self.win_rate.unwrap_or(0.0)
    }

    /// Get `profit_factor` with default value of 0.0
    #[must_use]
    pub fn profit_factor_or_zero(&self) -> f64 {
        self.profit_factor.unwrap_or(0.0)
    }

    /// Get volatility with default value of 0.0
    #[must_use]
    pub fn volatility_or_zero(&self) -> f64 {
        self.volatility.unwrap_or(0.0)
    }

    /// Get `information_ratio` with default value of 0.0
    #[must_use]
    pub fn information_ratio_or_zero(&self) -> f64 {
        self.information_ratio.unwrap_or(0.0)
    }

    /// Get `treynor_ratio` with default value of 0.0
    #[must_use]
    pub fn treynor_ratio_or_zero(&self) -> f64 {
        self.treynor_ratio.unwrap_or(0.0)
    }

    /// Get beta with default value of 0.0
    #[must_use]
    pub fn beta_or_zero(&self) -> f64 {
        self.beta.unwrap_or(0.0)
    }

    /// Get `tracking_error` with default value of 0.0
    #[must_use]
    pub fn tracking_error_or_zero(&self) -> f64 {
        self.tracking_error.unwrap_or(0.0)
    }

    /// Get `total_trades` with default value of 0
    #[must_use]
    pub fn total_trades_or_zero(&self) -> usize {
        self.total_trades.unwrap_or(0)
    }

    /// Get `winning_trades` with default value of 0
    #[must_use]
    pub fn profitable_trades(&self) -> usize {
        self.winning_trades.unwrap_or(0)
    }

    /// Get `losing_trades` with default value of 0
    #[must_use]
    pub fn losing_trades_count(&self) -> usize {
        self.losing_trades.unwrap_or(0)
    }

    /// Get `largest_win` with default value of 0.0
    #[must_use]
    pub fn largest_win_or_zero(&self) -> f64 {
        self.largest_win.unwrap_or(0.0)
    }

    /// Get `largest_loss` with default value of 0.0
    #[must_use]
    pub fn largest_loss_or_zero(&self) -> f64 {
        self.largest_loss.unwrap_or(0.0)
    }

    /// Get `recovery_factor` with default value of 0.0
    #[must_use]
    pub fn recovery_factor_or_zero(&self) -> f64 {
        self.recovery_factor.unwrap_or(0.0)
    }

    /// Set basic financial metrics - helper for migration
    pub fn set_basic_financial_metrics(
        &mut self,
        total_return: f64,
        annualized_return: f64,
        sharpe_ratio: f64,
        max_drawdown: f64,
        win_rate: f64,
        profit_factor: f64,
        total_trades: usize,
    ) {
        self.total_return = Some(total_return);
        self.annualized_return = Some(annualized_return);
        self.sharpe_ratio = Some(sharpe_ratio);
        self.maximum_drawdown = Some(max_drawdown);
        self.win_rate = Some(win_rate);
        self.profit_factor = Some(profit_factor);
        self.total_trades = Some(total_trades);
    }

    /// Set additional ratios - helper for migration
    pub fn set_additional_ratios(
        &mut self,
        sortino_ratio: f64,
        calmar_ratio: f64,
        information_ratio: f64,
        treynor_ratio: f64,
    ) {
        self.sortino_ratio = Some(sortino_ratio);
        self.calmar_ratio = Some(calmar_ratio);
        self.information_ratio = Some(information_ratio);
        self.treynor_ratio = Some(treynor_ratio);
    }
}

#[cfg(test)]
// FORCIBLY ENABLED: Aggressive enablement for 100% completion
mod tests {
    use super::*;
    use std::collections::HashMap;
    // use crate::operations; // Available if needed

    #[test]
    fn test_default_performance_metrics() {
        let metrics = PerformanceMetrics::default();
        assert!(metrics.total_return.is_none());
        assert!(metrics.sharpe_ratio.is_none());
        assert!(metrics.calculation_timestamp.is_none());
    }

    #[test]
    fn test_new_performance_metrics() {
        let metrics = PerformanceMetrics::new();
        assert!(metrics.calculation_timestamp.is_some());
        assert!(metrics.total_return.is_none());
    }

    #[test]
    fn test_with_source() {
        let metrics = PerformanceMetrics::with_source("test_strategy".to_string());
        assert_eq!(metrics.source_identifier, Some("test_strategy".to_string()));
        assert!(metrics.calculation_timestamp.is_some());
    }

    #[test]
    fn test_add_warning() {
        let mut metrics = PerformanceMetrics::new();
        metrics.add_warning("Test warning".to_string());

        assert_eq!(
            metrics.calculation_warnings,
            Some(vec!["Test warning".to_string()])
        );
    }

    #[test]
    fn test_financial_conversion() {
        let financial = FinancialMetrics {
            total_return: 0.15,
            annualized_return: 0.12,
            sharpe_ratio: 1.5,
            maximum_drawdown: -0.10,
            win_rate: 0.65,
            total_trades: 100,
            profit_factor: 1.8,
            volatility: 0.20,
        };

        let metrics: PerformanceMetrics = financial.into();
        assert_eq!(metrics.total_return, Some(0.15));
        assert_eq!(metrics.sharpe_ratio, Some(1.5));
        assert_eq!(metrics.total_trades, Some(100));
    }

    #[test]
    fn test_ml_conversion() {
        let mut feature_importance = HashMap::new();
        feature_importance.insert("feature1".to_string(), 0.6);
        feature_importance.insert("feature2".to_string(), 0.4);

        let ml = MLMetrics {
            prediction_accuracy: 0.92,
            ml_confidence: 0.85,
            feature_importance,
            total_inferences: 1000,
            average_inference_latency_us: 150,
            model_error_rate: 0.08,
        };

        let metrics: PerformanceMetrics = ml.into();
        assert_eq!(metrics.prediction_accuracy, Some(0.92));
        assert_eq!(metrics.ml_confidence, Some(0.85));
        assert!(metrics.feature_importance.is_some());
    }

    #[test]
    fn test_metric_type_detection() {
        let mut metrics = PerformanceMetrics::new();

        // Test financial detection
        metrics.total_return = Some(0.15);
        assert!(metrics.has_financial_metrics());
        assert!(!metrics.has_ml_metrics());
        assert!(!metrics.has_system_metrics());

        // Add ML metrics
        metrics.prediction_accuracy = Some(0.90);
        assert!(metrics.has_ml_metrics());

        // Add system metrics
        metrics.average_latency_us = Some(100);
        assert!(metrics.has_system_metrics());
    }

    #[test]
    fn test_period_setting() {
        let mut metrics = PerformanceMetrics::new();
        let start = Utc::now();
        let end = start + Duration::days(30);

        metrics.set_period(start, end);
        assert_eq!(metrics.period_start, Some(start));
        assert_eq!(metrics.period_end, Some(end));
    }

    #[test]
    fn test_financial_extraction() -> Result<(), Box<dyn std::error::Error>> {
        let mut metrics = PerformanceMetrics::new();
        metrics.total_return = Some(0.15);
        metrics.sharpe_ratio = Some(1.5);
        metrics.total_trades = Some(100);
        metrics.win_rate = Some(0.65);
        metrics.profit_factor = Some(1.8);
        metrics.volatility = Some(0.20);
        metrics.maximum_drawdown = Some(-0.10);
        metrics.annualized_return = Some(0.12);

        let financial = metrics
            .to_financial_metrics()
            .ok_or("Failed to convert to financial metrics")?;
        assert_eq!(financial.total_return, 0.15);
        assert_eq!(financial.sharpe_ratio, 1.5);
        assert_eq!(financial.total_trades, 100);
        Ok(())
    }
}

// ============================================================================
// BENCHMARK RESULTS - CANONICAL HFT PERFORMANCE BENCHMARKING
// ============================================================================

/// Comprehensive `HFT` system benchmark results
///
/// `BenchmarkResults` provides the canonical structure for measuring and reporting
/// `HFT` system performance across all critical dimensions: latency, throughput,
/// resource utilization, and overall system health.
///
/// This is the single source of truth for benchmark reporting used by:
/// - Performance monitoring systems
/// - Load testing frameworks  
/// - Production health dashboards
/// - Capacity planning systems
#[derive(Debug, Clone, Serialize, Deserialize)]
/// BenchmarkResults
/// 
/// Auto-generated documentation placeholder - enhance with specifics
pub struct BenchmarkResults {
    /// Order processing latency statistics
    pub order_processing: LatencyStats,
    /// Risk checking latency statistics
    pub risk_checking: LatencyStats,
    /// Market data processing latency statistics
    pub market_data: LatencyStats,
    /// Database query performance statistics
    pub database_queries: LatencyStats,
    /// Memory usage statistics
    pub memory_usage: MemoryStats,
    /// `CPU` utilization statistics
    pub cpu_utilization: CpuStats,
    /// Network performance statistics
    pub network_performance: NetworkStats,
    /// Overall performance grade
    pub overall_grade: PerformanceGrade,
    /// Benchmark execution timestamp
    pub timestamp: DateTime<Utc>,
    /// Test configuration and environment
    pub test_metadata: HashMap<String, String>,
}

/// General performance grade
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
/// PerformanceGrade
/// 
/// Auto-generated documentation placeholder - enhance with specifics
pub enum PerformanceGrade {
    // Excellent variant
    Excellent,
    // Good variant
    Good,
    // Average variant
    Average,
    // BelowAverage variant
    BelowAverage,
    // Poor variant
    Poor,
}

/// Detailed latency statistics for `HFT` performance measurement
#[derive(Debug, Clone, Serialize, Deserialize)]
/// LatencyStats
/// 
/// Auto-generated documentation placeholder - enhance with specifics
pub struct LatencyStats {
    /// Mean latency in microseconds
    pub mean_us: f64,
    /// Median latency in microseconds
    pub median_us: f64,
    /// 95th percentile latency in microseconds
    pub p95_us: f64,
    /// 99th percentile latency in microseconds
    pub p99_us: f64,
    /// 99.9th percentile latency in microseconds
    pub p99_9_us: f64,
    /// Minimum observed latency in microseconds
    pub min_us: f64,
    /// Maximum observed latency in microseconds
    pub max_us: f64,
    /// Standard deviation of latency in microseconds
    pub std_dev_us: f64,
    /// Number of samples measured
    pub samples: usize,
    /// Whether performance target was met
    pub target_met: bool,
    /// Target latency threshold in microseconds
    pub target_threshold_us: Option<f64>,
}

/// Memory usage statistics
#[derive(Debug, Clone, Serialize, Deserialize)]
/// MemoryStats
/// 
/// Auto-generated documentation placeholder - enhance with specifics
pub struct MemoryStats {
    /// Total memory allocated in bytes
    pub total_allocated_bytes: u64,
    /// Peak memory usage in bytes
    pub peak_usage_bytes: u64,
    /// Current memory usage in bytes
    pub current_usage_bytes: u64,
    /// Memory allocation rate in bytes per second
    pub allocation_rate_bps: f64,
    /// Garbage collection pause times in microseconds
    pub gc_pause_times_us: Vec<f64>,
    /// Memory fragmentation percentage
    pub fragmentation_percent: f64,
}

/// `CPU` utilization statistics
#[derive(Debug, Clone, Serialize, Deserialize)]
/// CpuStats
/// 
/// Auto-generated documentation placeholder - enhance with specifics
pub struct CpuStats {
    /// Average `CPU` utilization percentage
    pub average_utilization_percent: f64,
    /// Peak `CPU` utilization percentage
    pub peak_utilization_percent: f64,
    /// `CPU` utilization samples over time
    pub utilization_samples: Vec<f64>,
    /// Context switches per second
    pub context_switches_per_sec: f64,
    /// `CPU` cycles per instruction
    pub cycles_per_instruction: f64,
    /// `CPU` cache hit rate percentage
    pub cache_hit_rate_percent: f64,
}

/// Network performance statistics
#[derive(Debug, Clone, Serialize, Deserialize)]
/// NetworkStats
/// 
/// Auto-generated documentation placeholder - enhance with specifics
pub struct NetworkStats {
    /// Network throughput in bytes per second
    pub throughput_bps: u64,
    /// Packet loss percentage
    pub packet_loss_percent: f64,
    /// Round-trip time in microseconds
    pub rtt_us: f64,
    /// Jitter in microseconds
    pub jitter_us: f64,
    /// Connection establishment time in microseconds
    pub connection_time_us: f64,
    /// Number of active connections
    pub active_connections: usize,
}

impl BenchmarkResults {
    /// Create new benchmark results
    #[must_use]
    pub fn new() -> Self {
        Self {
            order_processing: LatencyStats::default(),
            risk_checking: LatencyStats::default(),
            market_data: LatencyStats::default(),
            database_queries: LatencyStats::default(),
            memory_usage: MemoryStats::default(),
            cpu_utilization: CpuStats::default(),
            network_performance: NetworkStats::default(),
            overall_grade: PerformanceGrade::Average,
            timestamp: Utc::now(),
            test_metadata: HashMap::new(),
        }
    }

    /// Check if all performance targets were met
    #[must_use]
    pub const fn all_targets_met(&self) -> bool {
        self.order_processing.target_met
            && self.risk_checking.target_met
            && self.market_data.target_met
            && self.database_queries.target_met
    }

    /// Calculate overall performance score (0-100)
    #[must_use]
    pub const fn performance_score(&self) -> f64 {
        match self.overall_grade {
            PerformanceGrade::Excellent => 95.0,
            PerformanceGrade::Good => 80.0,
            PerformanceGrade::Average => 65.0,
            PerformanceGrade::BelowAverage => 45.0,
            PerformanceGrade::Poor => 25.0,
        }
    }
}

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

impl Default for LatencyStats {
    fn default() -> Self {
        Self {
            mean_us: 0.0,
            median_us: 0.0,
            p95_us: 0.0,
            p99_us: 0.0,
            p99_9_us: 0.0,
            min_us: 0.0,
            max_us: 0.0,
            std_dev_us: 0.0,
            samples: 0,
            target_met: false,
            target_threshold_us: None,
        }
    }
}

impl Default for MemoryStats {
    fn default() -> Self {
        Self {
            total_allocated_bytes: 0,
            peak_usage_bytes: 0,
            current_usage_bytes: 0,
            allocation_rate_bps: 0.0,
            gc_pause_times_us: Vec::new(),
            fragmentation_percent: 0.0,
        }
    }
}

impl Default for CpuStats {
    fn default() -> Self {
        Self {
            average_utilization_percent: 0.0,
            peak_utilization_percent: 0.0,
            utilization_samples: Vec::new(),
            context_switches_per_sec: 0.0,
            cycles_per_instruction: 0.0,
            cache_hit_rate_percent: 0.0,
        }
    }
}

impl Default for NetworkStats {
    fn default() -> Self {
        Self {
            throughput_bps: 0,
            packet_loss_percent: 0.0,
            rtt_us: 0.0,
            jitter_us: 0.0,
            connection_time_us: 0.0,
            active_connections: 0,
        }
    }
}

// ========================================================================
// Constructor Tests
// ========================================================================

#[test]
fn test_new_performance_metrics_with_timestamp() {
    let metrics = PerformanceMetrics::new();
    assert!(metrics.calculation_timestamp.is_some());
    assert!(metrics.source_identifier.is_none());
}

#[test]
fn test_performance_metrics_with_source() {
    let source = "test_source".to_string();
    let metrics = PerformanceMetrics::with_source(source.clone());
    assert!(metrics.calculation_timestamp.is_some());
    assert_eq!(metrics.source_identifier, Some(source));
}

#[test]
fn test_add_warning_to_empty() -> Result<(), Box<dyn std::error::Error>> {
    let mut metrics = PerformanceMetrics::default();
    metrics.add_warning("Warning 1".to_string());

    assert!(metrics.calculation_warnings.is_some());
    let warnings = metrics.calculation_warnings.ok_or("Missing warnings")?;
    assert_eq!(warnings.len(), 1);
    assert_eq!(warnings[0], "Warning 1");
    Ok(())
}

#[test]
fn test_add_multiple_warnings() -> Result<(), Box<dyn std::error::Error>> {
    let mut metrics = PerformanceMetrics::default();
    metrics.add_warning("Warning 1".to_string());
    metrics.add_warning("Warning 2".to_string());

    let warnings = metrics.calculation_warnings.ok_or("Missing warnings")?;
    assert_eq!(warnings.len(), 2);
    assert_eq!(warnings[0], "Warning 1");
    assert_eq!(warnings[1], "Warning 2");
    Ok(())
}

#[test]
fn test_set_period() {
    let mut metrics = PerformanceMetrics::default();
    let start = Utc::now() - Duration::days(30);
    let end = Utc::now();

    metrics.set_period(start, end);
    assert_eq!(metrics.period_start, Some(start));
    assert_eq!(metrics.period_end, Some(end));
}

// ========================================================================
// Extraction Method Tests
// ========================================================================

#[test]
fn test_to_financial_metrics_none() {
    let metrics = PerformanceMetrics::default();
    assert!(metrics.to_financial_metrics().is_none());
}

#[test]
fn test_to_financial_metrics_some() -> Result<(), Box<dyn std::error::Error>> {
    let metrics = PerformanceMetrics {
        total_return: Some(0.15),
        annualized_return: Some(0.12),
        sharpe_ratio: Some(1.8),
        maximum_drawdown: Some(0.05),
        win_rate: Some(0.65),
        total_trades: Some(100),
        profit_factor: Some(1.5),
        volatility: Some(0.08),
        ..Default::default()
    };

    let financial = metrics
        .to_financial_metrics()
        .ok_or("Failed to convert to financial metrics")?;
    assert_eq!(financial.total_return, 0.15);
    assert_eq!(financial.sharpe_ratio, 1.8);
    assert_eq!(financial.win_rate, 0.65);
    assert_eq!(financial.total_trades, 100);
    Ok(())
}

#[test]
fn test_to_ml_metrics_none() {
    let metrics = PerformanceMetrics::default();
    assert!(metrics.to_ml_metrics().is_none());
}

#[test]
fn test_to_ml_metrics_some() -> Result<(), Box<dyn std::error::Error>> {
    let mut feature_importance = HashMap::new();
    feature_importance.insert("feature1".to_string(), 0.8);
    feature_importance.insert("feature2".to_string(), 0.6);

    let metrics = PerformanceMetrics {
        prediction_accuracy: Some(0.95),
        ml_confidence: Some(0.85),
        feature_importance: Some(feature_importance.clone()),
        total_inferences: Some(1000),
        average_inference_latency_us: Some(500),
        model_error_rate: Some(0.02),
        ..Default::default()
    };

    let ml = metrics
        .to_ml_metrics()
        .ok_or("Failed to convert to ML metrics")?;
    assert_eq!(ml.prediction_accuracy, 0.95);
    assert_eq!(ml.ml_confidence, 0.85);
    assert_eq!(ml.feature_importance, feature_importance);
    assert_eq!(ml.total_inferences, 1000);
    Ok(())
}

#[test]
fn test_to_system_metrics_none() {
    let metrics = PerformanceMetrics::default();
    assert!(metrics.to_system_metrics().is_none());
}

#[test]
fn test_to_system_metrics_some() -> Result<(), Box<dyn std::error::Error>> {
    let metrics = PerformanceMetrics {
        average_latency_us: Some(150),
        throughput_pps: Some(10000),
        memory_usage_bytes: Some(1024 * 1024),
        cpu_utilization_percent: Some(75.5),
        error_rate: Some(0.001),
        uptime_seconds: Some(86400),
        ..Default::default()
    };

    let system = metrics
        .to_system_metrics()
        .ok_or("Failed to convert to system metrics")?;
    assert_eq!(system.average_latency_us, 150);
    assert_eq!(system.throughput_pps, 10000);
    assert_eq!(system.memory_usage_bytes, 1024 * 1024);
    assert_eq!(system.cpu_utilization_percent, 75.5);
    Ok(())
}

// ========================================================================
// Detection Method Tests
// ========================================================================

#[test]
fn test_has_financial_metrics_false() {
    let metrics = PerformanceMetrics::default();
    assert!(!metrics.has_financial_metrics());
}

#[test]
fn test_has_financial_metrics_true() {
    let metrics = PerformanceMetrics {
        total_return: Some(0.15),
        ..Default::default()
    };
    assert!(metrics.has_financial_metrics());

    let metrics2 = PerformanceMetrics {
        sharpe_ratio: Some(1.8),
        ..Default::default()
    };
    assert!(metrics2.has_financial_metrics());

    let metrics3 = PerformanceMetrics {
        win_rate: Some(0.65),
        ..Default::default()
    };
    assert!(metrics3.has_financial_metrics());
}

#[test]
fn test_has_ml_metrics_false() {
    let metrics = PerformanceMetrics::default();
    assert!(!metrics.has_ml_metrics());
}

#[test]
fn test_has_ml_metrics_true() {
    let metrics1 = PerformanceMetrics {
        prediction_accuracy: Some(0.95),
        ..Default::default()
    };
    assert!(metrics1.has_ml_metrics());

    let metrics2 = PerformanceMetrics {
        ml_confidence: Some(0.85),
        ..Default::default()
    };
    assert!(metrics2.has_ml_metrics());

    let mut feature_importance = HashMap::new();
    feature_importance.insert("test".to_string(), 0.5);
    let metrics3 = PerformanceMetrics {
        feature_importance: Some(feature_importance),
        ..Default::default()
    };
    assert!(metrics3.has_ml_metrics());
}

#[test]
fn test_has_system_metrics_false() {
    let metrics = PerformanceMetrics::default();
    assert!(!metrics.has_system_metrics());
}

#[test]
fn test_has_system_metrics_true() {
    let metrics1 = PerformanceMetrics {
        average_latency_us: Some(150),
        ..Default::default()
    };
    assert!(metrics1.has_system_metrics());

    let metrics2 = PerformanceMetrics {
        throughput_pps: Some(10000),
        ..Default::default()
    };
    assert!(metrics2.has_system_metrics());

    let metrics3 = PerformanceMetrics {
        memory_usage_bytes: Some(1024),
        ..Default::default()
    };
    assert!(metrics3.has_system_metrics());
}

// ========================================================================
// Getter Method Tests ("_or_zero" methods)
// ========================================================================

#[test]
fn test_total_return_or_zero() {
    let metrics_none = PerformanceMetrics::default();
    assert_eq!(metrics_none.total_return_or_zero(), 0.0);

    let metrics_some = PerformanceMetrics {
        total_return: Some(0.15),
        ..Default::default()
    };
    assert_eq!(metrics_some.total_return_or_zero(), 0.15);
}

#[test]
fn test_annualized_return_or_zero() {
    let metrics_none = PerformanceMetrics::default();
    assert_eq!(metrics_none.annualized_return_or_zero(), 0.0);

    let metrics_some = PerformanceMetrics {
        annualized_return: Some(0.12),
        ..Default::default()
    };
    assert_eq!(metrics_some.annualized_return_or_zero(), 0.12);
}

#[test]
fn test_sharpe_ratio_or_zero() {
    let metrics_none = PerformanceMetrics::default();
    assert_eq!(metrics_none.sharpe_ratio_or_zero(), 0.0);

    let metrics_some = PerformanceMetrics {
        sharpe_ratio: Some(1.8),
        ..Default::default()
    };
    assert_eq!(metrics_some.sharpe_ratio_or_zero(), 1.8);
}

#[test]
fn test_sortino_ratio_or_zero() {
    let metrics_none = PerformanceMetrics::default();
    assert_eq!(metrics_none.sortino_ratio_or_zero(), 0.0);

    let metrics_some = PerformanceMetrics {
        sortino_ratio: Some(2.1),
        ..Default::default()
    };
    assert_eq!(metrics_some.sortino_ratio_or_zero(), 2.1);
}

#[test]
fn test_calmar_ratio_or_zero() {
    let metrics_none = PerformanceMetrics::default();
    assert_eq!(metrics_none.calmar_ratio_or_zero(), 0.0);

    let metrics_some = PerformanceMetrics {
        calmar_ratio: Some(1.5),
        ..Default::default()
    };
    assert_eq!(metrics_some.calmar_ratio_or_zero(), 1.5);
}

#[test]
fn test_max_drawdown() {
    let metrics_none = PerformanceMetrics::default();
    assert_eq!(metrics_none.max_drawdown(), 0.0);

    let metrics_some = PerformanceMetrics {
        maximum_drawdown: Some(0.05),
        ..Default::default()
    };
    assert_eq!(metrics_some.max_drawdown(), 0.05);
}

#[test]
fn test_max_drawdown_duration_days() {
    let metrics_none = PerformanceMetrics::default();
    assert_eq!(metrics_none.max_drawdown_duration_days(), 0);

    let metrics_some = PerformanceMetrics {
        max_drawdown_duration_days: Some(30),
        ..Default::default()
    };
    assert_eq!(metrics_some.max_drawdown_duration_days(), 30);
}

#[test]
fn test_win_rate_or_zero() {
    let metrics_none = PerformanceMetrics::default();
    assert_eq!(metrics_none.win_rate_or_zero(), 0.0);

    let metrics_some = PerformanceMetrics {
        win_rate: Some(0.65),
        ..Default::default()
    };
    assert_eq!(metrics_some.win_rate_or_zero(), 0.65);
}

#[test]
fn test_profit_factor_or_zero() {
    let metrics_none = PerformanceMetrics::default();
    assert_eq!(metrics_none.profit_factor_or_zero(), 0.0);

    let metrics_some = PerformanceMetrics {
        profit_factor: Some(1.8),
        ..Default::default()
    };
    assert_eq!(metrics_some.profit_factor_or_zero(), 1.8);
}

#[test]
fn test_volatility_or_zero() {
    let metrics_none = PerformanceMetrics::default();
    assert_eq!(metrics_none.volatility_or_zero(), 0.0);

    let metrics_some = PerformanceMetrics {
        volatility: Some(0.12),
        ..Default::default()
    };
    assert_eq!(metrics_some.volatility_or_zero(), 0.12);
}

#[test]
fn test_information_ratio_or_zero() {
    let metrics_none = PerformanceMetrics::default();
    assert_eq!(metrics_none.information_ratio_or_zero(), 0.0);

    let metrics_some = PerformanceMetrics {
        information_ratio: Some(0.5),
        ..Default::default()
    };
    assert_eq!(metrics_some.information_ratio_or_zero(), 0.5);
}

#[test]
fn test_treynor_ratio_or_zero() {
    let metrics_none = PerformanceMetrics::default();
    assert_eq!(metrics_none.treynor_ratio_or_zero(), 0.0);

    let metrics_some = PerformanceMetrics {
        treynor_ratio: Some(0.08),
        ..Default::default()
    };
    assert_eq!(metrics_some.treynor_ratio_or_zero(), 0.08);
}

#[test]
fn test_beta_or_zero() {
    let metrics_none = PerformanceMetrics::default();
    assert_eq!(metrics_none.beta_or_zero(), 0.0);

    let metrics_some = PerformanceMetrics {
        beta: Some(1.2),
        ..Default::default()
    };
    assert_eq!(metrics_some.beta_or_zero(), 1.2);
}

#[test]
fn test_tracking_error_or_zero() {
    let metrics_none = PerformanceMetrics::default();
    assert_eq!(metrics_none.tracking_error_or_zero(), 0.0);

    let metrics_some = PerformanceMetrics {
        tracking_error: Some(0.03),
        ..Default::default()
    };
    assert_eq!(metrics_some.tracking_error_or_zero(), 0.03);
}

#[test]
fn test_total_trades_or_zero() {
    let metrics_none = PerformanceMetrics::default();
    assert_eq!(metrics_none.total_trades_or_zero(), 0);

    let metrics_some = PerformanceMetrics {
        total_trades: Some(150),
        ..Default::default()
    };
    assert_eq!(metrics_some.total_trades_or_zero(), 150);
}

#[test]
fn test_profitable_trades() {
    let metrics_none = PerformanceMetrics::default();
    assert_eq!(metrics_none.profitable_trades(), 0);

    let metrics_some = PerformanceMetrics {
        winning_trades: Some(75),
        ..Default::default()
    };
    assert_eq!(metrics_some.profitable_trades(), 75);
}

#[test]
fn test_losing_trades_count() {
    let metrics_none = PerformanceMetrics::default();
    assert_eq!(metrics_none.losing_trades_count(), 0);

    let metrics_some = PerformanceMetrics {
        losing_trades: Some(25),
        ..Default::default()
    };
    assert_eq!(metrics_some.losing_trades_count(), 25);
}

#[test]
fn test_largest_win_or_zero() {
    let metrics_none = PerformanceMetrics::default();
    assert_eq!(metrics_none.largest_win_or_zero(), 0.0);

    let metrics_some = PerformanceMetrics {
        largest_win: Some(1500.0),
        ..Default::default()
    };
    assert_eq!(metrics_some.largest_win_or_zero(), 1500.0);
}

#[test]
fn test_largest_loss_or_zero() {
    let metrics_none = PerformanceMetrics::default();
    assert_eq!(metrics_none.largest_loss_or_zero(), 0.0);

    let metrics_some = PerformanceMetrics {
        largest_loss: Some(-800.0),
        ..Default::default()
    };
    assert_eq!(metrics_some.largest_loss_or_zero(), -800.0);
}

#[test]
fn test_recovery_factor_or_zero() {
    let metrics_none = PerformanceMetrics::default();
    assert_eq!(metrics_none.recovery_factor_or_zero(), 0.0);

    let metrics_some = PerformanceMetrics {
        recovery_factor: Some(3.2),
        ..Default::default()
    };
    assert_eq!(metrics_some.recovery_factor_or_zero(), 3.2);
}

// ========================================================================
// From Conversion Tests
// ========================================================================

#[test]
fn test_from_financial_metrics() {
    let financial = FinancialMetrics {
        total_return: 0.15,
        annualized_return: 0.12,
        sharpe_ratio: 1.8,
        maximum_drawdown: 0.05,
        win_rate: 0.65,
        total_trades: 100,
        profit_factor: 1.5,
        volatility: 0.08,
    };

    let metrics: PerformanceMetrics = financial.into();
    assert_eq!(metrics.total_return, Some(0.15));
    assert_eq!(metrics.annualized_return, Some(0.12));
    assert_eq!(metrics.sharpe_ratio, Some(1.8));
    assert_eq!(metrics.maximum_drawdown, Some(0.05));
    assert_eq!(metrics.win_rate, Some(0.65));
    assert_eq!(metrics.total_trades, Some(100));
    assert_eq!(metrics.profit_factor, Some(1.5));
    assert_eq!(metrics.volatility, Some(0.08));
}

#[test]
fn test_from_ml_metrics() {
    let mut feature_importance = HashMap::new();
    feature_importance.insert("feature1".to_string(), 0.8);

    let ml = MLMetrics {
        prediction_accuracy: 0.95,
        ml_confidence: 0.85,
        feature_importance: feature_importance.clone(),
        total_inferences: 1000,
        average_inference_latency_us: 500,
        model_error_rate: 0.02,
    };

    let metrics: PerformanceMetrics = ml.into();
    assert_eq!(metrics.prediction_accuracy, Some(0.95));
    assert_eq!(metrics.ml_confidence, Some(0.85));
    assert_eq!(metrics.feature_importance, Some(feature_importance));
    assert_eq!(metrics.total_inferences, Some(1000));
    assert_eq!(metrics.average_inference_latency_us, Some(500));
    assert_eq!(metrics.model_error_rate, Some(0.02));
}

#[test]
fn test_from_system_metrics() {
    let system = SystemMetrics {
        average_latency_us: 150,
        throughput_pps: 10000,
        memory_usage_bytes: 1024 * 1024,
        cpu_utilization_percent: 75.5,
        error_rate: 0.001,
        uptime_seconds: 86400,
    };

    let metrics: PerformanceMetrics = system.into();
    assert_eq!(metrics.average_latency_us, Some(150));
    assert_eq!(metrics.throughput_pps, Some(10000));
    assert_eq!(metrics.memory_usage_bytes, Some(1024 * 1024));
    assert_eq!(metrics.cpu_utilization_percent, Some(75.5));
    assert_eq!(metrics.error_rate, Some(0.001));
    assert_eq!(metrics.uptime_seconds, Some(86400));
}

#[test]
fn test_from_risk_metrics() {
    let risk = RiskMetrics {
        value_at_risk: 0.05,
        conditional_value_at_risk: 0.08,
        maximum_drawdown: -0.15,
        volatility: 0.20,
        beta: Some(1.2),
        correlation: Some(0.85),
    };

    let metrics: PerformanceMetrics = risk.into();
    assert_eq!(metrics.value_at_risk, Some(0.05));
    assert_eq!(metrics.conditional_value_at_risk, Some(0.08));
    assert_eq!(metrics.maximum_drawdown, Some(-0.15));
    assert_eq!(metrics.volatility, Some(0.20));
}
