quantrs2-circuit 0.1.3

Quantum circuit representation and DSL for the QuantRS2 framework
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
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
//! Resource estimator using `SciRS2` complexity analysis
//!
//! This module provides comprehensive resource estimation for quantum circuits,
//! including gate counts, circuit depth, memory requirements, and execution time
//! estimation using `SciRS2`'s advanced complexity analysis capabilities.

use crate::builder::Circuit;
use crate::scirs2_integration::{AnalyzerConfig, GraphMetrics, SciRS2CircuitAnalyzer};
use quantrs2_core::{
    error::{QuantRS2Error, QuantRS2Result},
    gate::GateOp,
    qubit::QubitId,
};
use scirs2_core::ndarray::Array2;
use scirs2_core::Complex64;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::time::Duration;

/// Comprehensive resource estimation result
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ResourceEstimate {
    /// Circuit-level resource metrics
    pub circuit_metrics: CircuitMetrics,
    /// Computational complexity analysis
    pub complexity_analysis: ComplexityAnalysis,
    /// Memory requirements estimation
    pub memory_requirements: MemoryRequirements,
    /// Execution time estimation
    pub execution_time: ExecutionTimeEstimate,
    /// Hardware-specific requirements
    pub hardware_requirements: HardwareRequirements,
    /// `SciRS2` graph analysis metrics
    pub graph_metrics: Option<GraphMetrics>,
    /// Scalability analysis
    pub scalability_analysis: ScalabilityAnalysis,
    /// Optimization suggestions
    pub optimization_suggestions: Vec<OptimizationSuggestion>,
}

/// Basic circuit metrics
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CircuitMetrics {
    /// Total number of gates
    pub total_gates: usize,
    /// Gate count by type
    pub gate_counts: HashMap<String, usize>,
    /// Circuit depth (critical path length)
    pub circuit_depth: usize,
    /// Number of qubits used
    pub qubit_count: usize,
    /// Number of two-qubit gates
    pub two_qubit_gates: usize,
    /// Number of single-qubit gates
    pub single_qubit_gates: usize,
    /// Number of multi-qubit gates (3+ qubits)
    pub multi_qubit_gates: usize,
    /// Quantum volume estimate
    pub quantum_volume: f64,
    /// Circuit fidelity estimate
    pub fidelity_estimate: f64,
}

/// Computational complexity analysis
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ComplexityAnalysis {
    /// Time complexity class
    pub time_complexity: ComplexityClass,
    /// Space complexity class
    pub space_complexity: ComplexityClass,
    /// Gate complexity (product of gates and qubits)
    pub gate_complexity: f64,
    /// Entanglement complexity
    pub entanglement_complexity: f64,
    /// Classical simulation complexity
    pub classical_simulation_complexity: f64,
    /// Quantum advantage factor
    pub quantum_advantage_factor: Option<f64>,
    /// Algorithm classification
    pub algorithm_classification: AlgorithmClass,
    /// Scaling behavior
    pub scaling_behavior: ScalingBehavior,
}

/// Complexity classes for quantum algorithms
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum ComplexityClass {
    /// Constant complexity O(1)
    Constant,
    /// Logarithmic complexity O(log n)
    Logarithmic,
    /// Linear complexity O(n)
    Linear,
    /// Polynomial complexity O(n^k)
    Polynomial { degree: f64 },
    /// Exponential complexity O(2^n)
    Exponential,
    /// Super-exponential complexity
    SuperExponential,
    /// Unknown or custom complexity
    Custom { description: String },
}

/// Algorithm classification
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum AlgorithmClass {
    /// Quantum Fourier Transform based
    QftBased,
    /// Amplitude amplification based
    AmplitudeAmplification,
    /// Variational quantum algorithm
    Variational,
    /// Quantum walk based
    QuantumWalk,
    /// Adiabatic quantum computation
    Adiabatic,
    /// Quantum error correction
    ErrorCorrection,
    /// Quantum machine learning
    QuantumML,
    /// Quantum simulation
    QuantumSimulation,
    /// Quantum cryptography
    Cryptography,
    /// Quantum optimization
    Optimization,
    /// General quantum circuit
    General,
}

/// Scaling behavior analysis
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ScalingBehavior {
    /// How gates scale with problem size
    pub gate_scaling: ScalingFunction,
    /// How depth scales with problem size
    pub depth_scaling: ScalingFunction,
    /// How qubits scale with problem size
    pub qubit_scaling: ScalingFunction,
    /// How execution time scales
    pub time_scaling: ScalingFunction,
}

/// Mathematical scaling function
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum ScalingFunction {
    /// Constant scaling
    Constant { value: f64 },
    /// Linear scaling
    Linear { coefficient: f64 },
    /// Polynomial scaling
    Polynomial { coefficient: f64, exponent: f64 },
    /// Exponential scaling
    Exponential { base: f64, coefficient: f64 },
    /// Logarithmic scaling
    Logarithmic { coefficient: f64 },
    /// Custom function
    Custom {
        description: String,
        complexity: f64,
    },
}

/// Memory requirements estimation
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MemoryRequirements {
    /// Classical memory for state vector (bytes)
    pub state_vector_memory: u64,
    /// Classical memory for gate matrices (bytes)
    pub gate_matrix_memory: u64,
    /// Auxiliary memory for computation (bytes)
    pub auxiliary_memory: u64,
    /// Total classical memory required (bytes)
    pub total_classical_memory: u64,
    /// Quantum memory (number of qubits)
    pub quantum_memory: usize,
    /// Memory complexity scaling
    pub memory_scaling: ScalingFunction,
    /// Memory optimization suggestions
    pub memory_optimizations: Vec<String>,
}

/// Execution time estimation
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ExecutionTimeEstimate {
    /// Estimated execution time
    pub estimated_time: Duration,
    /// Gate execution time breakdown
    pub gate_time_breakdown: HashMap<String, Duration>,
    /// Critical path execution time
    pub critical_path_time: Duration,
    /// Parallelization factor
    pub parallelization_factor: f64,
    /// Hardware-dependent timing factors
    pub hardware_timing_factors: HashMap<String, f64>,
    /// Confidence interval
    pub confidence_interval: (Duration, Duration),
    /// Timing model used
    pub timing_model: TimingModel,
}

/// Timing models for execution estimation
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum TimingModel {
    /// Simple gate counting model
    GateCounting { gates_per_second: f64 },
    /// Physics-based model with T1/T2 times
    PhysicsBased {
        t1_time: Duration,
        t2_time: Duration,
        gate_times: HashMap<String, Duration>,
    },
    /// Machine learning predicted times
    MachineLearning { model_id: String, accuracy: f64 },
    /// Benchmark-based empirical model
    Empirical { benchmark_data: String },
}

/// Hardware-specific requirements
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct HardwareRequirements {
    /// Minimum number of physical qubits
    pub min_physical_qubits: usize,
    /// Connectivity requirements
    pub connectivity_requirements: ConnectivityRequirement,
    /// Gate fidelity requirements
    pub fidelity_requirements: HashMap<String, f64>,
    /// Coherence time requirements
    pub coherence_requirements: CoherenceRequirement,
    /// Hardware platform recommendations
    pub platform_recommendations: Vec<PlatformRecommendation>,
    /// Error correction overhead
    pub error_correction_overhead: ErrorCorrectionOverhead,
}

/// Connectivity requirements for quantum hardware
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum ConnectivityRequirement {
    /// All-to-all connectivity required
    AllToAll,
    /// Linear nearest-neighbor connectivity
    Linear,
    /// Grid connectivity
    Grid { dimensions: (usize, usize) },
    /// Specific connectivity graph
    Custom { adjacency_matrix: Vec<Vec<bool>> },
    /// Minimum connectivity degree
    MinimumDegree { degree: usize },
}

/// Coherence time requirements
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CoherenceRequirement {
    /// Minimum T1 time required
    pub min_t1: Duration,
    /// Minimum T2 time required
    pub min_t2: Duration,
    /// Required gate time to coherence time ratio
    pub gate_to_coherence_ratio: f64,
}

/// Platform recommendation
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PlatformRecommendation {
    /// Platform name
    pub platform: String,
    /// Suitability score (0.0 to 1.0)
    pub suitability_score: f64,
    /// Reasoning for recommendation
    pub reasoning: String,
    /// Estimated success probability
    pub success_probability: f64,
    /// Required modifications
    pub required_modifications: Vec<String>,
}

/// Error correction overhead analysis
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ErrorCorrectionOverhead {
    /// Physical to logical qubit ratio
    pub physical_to_logical_ratio: f64,
    /// Gate count overhead factor
    pub gate_overhead_factor: f64,
    /// Time overhead factor
    pub time_overhead_factor: f64,
    /// Recommended error correction code
    pub recommended_code: String,
    /// Threshold error rate required
    pub threshold_error_rate: f64,
}

/// Scalability analysis
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ScalabilityAnalysis {
    /// Scalability score (0.0 to 1.0)
    pub scalability_score: f64,
    /// Bottleneck identification
    pub bottlenecks: Vec<ScalabilityBottleneck>,
    /// Scaling predictions
    pub scaling_predictions: HashMap<String, ScalingPrediction>,
    /// Resource limits
    pub resource_limits: ResourceLimits,
}

/// Scalability bottleneck
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ScalabilityBottleneck {
    /// Bottleneck type
    pub bottleneck_type: BottleneckType,
    /// Severity (0.0 to 1.0)
    pub severity: f64,
    /// Description
    pub description: String,
    /// Mitigation suggestions
    pub mitigation_suggestions: Vec<String>,
}

/// Types of scalability bottlenecks
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum BottleneckType {
    /// Memory bottleneck
    Memory,
    /// Computation time bottleneck
    ComputationTime,
    /// Quantum coherence bottleneck
    QuantumCoherence,
    /// Hardware connectivity bottleneck
    Connectivity,
    /// Error rate bottleneck
    ErrorRate,
    /// Classical processing bottleneck
    ClassicalProcessing,
}

/// Scaling prediction for different problem sizes
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ScalingPrediction {
    /// Problem sizes to predict for
    pub problem_sizes: Vec<usize>,
    /// Predicted resource values
    pub predicted_values: Vec<f64>,
    /// Confidence intervals
    pub confidence_intervals: Vec<(f64, f64)>,
    /// Prediction model used
    pub model: String,
}

/// Resource limits for different scales
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ResourceLimits {
    /// Maximum feasible problem size with current technology
    pub max_current_technology: usize,
    /// Maximum feasible with near-term improvements
    pub max_near_term: usize,
    /// Maximum theoretical limit
    pub max_theoretical: Option<usize>,
    /// Limiting factors
    pub limiting_factors: Vec<String>,
}

/// Optimization suggestion
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct OptimizationSuggestion {
    /// Suggestion type
    pub suggestion_type: OptimizationType,
    /// Expected improvement
    pub expected_improvement: f64,
    /// Implementation complexity
    pub implementation_complexity: ComplexityLevel,
    /// Description
    pub description: String,
    /// Code impact areas
    pub impact_areas: Vec<String>,
}

/// Types of optimization suggestions
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum OptimizationType {
    /// Gate count reduction
    GateCountReduction,
    /// Depth reduction
    DepthReduction,
    /// Memory optimization
    MemoryOptimization,
    /// Parallelization opportunity
    Parallelization,
    /// Algorithm substitution
    AlgorithmSubstitution,
    /// Hardware-specific optimization
    HardwareOptimization,
    /// Error mitigation
    ErrorMitigation,
}

/// Implementation complexity levels
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum ComplexityLevel {
    /// Low complexity (easy to implement)
    Low,
    /// Medium complexity (moderate effort)
    Medium,
    /// High complexity (significant effort)
    High,
    /// Research required
    Research,
}

/// Resource estimation configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ResourceEstimatorConfig {
    /// Enable detailed analysis
    pub enable_detailed_analysis: bool,
    /// Enable `SciRS2` graph analysis
    pub enable_graph_analysis: bool,
    /// Enable scalability analysis
    pub enable_scalability_analysis: bool,
    /// Enable hardware-specific analysis
    pub enable_hardware_analysis: bool,
    /// Target hardware platforms
    pub target_platforms: Vec<String>,
    /// Analysis depth level
    pub analysis_depth: AnalysisDepth,
    /// Include optimization suggestions
    pub include_optimizations: bool,
    /// `SciRS2` analyzer configuration
    pub scirs2_config: Option<AnalyzerConfig>,
}

/// Analysis depth levels
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum AnalysisDepth {
    /// Basic gate counting only
    Basic,
    /// Standard complexity analysis
    Standard,
    /// Comprehensive analysis
    Comprehensive,
    /// Research-grade analysis
    Research,
}

impl Default for ResourceEstimatorConfig {
    fn default() -> Self {
        Self {
            enable_detailed_analysis: true,
            enable_graph_analysis: true,
            enable_scalability_analysis: true,
            enable_hardware_analysis: true,
            target_platforms: vec![
                "IBM Quantum".to_string(),
                "Google Quantum AI".to_string(),
                "IonQ".to_string(),
                "Rigetti".to_string(),
            ],
            analysis_depth: AnalysisDepth::Standard,
            include_optimizations: true,
            scirs2_config: None,
        }
    }
}

/// SciRS2-powered resource estimator
pub struct ResourceEstimator {
    config: ResourceEstimatorConfig,
    scirs2_analyzer: Option<SciRS2CircuitAnalyzer>,
    gate_cost_database: HashMap<String, GateCost>,
    platform_database: HashMap<String, PlatformCharacteristics>,
}

/// Cost characteristics for different gates
#[derive(Debug, Clone)]
pub struct GateCost {
    /// Execution time
    pub execution_time: Duration,
    /// Error rate
    pub error_rate: f64,
    /// Energy consumption
    pub energy_cost: f64,
    /// Resource overhead
    pub resource_overhead: f64,
}

/// Platform characteristics database
#[derive(Debug, Clone)]
pub struct PlatformCharacteristics {
    /// Platform name
    pub name: String,
    /// Qubit count
    pub qubit_count: usize,
    /// Connectivity topology
    pub connectivity: ConnectivityRequirement,
    /// Gate fidelities
    pub gate_fidelities: HashMap<String, f64>,
    /// Coherence times
    pub coherence_times: CoherenceRequirement,
    /// Gate set supported
    pub native_gates: Vec<String>,
    /// Measurement fidelity
    pub measurement_fidelity: f64,
}

impl ResourceEstimator {
    /// Create a new resource estimator
    #[must_use]
    pub fn new(config: ResourceEstimatorConfig) -> Self {
        let scirs2_analyzer = if config.enable_graph_analysis {
            Some(SciRS2CircuitAnalyzer::new())
        } else {
            None
        };

        let mut estimator = Self {
            config,
            scirs2_analyzer,
            gate_cost_database: HashMap::new(),
            platform_database: HashMap::new(),
        };

        estimator.initialize_databases();
        estimator
    }

    /// Create resource estimator with custom `SciRS2` configuration
    #[must_use]
    pub fn with_scirs2_config(
        config: ResourceEstimatorConfig,
        scirs2_config: AnalyzerConfig,
    ) -> Self {
        let scirs2_analyzer = Some(SciRS2CircuitAnalyzer::with_config(scirs2_config));

        let mut estimator = Self {
            config,
            scirs2_analyzer,
            gate_cost_database: HashMap::new(),
            platform_database: HashMap::new(),
        };

        estimator.initialize_databases();
        estimator
    }

    /// Estimate resources for a quantum circuit
    pub fn estimate_resources<const N: usize>(
        &mut self,
        circuit: &Circuit<N>,
    ) -> QuantRS2Result<ResourceEstimate> {
        // Calculate basic circuit metrics
        let circuit_metrics = self.calculate_circuit_metrics(circuit)?;

        // Perform complexity analysis
        let complexity_analysis = self.analyze_complexity(circuit, &circuit_metrics)?;

        // Estimate memory requirements
        let memory_requirements = self.estimate_memory_requirements(circuit, &circuit_metrics)?;

        // Estimate execution time
        let execution_time = self.estimate_execution_time(circuit, &circuit_metrics)?;

        // Analyze hardware requirements
        let hardware_requirements = if self.config.enable_hardware_analysis {
            self.analyze_hardware_requirements(circuit, &circuit_metrics)?
        } else {
            self.default_hardware_requirements()
        };

        // Get SciRS2 graph metrics if enabled
        let graph_metrics = if self.config.enable_graph_analysis {
            self.get_graph_metrics(circuit)?
        } else {
            None
        };

        // Perform scalability analysis
        let scalability_analysis = if self.config.enable_scalability_analysis {
            self.analyze_scalability(circuit, &circuit_metrics, &complexity_analysis)?
        } else {
            self.default_scalability_analysis()
        };

        // Generate optimization suggestions
        let optimization_suggestions = if self.config.include_optimizations {
            self.generate_optimization_suggestions(
                circuit,
                &circuit_metrics,
                &complexity_analysis,
                &memory_requirements,
            )?
        } else {
            Vec::new()
        };

        Ok(ResourceEstimate {
            circuit_metrics,
            complexity_analysis,
            memory_requirements,
            execution_time,
            hardware_requirements,
            graph_metrics,
            scalability_analysis,
            optimization_suggestions,
        })
    }

    /// Initialize gate cost and platform databases
    fn initialize_databases(&mut self) {
        // Initialize gate cost database
        self.gate_cost_database.insert(
            "H".to_string(),
            GateCost {
                execution_time: Duration::from_nanos(20),
                error_rate: 0.001,
                energy_cost: 1.0,
                resource_overhead: 1.0,
            },
        );

        self.gate_cost_database.insert(
            "X".to_string(),
            GateCost {
                execution_time: Duration::from_nanos(20),
                error_rate: 0.001,
                energy_cost: 1.0,
                resource_overhead: 1.0,
            },
        );

        self.gate_cost_database.insert(
            "CNOT".to_string(),
            GateCost {
                execution_time: Duration::from_nanos(200),
                error_rate: 0.01,
                energy_cost: 5.0,
                resource_overhead: 2.0,
            },
        );

        // Initialize platform database
        self.platform_database.insert(
            "IBM Quantum".to_string(),
            PlatformCharacteristics {
                name: "IBM Quantum".to_string(),
                qubit_count: 127,
                connectivity: ConnectivityRequirement::Custom {
                    adjacency_matrix: Vec::new(), // Would contain actual IBM topology
                },
                gate_fidelities: [
                    ("H".to_string(), 0.999),
                    ("X".to_string(), 0.999),
                    ("CNOT".to_string(), 0.99),
                ]
                .iter()
                .cloned()
                .collect(),
                coherence_times: CoherenceRequirement {
                    min_t1: Duration::from_micros(100),
                    min_t2: Duration::from_micros(50),
                    gate_to_coherence_ratio: 0.01,
                },
                native_gates: vec![
                    "RZ".to_string(),
                    "SX".to_string(),
                    "X".to_string(),
                    "CNOT".to_string(),
                ],
                measurement_fidelity: 0.98,
            },
        );

        // Add more platforms...
    }

    /// Calculate basic circuit metrics
    fn calculate_circuit_metrics<const N: usize>(
        &self,
        circuit: &Circuit<N>,
    ) -> QuantRS2Result<CircuitMetrics> {
        let gates = circuit.gates();
        let total_gates = gates.len();

        let mut gate_counts = HashMap::new();
        let mut single_qubit_gates = 0;
        let mut two_qubit_gates = 0;
        let mut multi_qubit_gates = 0;

        for gate in gates {
            let gate_name = gate.name();
            *gate_counts.entry(gate_name.to_string()).or_insert(0) += 1;

            match gate.qubits().len() {
                1 => single_qubit_gates += 1,
                2 => two_qubit_gates += 1,
                n if n > 2 => multi_qubit_gates += 1,
                _ => {}
            }
        }

        // Calculate circuit depth (simplified)
        let circuit_depth = self.calculate_circuit_depth(circuit)?;

        // Estimate quantum volume
        let quantum_volume = (N as f64).min(circuit_depth as f64).powi(2);

        // Estimate fidelity
        let fidelity_estimate = self.estimate_circuit_fidelity(circuit, &gate_counts)?;

        Ok(CircuitMetrics {
            total_gates,
            gate_counts,
            circuit_depth,
            qubit_count: N,
            two_qubit_gates,
            single_qubit_gates,
            multi_qubit_gates,
            quantum_volume,
            fidelity_estimate,
        })
    }

    /// Calculate circuit depth using topological analysis
    fn calculate_circuit_depth<const N: usize>(
        &self,
        circuit: &Circuit<N>,
    ) -> QuantRS2Result<usize> {
        // Simplified depth calculation - would use proper DAG analysis in practice
        let gates = circuit.gates();
        if gates.is_empty() {
            return Ok(0);
        }

        // For now, return a rough estimate based on gate dependencies
        // In a full implementation, this would use proper topological sorting
        let mut depth_per_qubit = vec![0; N];

        for gate in gates {
            let qubits = gate.qubits();
            let max_current_depth = qubits
                .iter()
                .map(|q| depth_per_qubit[q.id() as usize])
                .max()
                .unwrap_or(0);

            for qubit in qubits {
                depth_per_qubit[qubit.id() as usize] = max_current_depth + 1;
            }
        }

        Ok(depth_per_qubit.into_iter().max().unwrap_or(0))
    }

    /// Estimate circuit fidelity based on gate error rates
    fn estimate_circuit_fidelity<const N: usize>(
        &self,
        circuit: &Circuit<N>,
        gate_counts: &HashMap<String, usize>,
    ) -> QuantRS2Result<f64> {
        let mut total_error_rate = 0.0;

        for (gate_name, count) in gate_counts {
            if let Some(gate_cost) = self.gate_cost_database.get(gate_name) {
                total_error_rate += gate_cost.error_rate * (*count as f64);
            } else {
                // Default error rate for unknown gates
                total_error_rate += 0.01 * (*count as f64);
            }
        }

        let fidelity = (1.0 - total_error_rate).clamp(0.0, 1.0);
        Ok(fidelity)
    }

    /// Analyze computational complexity
    fn analyze_complexity<const N: usize>(
        &self,
        circuit: &Circuit<N>,
        metrics: &CircuitMetrics,
    ) -> QuantRS2Result<ComplexityAnalysis> {
        // Analyze time complexity based on gate count and circuit structure
        let time_complexity = if metrics.total_gates <= 100 {
            ComplexityClass::Constant
        } else if metrics.total_gates < 1000 {
            ComplexityClass::Linear
        } else {
            ComplexityClass::Polynomial { degree: 2.0 }
        };

        // Analyze space complexity (exponential in qubit count for classical simulation)
        let space_complexity = ComplexityClass::Exponential;

        // Calculate gate complexity
        let gate_complexity = (metrics.total_gates as f64) * (N as f64);

        // Estimate entanglement complexity (simplified)
        let entanglement_complexity =
            (metrics.two_qubit_gates as f64) / (metrics.total_gates as f64).max(1.0);

        // Classical simulation complexity
        let classical_simulation_complexity = (N as f64).exp2();

        // Quantum advantage factor (simplified estimation)
        let quantum_advantage_factor = if classical_simulation_complexity > 1e6 {
            Some(classical_simulation_complexity / (metrics.total_gates as f64))
        } else {
            None
        };

        // Algorithm classification (simplified heuristic)
        let algorithm_classification = self.classify_algorithm(circuit, metrics)?;

        // Scaling behavior analysis
        let scaling_behavior = self.analyze_scaling_behavior(metrics)?;

        Ok(ComplexityAnalysis {
            time_complexity,
            space_complexity,
            gate_complexity,
            entanglement_complexity,
            classical_simulation_complexity,
            quantum_advantage_factor,
            algorithm_classification,
            scaling_behavior,
        })
    }

    /// Classify the quantum algorithm based on circuit structure
    fn classify_algorithm<const N: usize>(
        &self,
        circuit: &Circuit<N>,
        metrics: &CircuitMetrics,
    ) -> QuantRS2Result<AlgorithmClass> {
        // Simplified algorithm classification based on gate patterns
        let gates = circuit.gates();

        // Check for QFT patterns (many H gates)
        if let Some(&h_count) = metrics.gate_counts.get("H") {
            if h_count > N / 2 {
                return Ok(AlgorithmClass::QftBased);
            }
        }

        // Check for amplitude amplification (controlled gates + H gates)
        if metrics.two_qubit_gates > metrics.single_qubit_gates {
            return Ok(AlgorithmClass::AmplitudeAmplification);
        }

        // Check for variational patterns (parameterized gates)
        // This would require checking for RX, RY, RZ gates in practice
        if metrics.circuit_depth > metrics.total_gates / 4 {
            return Ok(AlgorithmClass::Variational);
        }

        Ok(AlgorithmClass::General)
    }

    /// Analyze scaling behavior
    fn analyze_scaling_behavior(
        &self,
        metrics: &CircuitMetrics,
    ) -> QuantRS2Result<ScalingBehavior> {
        Ok(ScalingBehavior {
            gate_scaling: ScalingFunction::Linear {
                coefficient: metrics.total_gates as f64 / metrics.qubit_count as f64,
            },
            depth_scaling: ScalingFunction::Linear {
                coefficient: metrics.circuit_depth as f64 / metrics.qubit_count as f64,
            },
            qubit_scaling: ScalingFunction::Linear { coefficient: 1.0 },
            time_scaling: ScalingFunction::Polynomial {
                coefficient: 1.0,
                exponent: 2.0,
            },
        })
    }

    /// Estimate memory requirements
    fn estimate_memory_requirements<const N: usize>(
        &self,
        circuit: &Circuit<N>,
        metrics: &CircuitMetrics,
    ) -> QuantRS2Result<MemoryRequirements> {
        // State vector memory: 2^N complex numbers, each 16 bytes
        let state_vector_memory = (1u64 << N) * 16;

        // Gate matrix memory: approximate based on gate count
        let gate_matrix_memory = (metrics.total_gates as u64) * 64; // 4x4 complex matrices

        // Auxiliary memory for computation (buffers, temporaries)
        let auxiliary_memory = state_vector_memory / 4;

        let total_classical_memory = state_vector_memory + gate_matrix_memory + auxiliary_memory;

        let memory_scaling = ScalingFunction::Exponential {
            base: 2.0,
            coefficient: 16.0,
        };

        let memory_optimizations = vec![
            "Use sparse state representations for low-entanglement circuits".to_string(),
            "Implement tensor network simulation for large qubit counts".to_string(),
            "Use GPU memory for state vector storage".to_string(),
        ];

        Ok(MemoryRequirements {
            state_vector_memory,
            gate_matrix_memory,
            auxiliary_memory,
            total_classical_memory,
            quantum_memory: N,
            memory_scaling,
            memory_optimizations,
        })
    }

    /// Estimate execution time
    fn estimate_execution_time<const N: usize>(
        &self,
        circuit: &Circuit<N>,
        metrics: &CircuitMetrics,
    ) -> QuantRS2Result<ExecutionTimeEstimate> {
        let mut total_time = Duration::from_nanos(0);
        let mut gate_time_breakdown = HashMap::new();

        // Calculate time for each gate type
        for (gate_name, count) in &metrics.gate_counts {
            let gate_time = if let Some(gate_cost) = self.gate_cost_database.get(gate_name) {
                gate_cost.execution_time
            } else {
                Duration::from_nanos(100) // Default gate time
            };

            let total_gate_time = gate_time * (*count as u32);
            gate_time_breakdown.insert(gate_name.clone(), total_gate_time);
            total_time += total_gate_time;
        }

        // Critical path time (simplified - would use proper scheduling analysis)
        let critical_path_time = total_time / 2; // Rough estimate

        // Parallelization factor
        let parallelization_factor = if metrics.circuit_depth > 0 {
            (metrics.total_gates as f64) / (metrics.circuit_depth as f64)
        } else {
            1.0
        };

        // Hardware timing factors
        let hardware_timing_factors = [
            ("decoherence_overhead".to_string(), 1.1),
            ("measurement_overhead".to_string(), 1.05),
            ("classical_processing".to_string(), 1.2),
        ]
        .iter()
        .cloned()
        .collect();

        // Confidence interval (±20%)
        let lower_bound = total_time * 80 / 100;
        let upper_bound = total_time * 120 / 100;

        let timing_model = TimingModel::GateCounting {
            gates_per_second: 1e6,
        };

        Ok(ExecutionTimeEstimate {
            estimated_time: total_time,
            gate_time_breakdown,
            critical_path_time,
            parallelization_factor,
            hardware_timing_factors,
            confidence_interval: (lower_bound, upper_bound),
            timing_model,
        })
    }

    /// Analyze hardware requirements
    fn analyze_hardware_requirements<const N: usize>(
        &self,
        circuit: &Circuit<N>,
        metrics: &CircuitMetrics,
    ) -> QuantRS2Result<HardwareRequirements> {
        // Minimum physical qubits (with error correction overhead)
        let min_physical_qubits = N * 50; // Rough estimate for logical qubits

        // Connectivity requirements based on circuit structure
        let connectivity_requirements = if metrics.two_qubit_gates > N {
            ConnectivityRequirement::AllToAll
        } else {
            ConnectivityRequirement::Linear
        };

        // Fidelity requirements
        let fidelity_requirements = [
            ("single_qubit".to_string(), 0.999),
            ("two_qubit".to_string(), 0.99),
            ("measurement".to_string(), 0.98),
        ]
        .iter()
        .cloned()
        .collect();

        // Coherence requirements
        let coherence_requirements = CoherenceRequirement {
            min_t1: Duration::from_micros((metrics.circuit_depth as u64) * 10),
            min_t2: Duration::from_micros((metrics.circuit_depth as u64) * 5),
            gate_to_coherence_ratio: 0.01,
        };

        // Platform recommendations
        let platform_recommendations = self.recommend_platforms(metrics)?;

        // Error correction overhead
        let error_correction_overhead = ErrorCorrectionOverhead {
            physical_to_logical_ratio: 50.0,
            gate_overhead_factor: 10.0,
            time_overhead_factor: 100.0,
            recommended_code: "Surface Code".to_string(),
            threshold_error_rate: 0.001,
        };

        Ok(HardwareRequirements {
            min_physical_qubits,
            connectivity_requirements,
            fidelity_requirements,
            coherence_requirements,
            platform_recommendations,
            error_correction_overhead,
        })
    }

    /// Recommend suitable hardware platforms
    fn recommend_platforms(
        &self,
        metrics: &CircuitMetrics,
    ) -> QuantRS2Result<Vec<PlatformRecommendation>> {
        let mut recommendations = Vec::new();

        for platform_name in &self.config.target_platforms {
            if let Some(platform) = self.platform_database.get(platform_name) {
                let suitability_score = self.calculate_platform_suitability(platform, metrics);

                recommendations.push(PlatformRecommendation {
                    platform: platform_name.clone(),
                    suitability_score,
                    reasoning: self.generate_platform_reasoning(
                        platform,
                        metrics,
                        suitability_score,
                    ),
                    success_probability: suitability_score * 0.8,
                    required_modifications: self.suggest_platform_modifications(platform, metrics),
                });
            }
        }

        recommendations.sort_by(|a, b| {
            b.suitability_score
                .partial_cmp(&a.suitability_score)
                .unwrap_or(std::cmp::Ordering::Equal)
        });
        Ok(recommendations)
    }

    /// Calculate platform suitability score
    fn calculate_platform_suitability(
        &self,
        platform: &PlatformCharacteristics,
        metrics: &CircuitMetrics,
    ) -> f64 {
        let mut score = 1.0;

        // Qubit count factor
        if platform.qubit_count < metrics.qubit_count {
            score *= 0.1; // Severely penalize insufficient qubits
        }

        // Gate fidelity factor
        let avg_fidelity: f64 =
            platform.gate_fidelities.values().sum::<f64>() / platform.gate_fidelities.len() as f64;
        score *= avg_fidelity;

        // Two-qubit gate factor
        if metrics.two_qubit_gates > metrics.qubit_count * 2 {
            score *= 0.8; // Penalize for high two-qubit gate requirements
        }

        score.clamp(0.0, 1.0)
    }

    /// Generate reasoning for platform recommendation
    fn generate_platform_reasoning(
        &self,
        platform: &PlatformCharacteristics,
        metrics: &CircuitMetrics,
        score: f64,
    ) -> String {
        if score > 0.8 {
            format!(
                "Excellent match: {} has sufficient qubits ({}) and high fidelity gates",
                platform.name, platform.qubit_count
            )
        } else if score > 0.6 {
            format!(
                "Good match: {} meets most requirements but may need optimization",
                platform.name
            )
        } else if score > 0.4 {
            format!(
                "Marginal match: {} has limitations for this circuit",
                platform.name
            )
        } else {
            format!(
                "Poor match: {} is not well-suited for this circuit",
                platform.name
            )
        }
    }

    /// Suggest platform modifications
    fn suggest_platform_modifications(
        &self,
        platform: &PlatformCharacteristics,
        metrics: &CircuitMetrics,
    ) -> Vec<String> {
        let mut modifications = Vec::new();

        if platform.qubit_count < metrics.qubit_count {
            modifications.push("Increase qubit count or decompose circuit".to_string());
        }

        if metrics.two_qubit_gates > platform.qubit_count {
            modifications.push("Optimize circuit connectivity".to_string());
        }

        modifications
    }

    /// Get `SciRS2` graph metrics
    fn get_graph_metrics<const N: usize>(
        &mut self,
        circuit: &Circuit<N>,
    ) -> QuantRS2Result<Option<GraphMetrics>> {
        if let Some(analyzer) = &mut self.scirs2_analyzer {
            let analysis = analyzer.analyze_circuit(circuit)?;
            Ok(Some(analysis.metrics))
        } else {
            Ok(None)
        }
    }

    /// Analyze scalability
    fn analyze_scalability<const N: usize>(
        &self,
        circuit: &Circuit<N>,
        metrics: &CircuitMetrics,
        complexity: &ComplexityAnalysis,
    ) -> QuantRS2Result<ScalabilityAnalysis> {
        let scalability_score = self.calculate_scalability_score(metrics, complexity);
        let bottlenecks = self.identify_bottlenecks(metrics, complexity);
        let scaling_predictions = self.predict_scaling(metrics)?;
        let resource_limits = self.calculate_resource_limits(metrics);

        Ok(ScalabilityAnalysis {
            scalability_score,
            bottlenecks,
            scaling_predictions,
            resource_limits,
        })
    }

    /// Calculate overall scalability score
    fn calculate_scalability_score(
        &self,
        metrics: &CircuitMetrics,
        complexity: &ComplexityAnalysis,
    ) -> f64 {
        let mut score: f64 = 1.0;

        // Penalize exponential classical simulation complexity
        if complexity.classical_simulation_complexity > 1e12 {
            score *= 0.5;
        }

        // Penalize high gate complexity
        if complexity.gate_complexity > 1e6 {
            score *= 0.7;
        }

        // Reward quantum advantage
        if complexity.quantum_advantage_factor.is_some() {
            score *= 1.2;
        }

        score.clamp(0.0, 1.0)
    }

    /// Identify scalability bottlenecks
    fn identify_bottlenecks(
        &self,
        metrics: &CircuitMetrics,
        complexity: &ComplexityAnalysis,
    ) -> Vec<ScalabilityBottleneck> {
        let mut bottlenecks = Vec::new();

        // Memory bottleneck
        if complexity.classical_simulation_complexity > 1e15 {
            bottlenecks.push(ScalabilityBottleneck {
                bottleneck_type: BottleneckType::Memory,
                severity: 0.9,
                description: "Exponential memory growth limits classical simulation".to_string(),
                mitigation_suggestions: vec![
                    "Use tensor network simulation".to_string(),
                    "Implement approximate methods".to_string(),
                ],
            });
        }

        // Coherence bottleneck
        if metrics.circuit_depth > 100 {
            bottlenecks.push(ScalabilityBottleneck {
                bottleneck_type: BottleneckType::QuantumCoherence,
                severity: 0.7,
                description: "Deep circuits may exceed coherence times".to_string(),
                mitigation_suggestions: vec![
                    "Reduce circuit depth".to_string(),
                    "Use error correction".to_string(),
                ],
            });
        }

        bottlenecks
    }

    /// Predict scaling for different problem sizes
    fn predict_scaling(
        &self,
        metrics: &CircuitMetrics,
    ) -> QuantRS2Result<HashMap<String, ScalingPrediction>> {
        let mut predictions = HashMap::new();

        // Gate count scaling
        let problem_sizes = vec![10, 20, 30, 40, 50];
        let gate_predictions: Vec<f64> = problem_sizes
            .iter()
            .map(|&size| {
                (size as f64) * (metrics.total_gates as f64) / (metrics.qubit_count as f64)
            })
            .collect();
        let gate_confidence: Vec<(f64, f64)> = gate_predictions
            .iter()
            .map(|&pred| (pred * 0.8, pred * 1.2))
            .collect();

        predictions.insert(
            "gates".to_string(),
            ScalingPrediction {
                problem_sizes,
                predicted_values: gate_predictions,
                confidence_intervals: gate_confidence,
                model: "Linear scaling".to_string(),
            },
        );

        Ok(predictions)
    }

    /// Calculate resource limits
    fn calculate_resource_limits(&self, metrics: &CircuitMetrics) -> ResourceLimits {
        ResourceLimits {
            max_current_technology: 50,   // Current NISQ limit
            max_near_term: 1000,          // Near-term with error correction
            max_theoretical: Some(10000), // Theoretical limit
            limiting_factors: vec![
                "Quantum error rates".to_string(),
                "Coherence times".to_string(),
                "Classical simulation complexity".to_string(),
            ],
        }
    }

    /// Generate optimization suggestions
    fn generate_optimization_suggestions<const N: usize>(
        &self,
        circuit: &Circuit<N>,
        metrics: &CircuitMetrics,
        complexity: &ComplexityAnalysis,
        memory: &MemoryRequirements,
    ) -> QuantRS2Result<Vec<OptimizationSuggestion>> {
        let mut suggestions = Vec::new();

        // Gate count reduction
        if metrics.total_gates > 100 {
            suggestions.push(OptimizationSuggestion {
                suggestion_type: OptimizationType::GateCountReduction,
                expected_improvement: 0.2,
                implementation_complexity: ComplexityLevel::Medium,
                description: "Apply gate fusion and redundancy elimination".to_string(),
                impact_areas: vec!["circuit_depth".to_string(), "execution_time".to_string()],
            });
        }

        // Memory optimization
        if memory.total_classical_memory > 1e9 as u64 {
            suggestions.push(OptimizationSuggestion {
                suggestion_type: OptimizationType::MemoryOptimization,
                expected_improvement: 0.5,
                implementation_complexity: ComplexityLevel::High,
                description: "Use tensor network or sparse representations".to_string(),
                impact_areas: vec![
                    "memory_usage".to_string(),
                    "simulation_feasibility".to_string(),
                ],
            });
        }

        // Parallelization
        if metrics.circuit_depth < metrics.total_gates / 2 {
            suggestions.push(OptimizationSuggestion {
                suggestion_type: OptimizationType::Parallelization,
                expected_improvement: 0.3,
                implementation_complexity: ComplexityLevel::Low,
                description: "Increase gate-level parallelism".to_string(),
                impact_areas: vec!["execution_time".to_string()],
            });
        }

        Ok(suggestions)
    }

    /// Default hardware requirements for simplified analysis
    fn default_hardware_requirements(&self) -> HardwareRequirements {
        HardwareRequirements {
            min_physical_qubits: 0,
            connectivity_requirements: ConnectivityRequirement::Linear,
            fidelity_requirements: HashMap::new(),
            coherence_requirements: CoherenceRequirement {
                min_t1: Duration::from_micros(100),
                min_t2: Duration::from_micros(50),
                gate_to_coherence_ratio: 0.01,
            },
            platform_recommendations: Vec::new(),
            error_correction_overhead: ErrorCorrectionOverhead {
                physical_to_logical_ratio: 1.0,
                gate_overhead_factor: 1.0,
                time_overhead_factor: 1.0,
                recommended_code: "None".to_string(),
                threshold_error_rate: 1.0,
            },
        }
    }

    /// Default scalability analysis for simplified analysis
    fn default_scalability_analysis(&self) -> ScalabilityAnalysis {
        ScalabilityAnalysis {
            scalability_score: 0.5,
            bottlenecks: Vec::new(),
            scaling_predictions: HashMap::new(),
            resource_limits: ResourceLimits {
                max_current_technology: 50,
                max_near_term: 100,
                max_theoretical: None,
                limiting_factors: Vec::new(),
            },
        }
    }
}

/// Quick resource estimation with default options
pub fn estimate_circuit_resources<const N: usize>(
    circuit: &Circuit<N>,
) -> QuantRS2Result<ResourceEstimate> {
    let mut estimator = ResourceEstimator::new(ResourceEstimatorConfig::default());
    estimator.estimate_resources(circuit)
}

/// Resource estimation with custom configuration
pub fn estimate_circuit_resources_with_config<const N: usize>(
    circuit: &Circuit<N>,
    config: ResourceEstimatorConfig,
) -> QuantRS2Result<ResourceEstimate> {
    let mut estimator = ResourceEstimator::new(config);
    estimator.estimate_resources(circuit)
}

#[cfg(test)]
mod tests {
    use super::*;
    use quantrs2_core::gate::multi::CNOT;
    use quantrs2_core::gate::single::Hadamard;

    #[test]
    fn test_basic_resource_estimation() {
        let mut circuit = Circuit::<3>::new();
        circuit
            .add_gate(Hadamard { target: QubitId(0) })
            .expect("Failed to add Hadamard gate to qubit 0");
        circuit
            .add_gate(CNOT {
                control: QubitId(0),
                target: QubitId(1),
            })
            .expect("Failed to add CNOT gate");
        circuit
            .add_gate(Hadamard { target: QubitId(2) })
            .expect("Failed to add Hadamard gate to qubit 2");

        let estimate =
            estimate_circuit_resources(&circuit).expect("Failed to estimate circuit resources");

        assert_eq!(estimate.circuit_metrics.total_gates, 3);
        assert_eq!(estimate.circuit_metrics.qubit_count, 3);
        assert!(estimate.circuit_metrics.single_qubit_gates > 0);
        assert!(estimate.circuit_metrics.two_qubit_gates > 0);
    }

    #[test]
    fn test_complexity_analysis() {
        let mut circuit = Circuit::<2>::new();
        circuit
            .add_gate(Hadamard { target: QubitId(0) })
            .expect("Failed to add Hadamard gate");
        circuit
            .add_gate(CNOT {
                control: QubitId(0),
                target: QubitId(1),
            })
            .expect("Failed to add CNOT gate");

        let estimate =
            estimate_circuit_resources(&circuit).expect("Failed to estimate circuit resources");

        // Should classify as constant time complexity for small circuits
        match estimate.complexity_analysis.time_complexity {
            ComplexityClass::Constant | ComplexityClass::Linear => {}
            _ => panic!("Unexpected time complexity for small circuit"),
        }

        // Space complexity should be exponential for classical simulation
        match estimate.complexity_analysis.space_complexity {
            ComplexityClass::Exponential => {}
            _ => panic!("Expected exponential space complexity"),
        }
    }

    #[test]
    fn test_memory_estimation() {
        let mut circuit = Circuit::<4>::new();
        for i in 0..4 {
            circuit
                .add_gate(Hadamard { target: QubitId(i) })
                .expect("Failed to add Hadamard gate");
        }

        let estimate =
            estimate_circuit_resources(&circuit).expect("Failed to estimate circuit resources");

        // 4 qubits should require 2^4 * 16 = 256 bytes for state vector
        assert_eq!(estimate.memory_requirements.state_vector_memory, 256);
        assert!(estimate.memory_requirements.total_classical_memory > 256);
    }

    #[test]
    fn test_execution_time_estimation() {
        let mut circuit = Circuit::<2>::new();
        circuit
            .add_gate(Hadamard { target: QubitId(0) })
            .expect("Failed to add Hadamard gate");
        circuit
            .add_gate(CNOT {
                control: QubitId(0),
                target: QubitId(1),
            })
            .expect("Failed to add CNOT gate");

        let estimate =
            estimate_circuit_resources(&circuit).expect("Failed to estimate circuit resources");

        assert!(estimate.execution_time.estimated_time > Duration::from_nanos(0));
        assert!(!estimate.execution_time.gate_time_breakdown.is_empty());
        assert!(estimate.execution_time.parallelization_factor > 0.0);
    }

    #[test]
    fn test_hardware_requirements() {
        let mut circuit = Circuit::<10>::new();
        for i in 0..9 {
            circuit
                .add_gate(CNOT {
                    control: QubitId(i),
                    target: QubitId(i + 1),
                })
                .expect("Failed to add CNOT gate");
        }

        let estimate =
            estimate_circuit_resources(&circuit).expect("Failed to estimate circuit resources");

        assert!(estimate.hardware_requirements.min_physical_qubits >= 10);
        assert!(!estimate
            .hardware_requirements
            .platform_recommendations
            .is_empty());
    }

    #[test]
    fn test_optimization_suggestions() {
        let mut circuit = Circuit::<5>::new();
        // Create a circuit with just enough gates to trigger optimization suggestions (>100)
        // Use 105 gates instead of 200 to avoid slow graph analysis with O(n^2) complexity
        for _ in 0..105 {
            circuit
                .add_gate(Hadamard { target: QubitId(0) })
                .expect("Failed to add Hadamard gate");
        }

        // Use lightweight config without expensive graph analysis
        let config = ResourceEstimatorConfig {
            enable_graph_analysis: false, // Skip O(n^2) graph analysis
            enable_hardware_analysis: false,
            enable_scalability_analysis: false,
            include_optimizations: true, // This is what we're testing
            ..Default::default()
        };

        let estimate = estimate_circuit_resources_with_config(&circuit, config)
            .expect("Failed to estimate circuit resources");

        assert!(!estimate.optimization_suggestions.is_empty());

        let has_gate_reduction = estimate
            .optimization_suggestions
            .iter()
            .any(|s| matches!(s.suggestion_type, OptimizationType::GateCountReduction));
        assert!(has_gate_reduction);
    }

    #[test]
    fn test_custom_configuration() {
        let config = ResourceEstimatorConfig {
            analysis_depth: AnalysisDepth::Comprehensive,
            enable_scalability_analysis: true,
            ..Default::default()
        };

        let mut circuit = Circuit::<3>::new();
        circuit
            .add_gate(Hadamard { target: QubitId(0) })
            .expect("Failed to add Hadamard gate");

        let estimate = estimate_circuit_resources_with_config(&circuit, config)
            .expect("Failed to estimate circuit resources with config");

        assert!(estimate.scalability_analysis.scalability_score >= 0.0);
        assert!(estimate.scalability_analysis.scalability_score <= 1.0);
    }

    #[test]
    fn test_algorithm_classification() {
        // Test QFT-like circuit (many H gates)
        let mut qft_circuit = Circuit::<4>::new();
        for i in 0..4 {
            qft_circuit
                .add_gate(Hadamard { target: QubitId(i) })
                .expect("Failed to add Hadamard gate");
        }

        let estimate =
            estimate_circuit_resources(&qft_circuit).expect("Failed to estimate circuit resources");
        match estimate.complexity_analysis.algorithm_classification {
            AlgorithmClass::QftBased | AlgorithmClass::General => {}
            _ => panic!("Unexpected algorithm classification"),
        }
    }
}