optirs-tpu 0.3.2

OptiRS TPU coordination and pod management
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
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
//! Data-only monitoring types: settings/configuration structs, metric
//! collectors, alert/anomaly/analytics records, and their supporting
//! enums.
//!
//! Every field here is `pub` (a plain configuration/data bag); the
//! meaningful logic that reads and mutates [`TopologyPerformanceMonitor`]
//! lives in the sibling [`super::monitor_impl`] module.

use std::collections::{HashMap, VecDeque};
use std::sync::atomic::AtomicU64;
use std::time::{Duration, Instant};

use crate::tpu_backend::DeviceId;

/// Type alias for topology metrics collection
pub type TopologyMetrics = HashMap<String, f64>;

/// Main topology performance monitor with comprehensive monitoring capabilities
#[derive(Debug, Default)]
pub struct TopologyPerformanceMonitor {
    /// Performance monitoring configuration
    pub performance_monitoring: PerformanceMonitoringSettings,
    /// Health monitoring configuration
    pub health_monitoring: HealthMonitoringSettings,
    /// Traffic monitoring configuration
    pub traffic_monitoring: TrafficMonitoringSettings,
    /// Alert management system
    pub alert_system: AlertSystem,
    /// Metrics collection engine
    pub metrics_collector: MetricsCollector,
    /// Anomaly detection system
    pub anomaly_detector: AnomalyDetector,
    /// Performance analytics
    pub analytics: PerformanceAnalytics,
    /// Monotonic counter used to mint unique performance-report identifiers.
    ///
    /// Stored as an `AtomicU64` so `generate_report(&self)` can allocate a fresh
    /// id through a shared reference without requiring `&mut self`.
    pub report_counter: AtomicU64,
}

/// Comprehensive monitoring settings for topology
#[derive(Debug, Clone, Default)]
pub struct TopologyMonitoringSettings {
    /// Performance monitoring
    pub performance_monitoring: PerformanceMonitoringSettings,
    /// Health monitoring
    pub health_monitoring: HealthMonitoringSettings,
    /// Traffic monitoring
    pub traffic_monitoring: TrafficMonitoringSettings,
    /// Alert settings
    pub alert_settings: AlertSettings,
}

/// Performance monitoring configuration and settings
#[derive(Debug, Clone)]
pub struct PerformanceMonitoringSettings {
    /// Monitoring interval
    pub monitoring_interval: Duration,
    /// Metrics collection
    pub metrics_collection: MetricsCollectionSettings,
    /// Performance thresholds
    pub performance_thresholds: PerformanceThresholds,
}

/// Metrics collection configuration and settings
#[derive(Debug, Clone)]
pub struct MetricsCollectionSettings {
    /// Collected metrics
    pub collected_metrics: Vec<MetricType>,
    /// Collection granularity
    pub granularity: CollectionGranularity,
    /// Data retention
    pub retention_period: Duration,
}

/// Types of metrics to collect and monitor
#[derive(Debug, Clone)]
pub enum MetricType {
    /// Latency metrics
    Latency,
    /// Throughput metrics
    Throughput,
    /// Bandwidth utilization
    BandwidthUtilization,
    /// Packet loss rate
    PacketLoss,
    /// Queue occupancy
    QueueOccupancy,
    /// Custom metric
    Custom { metric_name: String },
}

/// Collection granularity levels for metrics
#[derive(Debug, Clone)]
pub enum CollectionGranularity {
    /// Per-device granularity
    PerDevice,
    /// Per-link granularity
    PerLink,
    /// Per-flow granularity
    PerFlow,
    /// Aggregate granularity
    Aggregate,
}

/// Performance thresholds for monitoring and alerting
#[derive(Debug, Clone)]
pub struct PerformanceThresholds {
    /// Latency thresholds
    pub latency_thresholds: ThresholdLevels,
    /// Throughput thresholds
    pub throughput_thresholds: ThresholdLevels,
    /// Utilization thresholds
    pub utilization_thresholds: ThresholdLevels,
    /// Error rate thresholds
    pub error_thresholds: ThresholdLevels,
}

/// Threshold levels for performance metrics
#[derive(Debug, Clone)]
pub struct ThresholdLevels {
    /// Warning threshold
    pub warning: f64,
    /// Critical threshold
    pub critical: f64,
    /// Emergency threshold
    pub emergency: f64,
}

/// Health monitoring configuration and settings
#[derive(Debug, Clone)]
pub struct HealthMonitoringSettings {
    /// Health check frequency
    pub check_frequency: Duration,
    /// Health indicators
    pub health_indicators: Vec<HealthIndicator>,
    /// Failure detection
    pub failure_detection: FailureDetectionSettings,
}

/// Health indicators to monitor for system health
#[derive(Debug, Clone)]
pub enum HealthIndicator {
    /// Link connectivity
    LinkConnectivity,
    /// Device responsiveness
    DeviceResponsiveness,
    /// Performance degradation
    PerformanceDegradation,
    /// Error rate increase
    ErrorRateIncrease,
    /// Custom health indicator
    Custom { indicator_name: String },
}

/// Failure detection configuration and settings
#[derive(Debug, Clone)]
pub struct FailureDetectionSettings {
    /// Detection algorithm
    pub algorithm: FailureDetectionAlgorithm,
    /// Detection sensitivity
    pub sensitivity: f64,
    /// False positive tolerance
    pub false_positive_tolerance: f64,
}

/// Failure detection algorithms for health monitoring
#[derive(Debug, Clone)]
pub enum FailureDetectionAlgorithm {
    /// Threshold-based detection
    ThresholdBased,
    /// Statistical anomaly detection
    StatisticalAnomaly,
    /// Machine learning based
    MachineLearning { model_path: String },
    /// Consensus-based detection
    ConsensusBased,
}

/// Traffic monitoring configuration and settings
#[derive(Debug, Clone, Default)]
pub struct TrafficMonitoringSettings {
    /// Flow monitoring
    pub flow_monitoring: FlowMonitoringSettings,
    /// Pattern analysis
    pub pattern_analysis: PatternAnalysisSettings,
    /// Anomaly detection
    pub anomaly_detection: AnomalyDetectionSettings,
}

/// Flow monitoring configuration and settings
#[derive(Debug, Clone)]
pub struct FlowMonitoringSettings {
    /// Flow tracking granularity
    pub tracking_granularity: FlowTrackingGranularity,
    /// Flow timeout
    pub flow_timeout: Duration,
    /// Sampling rate
    pub sampling_rate: f64,
}

/// Flow tracking granularity levels
#[derive(Debug, Clone)]
pub enum FlowTrackingGranularity {
    /// Per-packet tracking
    PerPacket,
    /// Per-flow tracking
    PerFlow,
    /// Aggregated tracking
    Aggregated,
    /// Sampled tracking
    Sampled { sampling_ratio: f64 },
}

/// Pattern analysis configuration and settings
#[derive(Debug, Clone)]
pub struct PatternAnalysisSettings {
    /// Analysis window size
    pub window_size: Duration,
    /// Pattern detection algorithms
    pub detection_algorithms: Vec<PatternDetectionAlgorithm>,
    /// Pattern classification
    pub classification: PatternClassification,
}

/// Pattern detection algorithms for traffic analysis
#[derive(Debug, Clone)]
pub enum PatternDetectionAlgorithm {
    /// Frequency analysis
    FrequencyAnalysis,
    /// Time series analysis
    TimeSeriesAnalysis,
    /// Spectral analysis
    SpectralAnalysis,
    /// Custom pattern detection
    Custom { algorithm_name: String },
}

/// Pattern classification configuration
#[derive(Debug, Clone)]
pub struct PatternClassification {
    /// Classification method
    pub method: ClassificationMethod,
    /// Pattern categories
    pub categories: Vec<String>,
    /// Classification confidence threshold
    pub confidence_threshold: f64,
}

/// Classification methods for pattern analysis
#[derive(Debug, Clone)]
pub enum ClassificationMethod {
    /// Rule-based classification
    RuleBased,
    /// Machine learning classification
    MachineLearning { model_path: String },
    /// Statistical classification
    Statistical,
    /// Hybrid classification
    Hybrid,
}

/// Anomaly detection configuration and settings
#[derive(Debug, Clone)]
pub struct AnomalyDetectionSettings {
    /// Detection method
    pub method: AnomalyDetectionMethod,
    /// Detection sensitivity
    pub sensitivity: f64,
    /// Baseline establishment
    pub baseline_establishment: BaselineEstablishment,
}

/// Anomaly detection methods for traffic monitoring
#[derive(Debug, Clone)]
pub enum AnomalyDetectionMethod {
    /// Statistical anomaly detection
    Statistical,
    /// Machine learning based
    MachineLearning { model_path: String },
    /// Clustering-based detection
    ClusteringBased,
    /// Time series anomaly detection
    TimeSeries,
}

/// Baseline establishment for anomaly detection
#[derive(Debug, Clone)]
pub struct BaselineEstablishment {
    /// Baseline learning period
    pub learning_period: Duration,
    /// Baseline update frequency
    pub update_frequency: Duration,
    /// Baseline adaptation rate
    pub adaptation_rate: f64,
}

/// Alert system configuration and settings
#[derive(Debug, Clone)]
pub struct AlertSettings {
    /// Alert channels
    pub alert_channels: Vec<AlertChannel>,
    /// Alert thresholds
    pub alert_thresholds: AlertThresholds,
    /// Alert escalation
    pub escalation: AlertEscalation,
}

/// Alert channels for notifications and communication
#[derive(Debug, Clone)]
pub enum AlertChannel {
    /// Email alerts
    Email { recipients: Vec<String> },
    /// SMS alerts
    SMS { phone_numbers: Vec<String> },
    /// Slack alerts
    Slack { webhook_url: String },
    /// Custom alert channel
    Custom {
        channel_name: String,
        config: HashMap<String, String>,
    },
}

/// Alert thresholds for different alert types
#[derive(Debug, Clone)]
pub struct AlertThresholds {
    /// Performance alert thresholds
    pub performance: PerformanceThresholds,
    /// Health alert thresholds
    pub health: HealthThresholds,
    /// Anomaly alert thresholds
    pub anomaly: AnomalyThresholds,
}

/// Health alert thresholds
#[derive(Debug, Clone)]
pub struct HealthThresholds {
    /// Device failure threshold
    pub device_failure: f64,
    /// Link failure threshold
    pub link_failure: f64,
    /// Degradation threshold
    pub degradation: f64,
}

/// Anomaly alert thresholds
#[derive(Debug, Clone)]
pub struct AnomalyThresholds {
    /// Anomaly score threshold
    pub score_threshold: f64,
    /// Anomaly frequency threshold
    pub frequency_threshold: f64,
    /// Anomaly severity threshold
    pub severity_threshold: f64,
}

/// Alert escalation configuration
#[derive(Debug, Clone)]
pub struct AlertEscalation {
    /// Escalation levels
    pub levels: Vec<EscalationLevel>,
    /// Escalation timers
    pub timers: Vec<Duration>,
    /// Escalation actions
    pub actions: Vec<EscalationAction>,
}

/// Escalation levels for alert management
#[derive(Debug, Clone)]
pub struct EscalationLevel {
    /// Level identifier
    pub level_id: String,
    /// Level priority
    pub priority: EscalationPriority,
    /// Notification targets
    pub targets: Vec<String>,
    /// Required acknowledgment
    pub require_ack: bool,
}

/// Escalation priorities for alert handling
#[derive(Debug, Clone, PartialEq, PartialOrd)]
pub enum EscalationPriority {
    /// Low priority escalation
    Low,
    /// Medium priority escalation
    Medium,
    /// High priority escalation
    High,
    /// Critical priority escalation
    Critical,
}

/// Escalation actions for alert handling
#[derive(Debug, Clone)]
pub enum EscalationAction {
    /// Send notification
    SendNotification { channel: AlertChannel },
    /// Execute script
    ExecuteScript { script_path: String },
    /// Trigger automation
    TriggerAutomation { automation_id: String },
    /// Custom escalation action
    Custom {
        action_name: String,
        parameters: HashMap<String, String>,
    },
}

/// Comprehensive metrics for communication patterns
#[derive(Debug, Clone)]
pub struct PatternMetrics {
    /// Performance metrics
    pub performance: PatternPerformanceMetrics,
    /// Resource utilization metrics
    pub utilization: PatternUtilizationMetrics,
    /// Quality metrics
    pub quality: PatternQualityMetrics,
    /// Efficiency metrics
    pub efficiency: PatternEfficiencyMetrics,
}

/// Performance metrics for communication patterns
#[derive(Debug, Clone)]
pub struct PatternPerformanceMetrics {
    /// Throughput (messages/second)
    pub throughput: f64,
    /// Latency (microseconds)
    pub latency: f64,
    /// Bandwidth utilization (Gbps)
    pub bandwidth_utilization: f64,
    /// Message success rate
    pub success_rate: f64,
}

/// Resource utilization metrics for patterns
#[derive(Debug, Clone)]
pub struct PatternUtilizationMetrics {
    /// Memory utilization
    pub memory_utilization: f64,
    /// Compute utilization
    pub compute_utilization: f64,
    /// Network utilization
    pub network_utilization: f64,
    /// Power utilization
    pub power_utilization: f64,
}

/// Quality metrics for communication patterns
#[derive(Debug, Clone)]
pub struct PatternQualityMetrics {
    /// Reliability score
    pub reliability: f64,
    /// Consistency score
    pub consistency: f64,
    /// Availability score
    pub availability: f64,
    /// Error rate
    pub error_rate: f64,
}

/// Efficiency metrics for communication patterns
#[derive(Debug, Clone)]
pub struct PatternEfficiencyMetrics {
    /// Communication efficiency
    pub communication_efficiency: f64,
    /// Resource efficiency
    pub resource_efficiency: f64,
    /// Energy efficiency
    pub energy_efficiency: f64,
    /// Cost efficiency
    pub cost_efficiency: f64,
}

/// Quality metrics for layout solutions
#[derive(Debug, Clone)]
pub struct SolutionQualityMetrics {
    /// Total communication cost
    pub communication_cost: f64,
    /// Resource utilization efficiency
    pub resource_efficiency: f64,
    /// Load balance score
    pub load_balance: f64,
    /// Fault tolerance score
    pub fault_tolerance: f64,
}

/// Metrics for optimization iterations
#[derive(Debug, Clone)]
pub struct IterationMetrics {
    /// Time taken for iteration
    pub iteration_time: Duration,
    /// Memory usage during iteration
    pub memory_usage: u64,
    /// Number of evaluations performed
    pub evaluations: usize,
    /// Improvement over previous iteration
    pub improvement: f64,
}

/// Comprehensive metrics for layout optimizer
#[derive(Debug, Clone)]
pub struct LayoutOptimizerMetrics {
    /// Total optimization time
    pub total_time: Duration,
    /// Number of iterations performed
    pub iterations_performed: usize,
    /// Best objective value achieved
    pub best_objective: f64,
    /// Convergence metrics
    pub convergence_metrics: ConvergenceMetrics,
    /// Resource utilization metrics
    pub resource_metrics: OptimizerResourceMetrics,
}

/// Convergence metrics for optimization algorithms
#[derive(Debug, Clone)]
pub struct ConvergenceMetrics {
    /// Convergence rate
    pub convergence_rate: f64,
    /// Time to convergence
    pub time_to_convergence: Duration,
    /// Final improvement rate
    pub final_improvement_rate: f64,
    /// Objective value progression
    pub objective_progression: Vec<f64>,
}

/// Resource utilization metrics for optimizer performance
#[derive(Debug, Clone)]
pub struct OptimizerResourceMetrics {
    /// Peak memory usage
    pub peak_memory: u64,
    /// Average CPU utilization
    pub avg_cpu_utilization: f64,
    /// Total energy consumption
    pub energy_consumption: f64,
    /// Resource efficiency score
    pub efficiency_score: f64,
}

/// Quality metrics for clustering algorithms
#[derive(Debug, Clone)]
pub struct ClusteringQualityMetrics {
    /// Silhouette score
    pub silhouette_score: f64,
    /// Davies-Bouldin index
    pub davies_bouldin_index: f64,
    /// Calinski-Harabasz index
    pub calinski_harabasz_index: f64,
    /// Inertia (within-cluster sum of squares)
    pub inertia: f64,
}

/// Performance statistics for layout systems
#[derive(Debug, Clone)]
pub struct LayoutPerformanceStatistics {
    /// Communication latency statistics
    pub latency_stats: LatencyStatistics,
    /// Bandwidth utilization statistics
    pub bandwidth_stats: BandwidthStatistics,
    /// Throughput statistics
    pub throughput_stats: ThroughputStatistics,
    /// Resource utilization statistics
    pub resource_stats: ResourceUtilizationStatistics,
}

/// Latency statistics for performance monitoring
#[derive(Debug, Clone)]
pub struct LatencyStatistics {
    /// Mean latency
    pub mean_latency: f64,
    /// Median latency
    pub median_latency: f64,
    /// 95th percentile latency
    pub p95_latency: f64,
    /// 99th percentile latency
    pub p99_latency: f64,
    /// Maximum latency observed
    pub max_latency: f64,
    /// Latency standard deviation
    pub latency_std_dev: f64,
}

/// Bandwidth utilization statistics
#[derive(Debug, Clone)]
pub struct BandwidthStatistics {
    /// Average bandwidth utilization
    pub avg_utilization: f64,
    /// Peak bandwidth utilization
    pub peak_utilization: f64,
    /// Bandwidth efficiency score
    pub efficiency_score: f64,
    /// Utilization distribution
    pub utilization_distribution: Vec<f64>,
}

/// Throughput statistics for performance analysis
#[derive(Debug, Clone)]
pub struct ThroughputStatistics {
    /// Average throughput
    pub avg_throughput: f64,
    /// Peak throughput
    pub peak_throughput: f64,
    /// Throughput variance
    pub throughput_variance: f64,
    /// Sustained throughput duration
    pub sustained_duration: Duration,
}

/// Resource utilization statistics
#[derive(Debug, Clone)]
pub struct ResourceUtilizationStatistics {
    /// Memory utilization statistics
    pub memory_utilization: UtilizationStats,
    /// CPU utilization statistics
    pub cpu_utilization: UtilizationStats,
    /// Network utilization statistics
    pub network_utilization: UtilizationStats,
    /// Storage utilization statistics
    pub storage_utilization: UtilizationStats,
}

/// General utilization statistics template
#[derive(Debug, Clone)]
pub struct UtilizationStats {
    /// Current utilization percentage
    pub current: f64,
    /// Average utilization percentage
    pub average: f64,
    /// Peak utilization percentage
    pub peak: f64,
    /// Utilization trend
    pub trend: UtilizationTrend,
}

/// Utilization trend indicators
#[derive(Debug, Clone)]
pub enum UtilizationTrend {
    /// Utilization is increasing
    Increasing,
    /// Utilization is decreasing
    Decreasing,
    /// Utilization is stable
    Stable,
    /// Utilization is fluctuating
    Fluctuating,
}

/// Alert system for managing notifications and responses
#[derive(Debug, Clone, Default)]
pub struct AlertSystem {
    /// Alert configuration
    pub config: AlertSettings,
    /// Active alerts
    pub active_alerts: Vec<Alert>,
    /// Alert history
    pub alert_history: Vec<AlertRecord>,
    /// Alert processors
    pub processors: Vec<AlertProcessor>,
}

/// Individual alert instance
#[derive(Debug, Clone)]
pub struct Alert {
    /// Alert identifier
    pub alert_id: String,
    /// Alert type
    pub alert_type: AlertType,
    /// Alert severity
    pub severity: AlertSeverity,
    /// Alert timestamp
    pub timestamp: Instant,
    /// Alert message
    pub message: String,
    /// Associated device ID
    pub device_id: Option<DeviceId>,
    /// Alert status
    pub status: AlertStatus,
}

/// Types of alerts that can be generated
#[derive(Debug, Clone)]
pub enum AlertType {
    /// Performance alert
    Performance,
    /// Health alert
    Health,
    /// Anomaly alert
    Anomaly,
    /// System alert
    System,
    /// Custom alert
    Custom { alert_name: String },
}

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

/// Alert status tracking
#[derive(Debug, Clone, PartialEq)]
pub enum AlertStatus {
    /// Alert is active
    Active,
    /// Alert is acknowledged
    Acknowledged,
    /// Alert is resolved
    Resolved,
    /// Alert is escalated
    Escalated,
}

/// Alert record for historical tracking
#[derive(Debug, Clone)]
pub struct AlertRecord {
    /// Alert instance
    pub alert: Alert,
    /// Actions taken
    pub actions_taken: Vec<String>,
    /// Resolution time
    pub resolution_time: Option<Duration>,
    /// Resolution method
    pub resolution_method: Option<String>,
}

/// Alert processor for handling specific alert types
#[derive(Debug, Clone)]
pub struct AlertProcessor {
    /// Processor identifier
    pub processor_id: String,
    /// Supported alert types
    pub supported_types: Vec<AlertType>,
    /// Processing configuration
    pub config: AlertProcessorConfig,
}

/// Alert processor configuration
#[derive(Debug, Clone)]
pub struct AlertProcessorConfig {
    /// Enable automatic processing
    pub auto_process: bool,
    /// Processing timeout
    pub timeout: Duration,
    /// Retry configuration
    pub retry_config: RetryConfig,
}

/// Retry configuration for alert processing
#[derive(Debug, Clone)]
pub struct RetryConfig {
    /// Maximum retry attempts
    pub max_retries: usize,
    /// Retry delay
    pub retry_delay: Duration,
    /// Exponential backoff factor
    pub backoff_factor: f64,
}

/// Metrics collection engine
#[derive(Debug, Clone, Default)]
pub struct MetricsCollector {
    /// Collection configuration
    pub config: MetricsCollectionSettings,
    /// Collected metrics
    pub metrics: TopologyMetrics,
    /// Collection history
    pub history: Vec<MetricsSnapshot>,
    /// Active collectors
    pub collectors: Vec<MetricCollector>,
}

/// Individual metric collector
#[derive(Debug, Clone)]
pub struct MetricCollector {
    /// Collector identifier
    pub collector_id: String,
    /// Metric type
    pub metric_type: MetricType,
    /// Collection interval
    pub interval: Duration,
    /// Last collection time
    pub last_collection: Instant,
}

/// Metrics snapshot for historical analysis
#[derive(Debug, Clone)]
pub struct MetricsSnapshot {
    /// Snapshot timestamp
    pub timestamp: Instant,
    /// Metrics data
    pub metrics: TopologyMetrics,
    /// Snapshot metadata
    pub metadata: SnapshotMetadata,
}

/// Metadata for metrics snapshots
#[derive(Debug, Clone)]
pub struct SnapshotMetadata {
    /// Collection source
    pub source: String,
    /// Collection method
    pub method: String,
    /// Data quality score
    pub quality_score: f64,
}

/// Anomaly detection system
#[derive(Debug, Clone)]
pub struct AnomalyDetector {
    /// Detection configuration
    pub config: AnomalyDetectionSettings,
    /// Detection models
    pub models: Vec<AnomalyDetectionModel>,
    /// Detected anomalies
    pub anomalies: Vec<DetectedAnomaly>,
    /// Detection statistics
    pub statistics: AnomalyDetectionStatistics,
    /// Bounded rolling history of recent values per metric name.
    ///
    /// Used to build an online mean/standard-deviation baseline for z-score
    /// based anomaly detection. Each deque is capped at
    /// [`TopologyPerformanceMonitor::ANOMALY_HISTORY_CAPACITY`] samples.
    pub value_history: HashMap<String, VecDeque<f64>>,
}

/// Anomaly detection model
#[derive(Debug, Clone)]
pub struct AnomalyDetectionModel {
    /// Model identifier
    pub model_id: String,
    /// Model type
    pub model_type: AnomalyDetectionMethod,
    /// Model accuracy
    pub accuracy: f64,
    /// Last training time
    pub last_training: Instant,
    /// Model status
    pub status: ModelStatus,
}

/// Model status for anomaly detection
#[derive(Debug, Clone, PartialEq)]
pub enum ModelStatus {
    /// Model is training
    Training,
    /// Model is ready
    Ready,
    /// Model is updating
    Updating,
    /// Model has failed
    Failed,
}

/// Detected anomaly instance
#[derive(Debug, Clone)]
pub struct DetectedAnomaly {
    /// Anomaly identifier
    pub anomaly_id: String,
    /// Detection timestamp
    pub timestamp: Instant,
    /// Anomaly type
    pub anomaly_type: AnomalyType,
    /// Anomaly score
    pub score: f64,
    /// Associated metrics
    pub metrics: HashMap<String, f64>,
    /// Anomaly status
    pub status: AnomalyStatus,
}

/// Types of anomalies that can be detected
#[derive(Debug, Clone)]
pub enum AnomalyType {
    /// Performance anomaly
    Performance,
    /// Traffic pattern anomaly
    TrafficPattern,
    /// Resource utilization anomaly
    ResourceUtilization,
    /// Communication anomaly
    Communication,
    /// Custom anomaly
    Custom { anomaly_name: String },
}

/// Status of detected anomalies
#[derive(Debug, Clone, PartialEq)]
pub enum AnomalyStatus {
    /// Anomaly is new
    New,
    /// Anomaly is under investigation
    Investigating,
    /// Anomaly is confirmed
    Confirmed,
    /// Anomaly is false positive
    FalsePositive,
    /// Anomaly is resolved
    Resolved,
}

/// Statistics for anomaly detection system
#[derive(Debug, Clone)]
pub struct AnomalyDetectionStatistics {
    /// Total anomalies detected
    pub total_detected: usize,
    /// False positive rate
    pub false_positive_rate: f64,
    /// Detection accuracy
    pub detection_accuracy: f64,
    /// Average detection time
    pub avg_detection_time: Duration,
}

/// Performance analytics system
#[derive(Debug, Clone)]
pub struct PerformanceAnalytics {
    /// Analytics configuration
    pub config: AnalyticsConfig,
    /// Performance reports
    pub reports: Vec<PerformanceReport>,
    /// Trend analysis
    pub trend_analysis: TrendAnalysis,
    /// Predictive models
    pub predictive_models: Vec<PredictiveModel>,
}

/// Configuration for performance analytics
#[derive(Debug, Clone)]
pub struct AnalyticsConfig {
    /// Analysis window size
    pub analysis_window: Duration,
    /// Report generation frequency
    pub report_frequency: Duration,
    /// Enable predictive analytics
    pub enable_prediction: bool,
    /// Prediction horizon
    pub prediction_horizon: Duration,
}

/// Performance report generation
#[derive(Debug, Clone)]
pub struct PerformanceReport {
    /// Report identifier
    pub report_id: String,
    /// Report timestamp
    pub timestamp: Instant,
    /// Report period
    pub period: Duration,
    /// Performance summary
    pub summary: PerformanceSummary,
    /// Detailed metrics
    pub detailed_metrics: TopologyMetrics,
    /// Recommendations
    pub recommendations: Vec<PerformanceRecommendation>,
}

/// Performance summary for reports
#[derive(Debug, Clone)]
pub struct PerformanceSummary {
    /// Overall performance score
    pub overall_score: f64,
    /// Key performance indicators
    pub kpis: HashMap<String, f64>,
    /// Performance trends
    pub trends: Vec<PerformanceTrend>,
    /// Critical issues
    pub critical_issues: Vec<String>,
}

/// Performance trend analysis
#[derive(Debug, Clone)]
pub struct PerformanceTrend {
    /// Metric name
    pub metric_name: String,
    /// Trend direction
    pub direction: TrendDirection,
    /// Trend strength
    pub strength: f64,
    /// Confidence level
    pub confidence: f64,
}

/// Trend direction indicators
#[derive(Debug, Clone)]
pub enum TrendDirection {
    /// Improving trend
    Improving,
    /// Degrading trend
    Degrading,
    /// Stable trend
    Stable,
    /// Volatile trend
    Volatile,
}

/// Performance recommendations
#[derive(Debug, Clone)]
pub struct PerformanceRecommendation {
    /// Recommendation identifier
    pub recommendation_id: String,
    /// Recommendation type
    pub recommendation_type: RecommendationType,
    /// Priority level
    pub priority: RecommendationPriority,
    /// Description
    pub description: String,
    /// Expected impact
    pub expected_impact: f64,
}

/// Types of performance recommendations
#[derive(Debug, Clone)]
pub enum RecommendationType {
    /// Configuration optimization
    ConfigurationOptimization,
    /// Resource allocation
    ResourceAllocation,
    /// Topology adjustment
    TopologyAdjustment,
    /// Performance tuning
    PerformanceTuning,
    /// Custom recommendation
    Custom { recommendation_name: String },
}

/// Priority levels for recommendations
#[derive(Debug, Clone, PartialEq, PartialOrd)]
pub enum RecommendationPriority {
    /// Low priority
    Low,
    /// Medium priority
    Medium,
    /// High priority
    High,
    /// Critical priority
    Critical,
}

/// Trend analysis system
#[derive(Debug, Clone)]
pub struct TrendAnalysis {
    /// Analysis configuration
    pub config: TrendAnalysisConfig,
    /// Detected trends
    pub trends: Vec<DetectedTrend>,
    /// Trend predictions
    pub predictions: Vec<TrendPrediction>,
}

/// Configuration for trend analysis
#[derive(Debug, Clone)]
pub struct TrendAnalysisConfig {
    /// Analysis window size
    pub window_size: Duration,
    /// Minimum trend duration
    pub min_trend_duration: Duration,
    /// Trend detection sensitivity
    pub sensitivity: f64,
}

/// Detected trend information
#[derive(Debug, Clone)]
pub struct DetectedTrend {
    /// Trend identifier
    pub trend_id: String,
    /// Metric name
    pub metric_name: String,
    /// Trend type
    pub trend_type: TrendType,
    /// Start time
    pub start_time: Instant,
    /// Duration
    pub duration: Duration,
    /// Trend strength
    pub strength: f64,
}

/// Types of trends that can be detected
#[derive(Debug, Clone)]
pub enum TrendType {
    /// Linear trend
    Linear { slope: f64 },
    /// Exponential trend
    Exponential { rate: f64 },
    /// Periodic trend
    Periodic { period: Duration, amplitude: f64 },
    /// Step change
    StepChange { change_magnitude: f64 },
}

/// Trend prediction information
#[derive(Debug, Clone)]
pub struct TrendPrediction {
    /// Prediction identifier
    pub prediction_id: String,
    /// Predicted metric
    pub metric_name: String,
    /// Prediction horizon
    pub horizon: Duration,
    /// Predicted values
    pub predicted_values: Vec<f64>,
    /// Confidence intervals
    pub confidence_intervals: Vec<(f64, f64)>,
}

/// Predictive model for performance forecasting
#[derive(Debug, Clone)]
pub struct PredictiveModel {
    /// Model identifier
    pub model_id: String,
    /// Model type
    pub model_type: PredictiveModelType,
    /// Model accuracy
    pub accuracy: f64,
    /// Training data size
    pub training_data_size: usize,
    /// Last training time
    pub last_training: Instant,
}

/// Types of predictive models
#[derive(Debug, Clone)]
pub enum PredictiveModelType {
    /// Time series forecasting
    TimeSeriesForecasting,
    /// Regression model
    Regression,
    /// Neural network
    NeuralNetwork,
    /// Ensemble model
    Ensemble,
    /// Custom model
    Custom { model_name: String },
}

/// Health check result
#[derive(Debug, Clone)]
pub struct HealthCheckResult {
    /// Health indicator checked
    pub indicator: HealthIndicator,
    /// Health status result
    pub status: HealthStatus,
    /// Check timestamp
    pub timestamp: Instant,
    /// Additional details
    pub details: String,
}

/// Health status indicators
#[derive(Debug, Clone, PartialEq)]
pub enum HealthStatus {
    /// System is healthy
    Healthy,
    /// System has warnings
    Warning,
    /// System has errors
    Error,
    /// System is critical
    Critical,
    /// Status is unknown
    Unknown,
}