scirs2-core 0.4.3

Core utilities and common functionality for SciRS2 (scirs2-core)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
//! # Performance Dashboards System
//!
//! Enterprise-grade performance monitoring dashboards with real-time visualization
//! and historical trend analysis for production environments. Provides comprehensive
//! performance insights with customizable metrics and alerting capabilities.
//!
//! ## Features
//!
//! - Real-time performance visualization with live updates
//! - Historical trend analysis with configurable time ranges
//! - Customizable dashboard layouts and widgets
//! - Interactive charts and graphs with drill-down capabilities
//! - Performance alerting with threshold-based notifications
//! - Multi-dimensional metrics aggregation and filtering
//! - Export capabilities for reports and presentations
//! - Integration with external monitoring systems
//! - Web-based dashboard interface with REST API
//! - Mobile-responsive design for on-the-go monitoring
//!
//! ## Example
//!
//! ```rust
//! use scirs2_core::profiling::dashboards::{
//!     PerformanceDashboard, DashboardConfig, Widget, ChartType, MetricSource
//! };
//!
//! // Create a performance dashboard
//! let config = DashboardConfig::default()
//!     .with_title("Production System Performance")
//!     .with_refresh_interval(std::time::Duration::from_secs(30))
//!     .with_retention_period(std::time::Duration::from_secs(30 * 24 * 60 * 60));
//!
//! let mut dashboard = PerformanceDashboard::new(config)?;
//!
//! // Add performance widgets
//! dashboard.add_widget(Widget::new()
//!     .with_title("CPU Usage")
//!     .with_chart_type(ChartType::LineChart)
//!     .with_metric_source(MetricSource::SystemCpu)
//!     .with_alert_threshold(80.0)
//! )?;
//!
//! dashboard.add_widget(Widget::new()
//!     .with_title("Memory Usage")
//!     .with_chart_type(ChartType::AreaChart)
//!     .with_metric_source(MetricSource::SystemMemory)
//! )?;
//!
//! // Start the dashboard
//! dashboard.start()?;
//!
//! // Dashboard will now continuously update with real-time metrics
//! // Access via web interface at http://localhost:8080/dashboard
//! # Ok::<(), Box<dyn std::error::Error>>(())
//! ```

use crate::error::{CoreError, CoreResult};
use std::collections::{HashMap, VecDeque};
use std::sync::{Arc, Mutex, RwLock};
use std::time::{Duration, Instant, SystemTime};

use serde::{Deserialize, Serialize};

/// Dashboard configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DashboardConfig {
    /// Dashboard title
    pub title: String,
    /// Refresh interval for real-time updates
    pub refresh_interval: Duration,
    /// Data retention period
    pub retention_period: Duration,
    /// Maximum number of data points to keep
    pub max_data_points: usize,
    /// Enable web interface
    pub enable_web_interface: bool,
    /// Web server port
    pub web_port: u16,
    /// Enable REST API
    pub enable_rest_api: bool,
    /// API authentication token
    pub api_token: Option<String>,
    /// Enable real-time alerts
    pub enable_alerts: bool,
    /// Dashboard theme
    pub theme: DashboardTheme,
    /// Auto-save interval for persistence
    pub auto_save_interval: Duration,
}

impl Default for DashboardConfig {
    fn default() -> Self {
        Self {
            title: "Performance Dashboard".to_string(),
            refresh_interval: Duration::from_secs(5),
            retention_period: Duration::from_secs(7 * 24 * 60 * 60), // 7 days
            max_data_points: 1000,
            enable_web_interface: true,
            web_port: 8080,
            enable_rest_api: true,
            api_token: None,
            enable_alerts: true,
            theme: DashboardTheme::Dark,
            auto_save_interval: Duration::from_secs(60),
        }
    }
}

impl DashboardConfig {
    /// Set dashboard title
    pub fn with_title(mut self, title: &str) -> Self {
        self.title = title.to_string();
        self
    }

    /// Set refresh interval
    pub fn with_refresh_interval(mut self, interval: Duration) -> Self {
        self.refresh_interval = interval;
        self
    }

    /// Set data retention period
    pub fn with_retention_period(mut self, period: Duration) -> Self {
        self.retention_period = period;
        self
    }

    /// Enable web interface on specific port
    pub fn with_web_interface(mut self, port: u16) -> Self {
        self.enable_web_interface = true;
        self.web_port = port;
        self
    }

    /// Set API authentication token
    pub fn with_api_token(mut self, token: &str) -> Self {
        self.api_token = Some(token.to_string());
        self
    }

    /// Set dashboard theme
    pub fn with_theme(mut self, theme: DashboardTheme) -> Self {
        self.theme = theme;
        self
    }
}

/// Dashboard theme options
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum DashboardTheme {
    /// Light theme
    Light,
    /// Dark theme
    Dark,
    /// High contrast theme
    HighContrast,
    /// Custom theme
    Custom,
}

/// Chart types for dashboard widgets
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum ChartType {
    /// Line chart for time series data
    LineChart,
    /// Area chart for cumulative data
    AreaChart,
    /// Bar chart for categorical data
    BarChart,
    /// Gauge chart for single values
    GaugeChart,
    /// Pie chart for proportional data
    PieChart,
    /// Heatmap for matrix data
    Heatmap,
    /// Scatter plot for correlation analysis
    ScatterPlot,
    /// Histogram for distribution analysis
    Histogram,
}

/// Metric data sources
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum MetricSource {
    /// System CPU usage
    SystemCpu,
    /// System memory usage
    SystemMemory,
    /// Network I/O
    NetworkIO,
    /// Disk I/O
    DiskIO,
    /// Application-specific metrics
    Application(String),
    /// Custom metric query
    Custom(String),
    /// Database metrics
    Database(String),
    /// Cache metrics
    Cache(String),
}

/// Dashboard widget configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Widget {
    /// Widget ID
    pub id: String,
    /// Widget title
    pub title: String,
    /// Chart type
    pub chart_type: ChartType,
    /// Data source
    pub metric_source: MetricSource,
    /// Position and size
    pub layout: WidgetLayout,
    /// Alert configuration
    pub alert_config: Option<AlertConfig>,
    /// Refresh interval (overrides dashboard default)
    pub refresh_interval: Option<Duration>,
    /// Color scheme
    pub color_scheme: Vec<String>,
    /// Display options
    pub display_options: DisplayOptions,
}

/// Widget layout and positioning
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct WidgetLayout {
    /// X position (grid units)
    pub x: u32,
    /// Y position (grid units)
    pub y: u32,
    /// Width (grid units)
    pub width: u32,
    /// Height (grid units)
    pub height: u32,
}

impl Default for WidgetLayout {
    fn default() -> Self {
        Self {
            x: 0,
            y: 0,
            width: 4,
            height: 3,
        }
    }
}

/// Alert configuration for widgets
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AlertConfig {
    /// Alert threshold value
    pub threshold: f64,
    /// Alert condition
    pub condition: AlertCondition,
    /// Alert severity
    pub severity: AlertSeverity,
    /// Notification channels
    pub notification_channels: Vec<NotificationChannel>,
    /// Cooldown period to prevent spam
    pub cooldown_period: Duration,
}

/// Alert conditions
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum AlertCondition {
    /// Greater than threshold
    GreaterThan,
    /// Less than threshold
    LessThan,
    /// Equal to threshold
    EqualTo,
    /// Not equal to threshold
    NotEqualTo,
    /// Rate of change exceeds threshold
    RateOfChange,
}

/// Alert severity levels
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
pub enum AlertSeverity {
    /// Informational alert
    Info,
    /// Warning alert
    Warning,
    /// Error alert
    Error,
    /// Critical alert
    Critical,
}

/// Notification channels for alerts
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum NotificationChannel {
    /// Email notification
    Email(String),
    /// Slack webhook
    Slack(String),
    /// Custom webhook
    Webhook(String),
    /// Console log
    Console,
    /// File log
    File(String),
}

/// Display options for widgets
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DisplayOptions {
    /// Show data labels
    pub show_labels: bool,
    /// Show grid lines
    pub show_grid: bool,
    /// Show legend
    pub show_legend: bool,
    /// Animation enabled
    pub enable_animation: bool,
    /// Number format
    pub number_format: NumberFormat,
    /// Time format for time series
    pub time_format: String,
}

impl Default for DisplayOptions {
    fn default() -> Self {
        Self {
            show_labels: true,
            show_grid: true,
            show_legend: true,
            enable_animation: true,
            number_format: NumberFormat::Auto,
            time_format: "%H:%M:%S".to_string(),
        }
    }
}

/// Number formatting options
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum NumberFormat {
    /// Automatic formatting
    Auto,
    /// Integer formatting
    Integer,
    /// Decimal formatting with specified precision
    Decimal(u8),
    /// Percentage formatting
    Percentage,
    /// Scientific notation
    Scientific,
    /// Bytes formatting (KB, MB, GB)
    Bytes,
}

impl Widget {
    /// Create a new widget with default settings
    pub fn new() -> Self {
        Self {
            id: uuid::Uuid::new_v4().to_string(),
            title: "New Widget".to_string(),
            chart_type: ChartType::LineChart,
            metric_source: MetricSource::SystemCpu,
            layout: WidgetLayout::default(),
            alert_config: None,
            refresh_interval: None,
            color_scheme: vec![
                "#007acc".to_string(),
                "#ff6b35".to_string(),
                "#00b894".to_string(),
                "#fdcb6e".to_string(),
                "#e84393".to_string(),
            ],
            display_options: DisplayOptions::default(),
        }
    }

    /// Set widget title
    pub fn with_title(mut self, title: &str) -> Self {
        self.title = title.to_string();
        self
    }

    /// Set chart type
    pub fn with_chart_type(mut self, charttype: ChartType) -> Self {
        self.chart_type = charttype;
        self
    }

    /// Set metric source
    pub fn with_metric_source(mut self, source: MetricSource) -> Self {
        self.metric_source = source;
        self
    }

    /// Set widget layout
    pub const fn with_layout(mut self, x: u32, y: u32, width: u32, height: u32) -> Self {
        self.layout = WidgetLayout {
            x,
            y,
            width,
            height,
        };
        self
    }

    /// Set alert threshold
    pub fn with_alert_threshold(mut self, threshold: f64) -> Self {
        self.alert_config = Some(AlertConfig {
            threshold,
            condition: AlertCondition::GreaterThan,
            severity: AlertSeverity::Warning,
            notification_channels: vec![NotificationChannel::Console],
            cooldown_period: Duration::from_secs(300), // 5 minutes
        });
        self
    }

    /// Set custom refresh interval
    pub fn with_refresh_interval(mut self, interval: Duration) -> Self {
        self.refresh_interval = Some(interval);
        self
    }

    /// Set color scheme
    pub fn with_colors(mut self, colors: Vec<&str>) -> Self {
        self.color_scheme = colors.into_iter().map(|s| s.to_string()).collect();
        self
    }
}

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

/// Metric data point
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MetricDataPoint {
    /// Timestamp
    pub timestamp: SystemTime,
    /// Metric value
    pub value: f64,
    /// Optional metadata
    pub metadata: HashMap<String, String>,
}

/// Time series data for a metric
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MetricTimeSeries {
    /// Metric name
    pub name: String,
    /// Data points
    pub data_points: VecDeque<MetricDataPoint>,
    /// Last update time
    pub last_update: SystemTime,
}

impl MetricTimeSeries {
    /// Create a new time series
    pub fn new(name: &str) -> Self {
        Self {
            name: name.to_string(),
            data_points: VecDeque::new(),
            last_update: SystemTime::now(),
        }
    }

    /// Add a data point
    pub fn add_point(&mut self, value: f64, metadata: Option<HashMap<String, String>>) {
        let point = MetricDataPoint {
            timestamp: SystemTime::now(),
            value,
            metadata: metadata.unwrap_or_default(),
        };

        self.data_points.push_back(point);
        self.last_update = SystemTime::now();
    }

    /// Get latest value
    pub fn latest_value(&self) -> Option<f64> {
        self.data_points.back().map(|p| p.value)
    }

    /// Get average value over time range
    pub fn average_value(&self, duration: Duration) -> Option<f64> {
        let cutoff = SystemTime::now() - duration;
        let values: Vec<f64> = self
            .data_points
            .iter()
            .filter(|p| p.timestamp >= cutoff)
            .map(|p| p.value)
            .collect();

        if values.is_empty() {
            None
        } else {
            Some(values.iter().sum::<f64>() / values.len() as f64)
        }
    }

    /// Clean old data points
    pub fn cleanup(&mut self, retention_period: Duration, maxpoints: usize) {
        let cutoff = SystemTime::now() - retention_period;

        // Remove old data points
        while let Some(front) = self.data_points.front() {
            if front.timestamp < cutoff {
                self.data_points.pop_front();
            } else {
                break;
            }
        }

        // Limit maximum number of points
        while self.data_points.len() > maxpoints {
            self.data_points.pop_front();
        }
    }
}

/// Dashboard alert
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DashboardAlert {
    /// Alert ID
    pub id: String,
    /// Widget ID that triggered the alert
    pub widget_id: String,
    /// Alert message
    pub message: String,
    /// Alert severity
    pub severity: AlertSeverity,
    /// Trigger time
    pub triggered_at: SystemTime,
    /// Current value that triggered the alert
    pub current_value: f64,
    /// Threshold value
    pub threshold_value: f64,
    /// Alert status
    pub status: AlertStatus,
}

/// Alert status
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum AlertStatus {
    /// Alert is active
    Active,
    /// Alert is acknowledged
    Acknowledged,
    /// Alert is resolved
    Resolved,
}

/// Performance dashboard
pub struct PerformanceDashboard {
    /// Dashboard configuration
    config: DashboardConfig,
    /// Dashboard widgets
    widgets: HashMap<String, Widget>,
    /// Metric time series data
    metrics: Arc<RwLock<HashMap<String, MetricTimeSeries>>>,
    /// Active alerts
    alerts: Arc<Mutex<HashMap<String, DashboardAlert>>>,
    /// Dashboard state
    state: DashboardState,
    /// Last update time
    last_update: Instant,
    /// Web server handle (if enabled)
    web_server_handle: Option<WebServerHandle>,
}

/// Dashboard state
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum DashboardState {
    /// Dashboard is stopped
    Stopped,
    /// Dashboard is running
    Running,
    /// Dashboard is paused
    Paused,
    /// Dashboard has encountered an error
    Error,
}

/// Web server handle for dashboard
pub struct WebServerHandle {
    /// Server address
    pub address: String,
    /// Server port
    pub port: u16,
    /// Running state
    pub running: Arc<Mutex<bool>>,
}

impl PerformanceDashboard {
    /// Create a new performance dashboard
    pub fn new(config: DashboardConfig) -> CoreResult<Self> {
        Ok(Self {
            config,
            widgets: HashMap::new(),
            metrics: Arc::new(RwLock::new(HashMap::new())),
            alerts: Arc::new(Mutex::new(HashMap::new())),
            state: DashboardState::Stopped,
            last_update: Instant::now(),
            web_server_handle: None,
        })
    }

    /// Add a widget to the dashboard
    pub fn add_widget(&mut self, widget: Widget) -> CoreResult<String> {
        let widget_id = widget.id.clone();
        self.widgets.insert(widget_id.clone(), widget);

        // Initialize metric time series for this widget
        let metrics_name = format!("widget_{widget_id}");
        if let Ok(mut metrics) = self.metrics.write() {
            metrics.insert(metrics_name, MetricTimeSeries::new(&widget_id));
        }

        Ok(widget_id)
    }

    /// Remove a widget from the dashboard
    pub fn remove_widget(&mut self, widgetid: &str) -> CoreResult<()> {
        self.widgets.remove(widgetid);

        // Remove associated metric data
        let metrics_name = format!("widget_{widgetid}");
        if let Ok(mut metrics) = self.metrics.write() {
            metrics.remove(&metrics_name);
        }

        Ok(())
    }

    /// Start the dashboard
    pub fn start(&mut self) -> CoreResult<()> {
        if self.state == DashboardState::Running {
            return Ok(());
        }

        // Start web server if enabled
        if self.config.enable_web_interface {
            self.start_web_server()?;
        }

        self.state = DashboardState::Running;
        self.last_update = Instant::now();

        Ok(())
    }

    /// Stop the dashboard
    pub fn stop(&mut self) -> CoreResult<()> {
        // Stop web server if running
        if let Some(ref handle) = self.web_server_handle {
            if let Ok(mut running) = handle.running.lock() {
                *running = false;
            }
        }

        self.state = DashboardState::Stopped;
        Ok(())
    }

    /// Update dashboard with new metric data
    pub fn update_metric(&mut self, source: &MetricSource, value: f64) -> CoreResult<()> {
        let metricname = self.metric_source_to_name(source);

        if let Ok(mut metrics) = self.metrics.write() {
            let time_series = metrics
                .entry(metricname.clone())
                .or_insert_with(|| MetricTimeSeries::new(&metricname));

            time_series.add_point(value, None);

            // Clean up old data
            time_series.cleanup(self.config.retention_period, self.config.max_data_points);
        }

        // Check for alerts
        self.check_alerts(&metricname, value)?;

        self.last_update = Instant::now();
        Ok(())
    }

    /// Get current metrics data
    pub fn get_metrics(&self) -> CoreResult<HashMap<String, MetricTimeSeries>> {
        self.metrics
            .read()
            .map(|metrics| metrics.clone())
            .map_err(|_| CoreError::from(std::io::Error::other("Failed to read metrics")))
    }

    /// Get dashboard statistics
    pub fn get_statistics(&self) -> DashboardStatistics {
        let metrics = self.metrics.read().expect("Operation failed");
        let alerts = self.alerts.lock().expect("Operation failed");

        DashboardStatistics {
            total_widgets: self.widgets.len(),
            total_metrics: metrics.len(),
            active_alerts: alerts
                .values()
                .filter(|a| a.status == AlertStatus::Active)
                .count(),
            last_update: self.last_update,
            uptime: self.last_update.elapsed(),
            state: self.state,
        }
    }

    /// Export dashboard configuration
    pub fn export_config(&self) -> CoreResult<String> {
        {
            let export_data = DashboardExport {
                config: self.config.clone(),
                widgets: self.widgets.values().cloned().collect(),
                created_at: SystemTime::now(),
            };

            serde_json::to_string_pretty(&export_data).map_err(|e| {
                CoreError::from(std::io::Error::other(format!(
                    "Failed to serialize dashboard config: {e}"
                )))
            })
        }
        #[cfg(not(feature = "serde"))]
        {
            Ok(format!("title: {}", self.config.title))
        }
    }

    /// Import dashboard configuration
    pub fn import_configuration(&mut self, configjson: &str) -> CoreResult<()> {
        {
            let import_data: DashboardExport = serde_json::from_str(configjson).map_err(|e| {
                CoreError::from(std::io::Error::other(format!(
                    "Failed to parse dashboard config: {e}"
                )))
            })?;

            self.config = import_data.config;
            self.widgets.clear();

            for widget in import_data.widgets {
                self.widgets.insert(widget.id.clone(), widget);
            }

            Ok(())
        }
        #[cfg(not(feature = "serde"))]
        {
            let _ = configjson; // Suppress unused variable warning
            Err(CoreError::from(std::io::Error::other(
                "Serde feature not enabled for configuration import",
            )))
        }
    }

    /// Check for alert conditions
    fn check_alerts(&self, metricname: &str, value: f64) -> CoreResult<()> {
        for widget in self.widgets.values() {
            if let Some(ref alert_config) = widget.alert_config {
                let widget_metric = self.metric_source_to_name(&widget.metric_source);

                if widget_metric == metricname {
                    let triggered = match alert_config.condition {
                        AlertCondition::GreaterThan => value > alert_config.threshold,
                        AlertCondition::LessThan => value < alert_config.threshold,
                        AlertCondition::EqualTo => {
                            (value - alert_config.threshold).abs() < f64::EPSILON
                        }
                        AlertCondition::NotEqualTo => {
                            (value - alert_config.threshold).abs() > f64::EPSILON
                        }
                        AlertCondition::RateOfChange => {
                            // Would implement rate of change calculation here
                            false
                        }
                    };

                    if triggered {
                        let alert = DashboardAlert {
                            id: uuid::Uuid::new_v4().to_string(),
                            widget_id: widget.id.clone(),
                            message: format!(
                                "Alert triggered for '{}': value {:.2} {} threshold {:.2}",
                                widget.title,
                                value,
                                match alert_config.condition {
                                    AlertCondition::GreaterThan => "exceeds",
                                    AlertCondition::LessThan => "below",
                                    _ => "meets",
                                },
                                alert_config.threshold
                            ),
                            severity: alert_config.severity,
                            triggered_at: SystemTime::now(),
                            current_value: value,
                            threshold_value: alert_config.threshold,
                            status: AlertStatus::Active,
                        };

                        if let Ok(mut alerts) = self.alerts.lock() {
                            alerts.insert(alert.id.clone(), alert.clone());
                        }

                        // Send notifications
                        self.send_alert_notifications(&alert, alert_config)?;
                    }
                }
            }
        }

        Ok(())
    }

    /// Send alert notifications
    fn send_alert_notifications(
        &self,
        alert: &DashboardAlert,
        config: &AlertConfig,
    ) -> CoreResult<()> {
        for channel in &config.notification_channels {
            match channel {
                NotificationChannel::Console => {
                    println!("[DASHBOARD ALERT] {message}", message = alert.message);
                }
                NotificationChannel::File(path) => {
                    use std::fs::OpenOptions;
                    use std::io::Write;

                    if let Ok(mut file) = OpenOptions::new().create(true).append(true).open(path) {
                        writeln!(
                            file,
                            "[{}] {}",
                            chrono::Utc::now().format("%Y-%m-%d %H:%M:%S UTC"),
                            alert.message
                        )
                        .ok();
                    }
                }
                #[cfg(feature = "observability_http")]
                NotificationChannel::Webhook(url) => {
                    // Would implement webhook notification here
                    let _ = url; // Suppress unused warning
                }
                #[cfg(not(feature = "observability_http"))]
                NotificationChannel::Webhook(_) => {
                    // Webhook notifications require HTTP feature
                }
                NotificationChannel::Email(_) | NotificationChannel::Slack(_) => {
                    // Would implement email/slack notifications here in production
                }
            }
        }

        Ok(())
    }

    /// Convert metric source to internal metric name
    fn metric_source_to_name(&self, source: &MetricSource) -> String {
        match source {
            MetricSource::SystemCpu => "system.cpu".to_string(),
            MetricSource::SystemMemory => "system.memory".to_string(),
            MetricSource::NetworkIO => "system.network_io".to_string(),
            MetricSource::DiskIO => "system.disk_io".to_string(),
            MetricSource::Application(name) => format!("app.{name}"),
            MetricSource::Custom(name) => format!("custom.{name}"),
            MetricSource::Database(name) => format!("db.{name}"),
            MetricSource::Cache(name) => format!("cache.{name}"),
        }
    }

    /// Start web server for dashboard interface
    fn start_web_server(&mut self) -> CoreResult<()> {
        // In a full implementation, this would start an actual web server
        // For now, we'll simulate it

        let handle = WebServerHandle {
            address: "0.0.0.0".to_string(),
            port: self.config.web_port,
            running: Arc::new(Mutex::new(true)),
        };

        self.web_server_handle = Some(handle);

        println!(
            "Dashboard web interface started at http://localhost:{}/dashboard",
            self.config.web_port
        );

        Ok(())
    }
}

/// Dashboard export/import structure
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DashboardExport {
    /// Dashboard configuration
    pub config: DashboardConfig,
    /// Widget configurations
    pub widgets: Vec<Widget>,
    /// Export timestamp
    pub created_at: SystemTime,
}

/// Dashboard statistics
#[derive(Debug, Clone)]
#[cfg_attr(feature = "serde", derive(Serialize))]
pub struct DashboardStatistics {
    /// Total number of widgets
    pub total_widgets: usize,
    /// Total number of metrics
    pub total_metrics: usize,
    /// Number of active alerts
    pub active_alerts: usize,
    /// Last update time
    #[cfg_attr(feature = "serde", serde(skip))]
    pub last_update: Instant,
    /// Dashboard uptime
    pub uptime: Duration,
    /// Current state
    pub state: DashboardState,
}

impl Default for DashboardStatistics {
    fn default() -> Self {
        Self {
            total_widgets: 0,
            total_metrics: 0,
            active_alerts: 0,
            last_update: Instant::now(),
            uptime: Duration::from_secs(0),
            state: DashboardState::Stopped,
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_dashboard_creation() {
        let config = DashboardConfig::default()
            .with_title("Test Dashboard")
            .with_refresh_interval(Duration::from_secs(10));

        let dashboard = PerformanceDashboard::new(config);
        assert!(dashboard.is_ok());

        let dashboard = dashboard.expect("Operation failed");
        assert_eq!(dashboard.config.title, "Test Dashboard");
        assert_eq!(dashboard.config.refresh_interval, Duration::from_secs(10));
    }

    #[test]
    fn test_widget_creation_and_addition() {
        let config = DashboardConfig::default();
        let mut dashboard = PerformanceDashboard::new(config).expect("Operation failed");

        let widget = Widget::new()
            .with_title("CPU Usage")
            .with_chart_type(ChartType::LineChart)
            .with_metric_source(MetricSource::SystemCpu)
            .with_alert_threshold(80.0);

        let widget_id = dashboard.add_widget(widget).expect("Operation failed");
        assert!(!widget_id.is_empty());
        assert_eq!(dashboard.widgets.len(), 1);
    }

    #[test]
    fn test_metric_updates() {
        let config = DashboardConfig::default();
        let mut dashboard = PerformanceDashboard::new(config).expect("Operation failed");

        // Add a widget
        let widget = Widget::new().with_metric_source(MetricSource::SystemCpu);

        dashboard.add_widget(widget).expect("Operation failed");

        // Update metric
        let result = dashboard.update_metric(&MetricSource::SystemCpu, 75.5);
        assert!(result.is_ok());

        // Check that metric was recorded
        let metrics = dashboard.get_metrics().expect("Operation failed");
        let cpu_metric = metrics.get("system.cpu");
        assert!(cpu_metric.is_some());

        let cpu_metric = cpu_metric.expect("Operation failed");
        assert_eq!(cpu_metric.latest_value(), Some(75.5));
    }

    #[test]
    fn test_metric_time_series() {
        let mut ts = MetricTimeSeries::new("test_metric");

        ts.add_point(10.0, None);
        ts.add_point(20.0, None);
        ts.add_point(30.0, None);

        assert_eq!(ts.latest_value(), Some(30.0));
        assert_eq!(ts.data_points.len(), 3);

        // Test cleanup
        ts.cleanup(Duration::from_secs(1), 2);
        assert_eq!(ts.data_points.len(), 2);
    }

    #[test]
    fn test_alert_configuration() {
        let widget = Widget::new()
            .with_title("Memory Usage")
            .with_alert_threshold(90.0);

        assert!(widget.alert_config.is_some());

        let alert_config = widget.alert_config.expect("Operation failed");
        assert_eq!(alert_config.threshold, 90.0);
        assert_eq!(alert_config.condition, AlertCondition::GreaterThan);
        assert_eq!(alert_config.severity, AlertSeverity::Warning);
    }

    #[test]
    fn test_dashboard_statistics() {
        let config = DashboardConfig::default();
        let mut dashboard = PerformanceDashboard::new(config).expect("Operation failed");

        // Add some widgets
        for i in 0..3 {
            let widget = Widget::new().with_title(&format!("Widget {i}"));
            dashboard.add_widget(widget).expect("Operation failed");
        }

        let stats = dashboard.get_statistics();
        assert_eq!(stats.total_widgets, 3);
        assert_eq!(stats.active_alerts, 0);
        assert_eq!(stats.state, DashboardState::Stopped);
    }

    #[test]
    fn test_dashboard_config_builder() {
        let config = DashboardConfig::default()
            .with_title("Custom Dashboard")
            .with_refresh_interval(Duration::from_secs(30))
            .with_retention_period(Duration::from_secs(14 * 24 * 60 * 60)) // 14 days
            .with_web_interface(9090)
            .with_api_token("test-token")
            .with_theme(DashboardTheme::Light);

        assert_eq!(config.title, "Custom Dashboard");
        assert_eq!(config.refresh_interval, Duration::from_secs(30));
        assert_eq!(
            config.retention_period,
            Duration::from_secs(14 * 24 * 60 * 60)
        ); // 14 days
        assert_eq!(config.web_port, 9090);
        assert_eq!(config.api_token, Some("test-token".to_string()));
        assert_eq!(config.theme, DashboardTheme::Light);
    }

    #[test]
    fn test_widget_layout() {
        let widget = Widget::new().with_layout(2, 3, 6, 4);

        assert_eq!(widget.layout.x, 2);
        assert_eq!(widget.layout.y, 3);
        assert_eq!(widget.layout.width, 6);
        assert_eq!(widget.layout.height, 4);
    }
}