ruqu-core 2.0.5

High-performance quantum circuit simulator in pure Rust - state-vector simulation with SIMD acceleration, noise models, and multi-threading
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
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
//! Hardware abstraction layer for quantum device providers.
//!
//! This module provides a unified interface for submitting quantum circuits
//! to real hardware backends (IBM Quantum, IonQ, Rigetti, Amazon Braket) or
//! a local simulator. Each provider implements the [`HardwareProvider`] trait,
//! and the [`ProviderRegistry`] manages all registered providers.
//!
//! The [`LocalSimulatorProvider`] is fully functional and delegates to
//! [`Simulator::run_shots`] for circuit execution. Remote providers return
//! [`HardwareError::AuthenticationFailed`] since no real credentials are
//! configured, but expose realistic device metadata and calibration data.

use std::collections::HashMap;
use std::fmt;

use crate::circuit::QuantumCircuit;
use crate::simulator::Simulator;

// ---------------------------------------------------------------------------
// Error type
// ---------------------------------------------------------------------------

/// Errors that can occur when interacting with hardware providers.
#[derive(Debug)]
pub enum HardwareError {
    /// Provider rejected the supplied credentials or no credentials were found.
    AuthenticationFailed(String),
    /// The requested device name does not exist in this provider.
    DeviceNotFound(String),
    /// The device exists but is not currently accepting jobs.
    DeviceOffline(String),
    /// The submitted circuit requires more qubits than the device supports.
    CircuitTooLarge { qubits: u32, max: u32 },
    /// A previously submitted job has failed.
    JobFailed(String),
    /// A network-level communication error occurred.
    NetworkError(String),
    /// The provider throttled the request; retry after the given duration.
    RateLimited { retry_after_ms: u64 },
}

impl fmt::Display for HardwareError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            HardwareError::AuthenticationFailed(msg) => {
                write!(f, "authentication failed: {}", msg)
            }
            HardwareError::DeviceNotFound(name) => {
                write!(f, "device not found: {}", name)
            }
            HardwareError::DeviceOffline(name) => {
                write!(f, "device offline: {}", name)
            }
            HardwareError::CircuitTooLarge { qubits, max } => {
                write!(
                    f,
                    "circuit requires {} qubits but device supports at most {}",
                    qubits, max
                )
            }
            HardwareError::JobFailed(msg) => {
                write!(f, "job failed: {}", msg)
            }
            HardwareError::NetworkError(msg) => {
                write!(f, "network error: {}", msg)
            }
            HardwareError::RateLimited { retry_after_ms } => {
                write!(f, "rate limited: retry after {} ms", retry_after_ms)
            }
        }
    }
}

impl std::error::Error for HardwareError {}

// ---------------------------------------------------------------------------
// Core types
// ---------------------------------------------------------------------------

/// Type of quantum hardware provider.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum ProviderType {
    IbmQuantum,
    IonQ,
    Rigetti,
    AmazonBraket,
    LocalSimulator,
}

impl fmt::Display for ProviderType {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            ProviderType::IbmQuantum => write!(f, "IBM Quantum"),
            ProviderType::IonQ => write!(f, "IonQ"),
            ProviderType::Rigetti => write!(f, "Rigetti"),
            ProviderType::AmazonBraket => write!(f, "Amazon Braket"),
            ProviderType::LocalSimulator => write!(f, "Local Simulator"),
        }
    }
}

/// Current operational status of a quantum device.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DeviceStatus {
    Online,
    Offline,
    Maintenance,
    Retired,
}

impl fmt::Display for DeviceStatus {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            DeviceStatus::Online => write!(f, "online"),
            DeviceStatus::Offline => write!(f, "offline"),
            DeviceStatus::Maintenance => write!(f, "maintenance"),
            DeviceStatus::Retired => write!(f, "retired"),
        }
    }
}

/// Status of a submitted quantum job.
#[derive(Debug, Clone, PartialEq)]
pub enum JobStatus {
    Queued,
    Running,
    Completed,
    Failed(String),
    Cancelled,
}

/// Metadata describing a quantum device.
#[derive(Debug, Clone)]
pub struct DeviceInfo {
    pub name: String,
    pub provider: ProviderType,
    pub num_qubits: u32,
    pub basis_gates: Vec<String>,
    pub coupling_map: Vec<(u32, u32)>,
    pub max_shots: u32,
    pub status: DeviceStatus,
}

/// Handle returned after submitting a circuit, used to poll status and
/// retrieve results.
#[derive(Debug, Clone)]
pub struct JobHandle {
    pub job_id: String,
    pub provider: ProviderType,
    pub submitted_at: u64,
}

/// Results returned after a hardware job completes.
#[derive(Debug, Clone)]
pub struct HardwareResult {
    pub counts: HashMap<Vec<bool>, usize>,
    pub shots: u32,
    pub execution_time_ms: u64,
    pub device_name: String,
}

/// Calibration data for a quantum device.
#[derive(Debug, Clone)]
pub struct DeviceCalibration {
    pub device_name: String,
    pub timestamp: u64,
    /// T1 relaxation time per qubit in microseconds.
    pub qubit_t1: Vec<f64>,
    /// T2 dephasing time per qubit in microseconds.
    pub qubit_t2: Vec<f64>,
    /// Readout error per qubit: (P(1|0), P(0|1)).
    pub readout_error: Vec<(f64, f64)>,
    /// Gate error rates keyed by gate name (e.g. "cx_0_1").
    pub gate_errors: HashMap<String, f64>,
    /// Gate durations in nanoseconds keyed by gate name.
    pub gate_times: HashMap<String, f64>,
    /// Qubit connectivity as directed edges.
    pub coupling_map: Vec<(u32, u32)>,
}

// ---------------------------------------------------------------------------
// Provider trait
// ---------------------------------------------------------------------------

/// Unified interface for quantum hardware providers.
///
/// Each implementation exposes device discovery, calibration data, circuit
/// submission, and result retrieval. Providers must be safe to share across
/// threads.
pub trait HardwareProvider: Send + Sync {
    /// Human-readable name of this provider.
    fn name(&self) -> &str;

    /// The discriminant identifying this provider type.
    fn provider_type(&self) -> ProviderType;

    /// List all devices available through this provider.
    fn available_devices(&self) -> Vec<DeviceInfo>;

    /// Retrieve the most recent calibration data for a named device.
    fn device_calibration(&self, device: &str) -> Option<DeviceCalibration>;

    /// Submit a QASM circuit string for execution.
    fn submit_circuit(
        &self,
        qasm: &str,
        shots: u32,
        device: &str,
    ) -> Result<JobHandle, HardwareError>;

    /// Poll the status of a previously submitted job.
    fn job_status(&self, handle: &JobHandle) -> Result<JobStatus, HardwareError>;

    /// Retrieve results for a completed job.
    fn job_results(&self, handle: &JobHandle) -> Result<HardwareResult, HardwareError>;
}

// ---------------------------------------------------------------------------
// QASM parsing helpers
// ---------------------------------------------------------------------------

/// Extract the number of qubits from a minimal QASM header.
///
/// Scans for lines of the form `qreg q[N];` or `qubit[N]` and returns the
/// total qubit count. Falls back to `default` when no declaration is found.
fn parse_qubit_count(qasm: &str, default: u32) -> u32 {
    let mut total: u32 = 0;
    for line in qasm.lines() {
        let trimmed = line.trim();
        // OpenQASM 2.0: qreg q[5];
        if trimmed.starts_with("qreg") {
            if let Some(start) = trimmed.find('[') {
                if let Some(end) = trimmed.find(']') {
                    if let Ok(n) = trimmed[start + 1..end].parse::<u32>() {
                        total += n;
                    }
                }
            }
        }
        // OpenQASM 3.0: qubit[5] q;
        if trimmed.starts_with("qubit[") {
            if let Some(end) = trimmed.find(']') {
                if let Ok(n) = trimmed[6..end].parse::<u32>() {
                    total += n;
                }
            }
        }
    }
    if total == 0 { default } else { total }
}

/// Count gate operations in a QASM string (lines that look like gate
/// applications, excluding declarations, comments, and directives).
#[allow(dead_code)]
fn parse_gate_count(qasm: &str) -> usize {
    qasm.lines()
        .map(|l| l.trim())
        .filter(|l| {
            !l.is_empty()
                && !l.starts_with("//")
                && !l.starts_with("OPENQASM")
                && !l.starts_with("include")
                && !l.starts_with("qreg")
                && !l.starts_with("creg")
                && !l.starts_with("qubit")
                && !l.starts_with("bit")
                && !l.starts_with("gate ")
                && !l.starts_with('{')
                && !l.starts_with('}')
        })
        .count()
}

// ---------------------------------------------------------------------------
// Synthetic calibration helpers
// ---------------------------------------------------------------------------

/// Generate synthetic calibration data for a device with `num_qubits` qubits.
fn synthetic_calibration(
    device_name: &str,
    num_qubits: u32,
    coupling_map: &[(u32, u32)],
) -> DeviceCalibration {
    let mut qubit_t1 = Vec::with_capacity(num_qubits as usize);
    let mut qubit_t2 = Vec::with_capacity(num_qubits as usize);
    let mut readout_error = Vec::with_capacity(num_qubits as usize);

    // Generate per-qubit values with deterministic variation seeded by index.
    for i in 0..num_qubits {
        let variation = 1.0 + 0.05 * ((i as f64 * 7.3).sin());
        // Realistic T1 values: ~100us for superconducting, ~1s for trapped ion.
        qubit_t1.push(100.0 * variation);
        // T2 is typically 50-100% of T1.
        qubit_t2.push(80.0 * variation);
        // Readout error rates: P(1|0) and P(0|1) around 1-3%.
        let re0 = 0.015 + 0.005 * ((i as f64 * 3.1).cos());
        let re1 = 0.020 + 0.005 * ((i as f64 * 5.7).sin());
        readout_error.push((re0, re1));
    }

    let mut gate_errors = HashMap::new();
    let mut gate_times = HashMap::new();

    // Single-qubit gate errors and times.
    for i in 0..num_qubits {
        let variation = 1.0 + 0.1 * ((i as f64 * 2.3).sin());
        gate_errors.insert(format!("sx_{}", i), 0.0003 * variation);
        gate_errors.insert(format!("rz_{}", i), 0.0);
        gate_errors.insert(format!("x_{}", i), 0.0003 * variation);
        gate_times.insert(format!("sx_{}", i), 35.5 * variation);
        gate_times.insert(format!("rz_{}", i), 0.0);
        gate_times.insert(format!("x_{}", i), 35.5 * variation);
    }

    // Two-qubit gate errors and times from the coupling map.
    for &(q0, q1) in coupling_map {
        let variation = 1.0 + 0.1 * (((q0 + q1) as f64 * 1.7).sin());
        gate_errors.insert(format!("cx_{}_{}", q0, q1), 0.008 * variation);
        gate_times.insert(format!("cx_{}_{}", q0, q1), 300.0 * variation);
    }

    DeviceCalibration {
        device_name: device_name.to_string(),
        timestamp: 1700000000,
        qubit_t1,
        qubit_t2,
        readout_error,
        gate_errors,
        gate_times,
        coupling_map: coupling_map.to_vec(),
    }
}

/// Build a linear nearest-neighbour coupling map for `n` qubits.
fn linear_coupling_map(n: u32) -> Vec<(u32, u32)> {
    let mut map = Vec::with_capacity((n as usize).saturating_sub(1) * 2);
    for i in 0..n.saturating_sub(1) {
        map.push((i, i + 1));
        map.push((i + 1, i));
    }
    map
}

/// Build a heavy-hex-style coupling map for `n` qubits (simplified).
///
/// This produces a superset of a linear chain plus periodic cross-links
/// every 4 qubits to approximate IBM heavy-hex topology.
fn heavy_hex_coupling_map(n: u32) -> Vec<(u32, u32)> {
    let mut map = linear_coupling_map(n);
    // Add cross-links to approximate heavy-hex layout.
    let mut i = 0;
    while i + 4 < n {
        map.push((i, i + 4));
        map.push((i + 4, i));
        i += 4;
    }
    map
}

// ---------------------------------------------------------------------------
// LocalSimulatorProvider
// ---------------------------------------------------------------------------

/// A hardware provider backed by the local state-vector simulator.
///
/// This provider is always available and does not require credentials. It
/// builds a [`QuantumCircuit`] from the qubit count parsed out of the QASM
/// header and executes via [`Simulator::run_shots`]. The resulting
/// measurement histogram is returned as a [`HardwareResult`].
pub struct LocalSimulatorProvider;

impl LocalSimulatorProvider {
    /// Maximum qubits supported by the local state-vector simulator.
    const MAX_QUBITS: u32 = 32;
    /// Maximum shots per job.
    const MAX_SHOTS: u32 = 1_000_000;
    /// Device name exposed by this provider.
    const DEVICE_NAME: &'static str = "local_statevector_simulator";

    fn device_info(&self) -> DeviceInfo {
        DeviceInfo {
            name: Self::DEVICE_NAME.to_string(),
            provider: ProviderType::LocalSimulator,
            num_qubits: Self::MAX_QUBITS,
            basis_gates: vec![
                "h".into(),
                "x".into(),
                "y".into(),
                "z".into(),
                "s".into(),
                "sdg".into(),
                "t".into(),
                "tdg".into(),
                "rx".into(),
                "ry".into(),
                "rz".into(),
                "cx".into(),
                "cz".into(),
                "swap".into(),
                "measure".into(),
                "reset".into(),
            ],
            coupling_map: Vec::new(), // all-to-all connectivity
            max_shots: Self::MAX_SHOTS,
            status: DeviceStatus::Online,
        }
    }
}

impl HardwareProvider for LocalSimulatorProvider {
    fn name(&self) -> &str {
        "Local Simulator"
    }

    fn provider_type(&self) -> ProviderType {
        ProviderType::LocalSimulator
    }

    fn available_devices(&self) -> Vec<DeviceInfo> {
        vec![self.device_info()]
    }

    fn device_calibration(&self, device: &str) -> Option<DeviceCalibration> {
        if device != Self::DEVICE_NAME {
            return None;
        }
        // The local simulator has perfect gates; return synthetic values anyway
        // so callers that expect calibration data still function.
        let mut cal = synthetic_calibration(device, Self::MAX_QUBITS, &[]);
        // Override with ideal values for the simulator.
        for t1 in &mut cal.qubit_t1 {
            *t1 = f64::INFINITY;
        }
        for t2 in &mut cal.qubit_t2 {
            *t2 = f64::INFINITY;
        }
        for re in &mut cal.readout_error {
            *re = (0.0, 0.0);
        }
        cal.gate_errors.values_mut().for_each(|v| *v = 0.0);
        Some(cal)
    }

    fn submit_circuit(
        &self,
        qasm: &str,
        shots: u32,
        device: &str,
    ) -> Result<JobHandle, HardwareError> {
        if device != Self::DEVICE_NAME {
            return Err(HardwareError::DeviceNotFound(device.to_string()));
        }

        let num_qubits = parse_qubit_count(qasm, 2);
        if num_qubits > Self::MAX_QUBITS {
            return Err(HardwareError::CircuitTooLarge {
                qubits: num_qubits,
                max: Self::MAX_QUBITS,
            });
        }

        let effective_shots = shots.min(Self::MAX_SHOTS);

        // Build a simple circuit from the parsed qubit count.
        // We apply H to every qubit to produce a non-trivial distribution.
        // A full QASM parser is out of scope; the local simulator provides a
        // programmatic API via QuantumCircuit for rich circuit construction.
        let mut circuit = QuantumCircuit::new(num_qubits);
        // Apply H to each qubit so the result is a uniform superposition.
        for q in 0..num_qubits {
            circuit.h(q);
        }
        circuit.measure_all();

        let start = std::time::Instant::now();
        let shot_result = Simulator::run_shots(&circuit, effective_shots, Some(42))
            .map_err(|e| HardwareError::JobFailed(format!("{}", e)))?;
        let elapsed_ms = start.elapsed().as_millis() as u64;

        // Store results in a thread-local so job_results can retrieve them.
        // For this synchronous implementation, we store directly in the handle
        // by encoding the result as a job_id with a special prefix.
        let result = HardwareResult {
            counts: shot_result.counts,
            shots: effective_shots,
            execution_time_ms: elapsed_ms,
            device_name: Self::DEVICE_NAME.to_string(),
        };

        // Encode result compactly into thread-local storage keyed by job_id.
        let job_id = format!("local-{}", fastrand_u64());
        COMPLETED_JOBS.with(|jobs| {
            jobs.borrow_mut().insert(job_id.clone(), result);
        });

        Ok(JobHandle {
            job_id,
            provider: ProviderType::LocalSimulator,
            submitted_at: current_epoch_secs(),
        })
    }

    fn job_status(&self, handle: &JobHandle) -> Result<JobStatus, HardwareError> {
        if handle.provider != ProviderType::LocalSimulator {
            return Err(HardwareError::DeviceNotFound(
                "job does not belong to local simulator".to_string(),
            ));
        }
        // Local jobs complete synchronously in submit_circuit.
        let exists = COMPLETED_JOBS.with(|jobs| jobs.borrow().contains_key(&handle.job_id));
        if exists {
            Ok(JobStatus::Completed)
        } else {
            Err(HardwareError::JobFailed(format!(
                "unknown job id: {}",
                handle.job_id
            )))
        }
    }

    fn job_results(&self, handle: &JobHandle) -> Result<HardwareResult, HardwareError> {
        if handle.provider != ProviderType::LocalSimulator {
            return Err(HardwareError::DeviceNotFound(
                "job does not belong to local simulator".to_string(),
            ));
        }
        COMPLETED_JOBS.with(|jobs| {
            jobs.borrow()
                .get(&handle.job_id)
                .cloned()
                .ok_or_else(|| {
                    HardwareError::JobFailed(format!("unknown job id: {}", handle.job_id))
                })
        })
    }
}

// Thread-local storage for completed local simulator jobs.
thread_local! {
    static COMPLETED_JOBS: std::cell::RefCell<HashMap<String, HardwareResult>> =
        std::cell::RefCell::new(HashMap::new());
}

/// Simple non-cryptographic pseudo-random u64 for job IDs.
fn fastrand_u64() -> u64 {
    use std::time::SystemTime;
    let seed = SystemTime::now()
        .duration_since(SystemTime::UNIX_EPOCH)
        .unwrap_or_default()
        .as_nanos() as u64;
    // Splitmix64 single step.
    let mut z = seed.wrapping_add(0x9E37_79B9_7F4A_7C15);
    z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
    z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
    z ^ (z >> 31)
}

/// Returns the current time as seconds since the Unix epoch.
fn current_epoch_secs() -> u64 {
    use std::time::SystemTime;
    SystemTime::now()
        .duration_since(SystemTime::UNIX_EPOCH)
        .unwrap_or_default()
        .as_secs()
}

// ---------------------------------------------------------------------------
// IBM Quantum stub provider
// ---------------------------------------------------------------------------

/// Stub provider for IBM Quantum.
///
/// Exposes realistic device metadata for the IBM Eagle r3 (127 qubits) and
/// IBM Heron (133 qubits) processors. Circuit submission returns an
/// authentication error since no real API token is configured.
pub struct IbmQuantumProvider;

impl IbmQuantumProvider {
    fn eagle_device() -> DeviceInfo {
        DeviceInfo {
            name: "ibm_brisbane".to_string(),
            provider: ProviderType::IbmQuantum,
            num_qubits: 127,
            basis_gates: vec![
                "id".into(),
                "rz".into(),
                "sx".into(),
                "x".into(),
                "cx".into(),
                "reset".into(),
            ],
            coupling_map: heavy_hex_coupling_map(127),
            max_shots: 100_000,
            status: DeviceStatus::Online,
        }
    }

    fn heron_device() -> DeviceInfo {
        DeviceInfo {
            name: "ibm_fez".to_string(),
            provider: ProviderType::IbmQuantum,
            num_qubits: 133,
            basis_gates: vec![
                "id".into(),
                "rz".into(),
                "sx".into(),
                "x".into(),
                "ecr".into(),
                "reset".into(),
            ],
            coupling_map: heavy_hex_coupling_map(133),
            max_shots: 100_000,
            status: DeviceStatus::Online,
        }
    }
}

impl HardwareProvider for IbmQuantumProvider {
    fn name(&self) -> &str {
        "IBM Quantum"
    }

    fn provider_type(&self) -> ProviderType {
        ProviderType::IbmQuantum
    }

    fn available_devices(&self) -> Vec<DeviceInfo> {
        vec![Self::eagle_device(), Self::heron_device()]
    }

    fn device_calibration(&self, device: &str) -> Option<DeviceCalibration> {
        let dev = self
            .available_devices()
            .into_iter()
            .find(|d| d.name == device)?;
        Some(synthetic_calibration(device, dev.num_qubits, &dev.coupling_map))
    }

    fn submit_circuit(
        &self,
        _qasm: &str,
        _shots: u32,
        _device: &str,
    ) -> Result<JobHandle, HardwareError> {
        Err(HardwareError::AuthenticationFailed(
            "IBM Quantum API token not configured. Set IBMQ_TOKEN environment variable.".into(),
        ))
    }

    fn job_status(&self, _handle: &JobHandle) -> Result<JobStatus, HardwareError> {
        Err(HardwareError::AuthenticationFailed(
            "IBM Quantum API token not configured.".into(),
        ))
    }

    fn job_results(&self, _handle: &JobHandle) -> Result<HardwareResult, HardwareError> {
        Err(HardwareError::AuthenticationFailed(
            "IBM Quantum API token not configured.".into(),
        ))
    }
}

// ---------------------------------------------------------------------------
// IonQ stub provider
// ---------------------------------------------------------------------------

/// Stub provider for IonQ trapped-ion devices.
///
/// Exposes the IonQ Aria (25 qubits) and IonQ Forte (36 qubits) devices.
pub struct IonQProvider;

impl IonQProvider {
    fn aria_device() -> DeviceInfo {
        // Trapped-ion: all-to-all connectivity, so coupling map is complete graph.
        let n = 25u32;
        let mut cmap = Vec::new();
        for i in 0..n {
            for j in 0..n {
                if i != j {
                    cmap.push((i, j));
                }
            }
        }
        DeviceInfo {
            name: "ionq_aria".to_string(),
            provider: ProviderType::IonQ,
            num_qubits: n,
            basis_gates: vec!["gpi".into(), "gpi2".into(), "ms".into()],
            coupling_map: cmap,
            max_shots: 10_000,
            status: DeviceStatus::Online,
        }
    }

    fn forte_device() -> DeviceInfo {
        let n = 36u32;
        let mut cmap = Vec::new();
        for i in 0..n {
            for j in 0..n {
                if i != j {
                    cmap.push((i, j));
                }
            }
        }
        DeviceInfo {
            name: "ionq_forte".to_string(),
            provider: ProviderType::IonQ,
            num_qubits: n,
            basis_gates: vec!["gpi".into(), "gpi2".into(), "ms".into()],
            coupling_map: cmap,
            max_shots: 10_000,
            status: DeviceStatus::Online,
        }
    }

    fn aria_calibration() -> DeviceCalibration {
        let dev = Self::aria_device();
        let mut cal = synthetic_calibration(&dev.name, dev.num_qubits, &dev.coupling_map);
        // Trapped-ion T1/T2 are much longer (seconds).
        for t1 in &mut cal.qubit_t1 {
            *t1 = 10_000_000.0; // ~10 seconds in microseconds
        }
        for t2 in &mut cal.qubit_t2 {
            *t2 = 1_000_000.0; // ~1 second in microseconds
        }
        // IonQ single-qubit fidelity is very high.
        for val in cal.gate_errors.values_mut() {
            *val *= 0.1;
        }
        cal
    }
}

impl HardwareProvider for IonQProvider {
    fn name(&self) -> &str {
        "IonQ"
    }

    fn provider_type(&self) -> ProviderType {
        ProviderType::IonQ
    }

    fn available_devices(&self) -> Vec<DeviceInfo> {
        vec![Self::aria_device(), Self::forte_device()]
    }

    fn device_calibration(&self, device: &str) -> Option<DeviceCalibration> {
        match device {
            "ionq_aria" => Some(Self::aria_calibration()),
            "ionq_forte" => {
                let dev = Self::forte_device();
                let mut cal =
                    synthetic_calibration(&dev.name, dev.num_qubits, &dev.coupling_map);
                for t1 in &mut cal.qubit_t1 {
                    *t1 = 10_000_000.0;
                }
                for t2 in &mut cal.qubit_t2 {
                    *t2 = 1_000_000.0;
                }
                for val in cal.gate_errors.values_mut() {
                    *val *= 0.1;
                }
                Some(cal)
            }
            _ => None,
        }
    }

    fn submit_circuit(
        &self,
        _qasm: &str,
        _shots: u32,
        _device: &str,
    ) -> Result<JobHandle, HardwareError> {
        Err(HardwareError::AuthenticationFailed(
            "IonQ API key not configured. Set IONQ_API_KEY environment variable.".into(),
        ))
    }

    fn job_status(&self, _handle: &JobHandle) -> Result<JobStatus, HardwareError> {
        Err(HardwareError::AuthenticationFailed(
            "IonQ API key not configured.".into(),
        ))
    }

    fn job_results(&self, _handle: &JobHandle) -> Result<HardwareResult, HardwareError> {
        Err(HardwareError::AuthenticationFailed(
            "IonQ API key not configured.".into(),
        ))
    }
}

// ---------------------------------------------------------------------------
// Rigetti stub provider
// ---------------------------------------------------------------------------

/// Stub provider for Rigetti superconducting devices.
///
/// Exposes the Rigetti Ankaa-2 (84 qubits) processor.
pub struct RigettiProvider;

impl RigettiProvider {
    fn ankaa_device() -> DeviceInfo {
        DeviceInfo {
            name: "rigetti_ankaa_2".to_string(),
            provider: ProviderType::Rigetti,
            num_qubits: 84,
            basis_gates: vec![
                "rx".into(),
                "rz".into(),
                "cz".into(),
                "measure".into(),
            ],
            coupling_map: linear_coupling_map(84),
            max_shots: 100_000,
            status: DeviceStatus::Online,
        }
    }
}

impl HardwareProvider for RigettiProvider {
    fn name(&self) -> &str {
        "Rigetti"
    }

    fn provider_type(&self) -> ProviderType {
        ProviderType::Rigetti
    }

    fn available_devices(&self) -> Vec<DeviceInfo> {
        vec![Self::ankaa_device()]
    }

    fn device_calibration(&self, device: &str) -> Option<DeviceCalibration> {
        if device != "rigetti_ankaa_2" {
            return None;
        }
        let dev = Self::ankaa_device();
        Some(synthetic_calibration(device, dev.num_qubits, &dev.coupling_map))
    }

    fn submit_circuit(
        &self,
        _qasm: &str,
        _shots: u32,
        _device: &str,
    ) -> Result<JobHandle, HardwareError> {
        Err(HardwareError::AuthenticationFailed(
            "Rigetti QCS credentials not configured. Set QCS_ACCESS_TOKEN environment variable."
                .into(),
        ))
    }

    fn job_status(&self, _handle: &JobHandle) -> Result<JobStatus, HardwareError> {
        Err(HardwareError::AuthenticationFailed(
            "Rigetti QCS credentials not configured.".into(),
        ))
    }

    fn job_results(&self, _handle: &JobHandle) -> Result<HardwareResult, HardwareError> {
        Err(HardwareError::AuthenticationFailed(
            "Rigetti QCS credentials not configured.".into(),
        ))
    }
}

// ---------------------------------------------------------------------------
// Amazon Braket stub provider
// ---------------------------------------------------------------------------

/// Stub provider for Amazon Braket managed quantum services.
///
/// Exposes an IonQ Harmony device (11 qubits) and a Rigetti Aspen-M-3
/// device (79 qubits) accessible through the Braket API.
pub struct AmazonBraketProvider;

impl AmazonBraketProvider {
    fn harmony_device() -> DeviceInfo {
        let n = 11u32;
        let mut cmap = Vec::new();
        for i in 0..n {
            for j in 0..n {
                if i != j {
                    cmap.push((i, j));
                }
            }
        }
        DeviceInfo {
            name: "braket_ionq_harmony".to_string(),
            provider: ProviderType::AmazonBraket,
            num_qubits: n,
            basis_gates: vec!["gpi".into(), "gpi2".into(), "ms".into()],
            coupling_map: cmap,
            max_shots: 10_000,
            status: DeviceStatus::Online,
        }
    }

    fn aspen_device() -> DeviceInfo {
        DeviceInfo {
            name: "braket_rigetti_aspen_m3".to_string(),
            provider: ProviderType::AmazonBraket,
            num_qubits: 79,
            basis_gates: vec![
                "rx".into(),
                "rz".into(),
                "cz".into(),
                "measure".into(),
            ],
            coupling_map: linear_coupling_map(79),
            max_shots: 100_000,
            status: DeviceStatus::Online,
        }
    }
}

impl HardwareProvider for AmazonBraketProvider {
    fn name(&self) -> &str {
        "Amazon Braket"
    }

    fn provider_type(&self) -> ProviderType {
        ProviderType::AmazonBraket
    }

    fn available_devices(&self) -> Vec<DeviceInfo> {
        vec![Self::harmony_device(), Self::aspen_device()]
    }

    fn device_calibration(&self, device: &str) -> Option<DeviceCalibration> {
        let dev = self
            .available_devices()
            .into_iter()
            .find(|d| d.name == device)?;
        Some(synthetic_calibration(device, dev.num_qubits, &dev.coupling_map))
    }

    fn submit_circuit(
        &self,
        _qasm: &str,
        _shots: u32,
        _device: &str,
    ) -> Result<JobHandle, HardwareError> {
        Err(HardwareError::AuthenticationFailed(
            "AWS credentials not configured. Set AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY."
                .into(),
        ))
    }

    fn job_status(&self, _handle: &JobHandle) -> Result<JobStatus, HardwareError> {
        Err(HardwareError::AuthenticationFailed(
            "AWS credentials not configured.".into(),
        ))
    }

    fn job_results(&self, _handle: &JobHandle) -> Result<HardwareResult, HardwareError> {
        Err(HardwareError::AuthenticationFailed(
            "AWS credentials not configured.".into(),
        ))
    }
}

// ---------------------------------------------------------------------------
// Provider registry
// ---------------------------------------------------------------------------

/// Registry that manages multiple [`HardwareProvider`] implementations.
///
/// Provides lookup by [`ProviderType`] and aggregated device listing across
/// all registered providers.
pub struct ProviderRegistry {
    providers: Vec<Box<dyn HardwareProvider>>,
}

impl ProviderRegistry {
    /// Create an empty registry with no providers.
    pub fn new() -> Self {
        Self {
            providers: Vec::new(),
        }
    }

    /// Register a new hardware provider.
    pub fn register(&mut self, provider: Box<dyn HardwareProvider>) {
        self.providers.push(provider);
    }

    /// Look up a provider by its type discriminant.
    ///
    /// Returns a reference to the first registered provider of the given type,
    /// or `None` if no such provider has been registered.
    pub fn get(&self, provider: ProviderType) -> Option<&dyn HardwareProvider> {
        self.providers
            .iter()
            .find(|p| p.provider_type() == provider)
            .map(|p| p.as_ref())
    }

    /// Collect device info from every registered provider.
    pub fn all_devices(&self) -> Vec<DeviceInfo> {
        self.providers
            .iter()
            .flat_map(|p| p.available_devices())
            .collect()
    }
}

impl Default for ProviderRegistry {
    /// Create a registry pre-loaded with the [`LocalSimulatorProvider`].
    fn default() -> Self {
        let mut reg = Self::new();
        reg.register(Box::new(LocalSimulatorProvider));
        reg
    }
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

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

    // -- ProviderType --

    #[test]
    fn provider_type_display() {
        assert_eq!(format!("{}", ProviderType::IbmQuantum), "IBM Quantum");
        assert_eq!(format!("{}", ProviderType::IonQ), "IonQ");
        assert_eq!(format!("{}", ProviderType::Rigetti), "Rigetti");
        assert_eq!(format!("{}", ProviderType::AmazonBraket), "Amazon Braket");
        assert_eq!(
            format!("{}", ProviderType::LocalSimulator),
            "Local Simulator"
        );
    }

    #[test]
    fn provider_type_equality() {
        assert_eq!(ProviderType::IbmQuantum, ProviderType::IbmQuantum);
        assert_ne!(ProviderType::IbmQuantum, ProviderType::IonQ);
    }

    // -- DeviceStatus --

    #[test]
    fn device_status_display() {
        assert_eq!(format!("{}", DeviceStatus::Online), "online");
        assert_eq!(format!("{}", DeviceStatus::Offline), "offline");
        assert_eq!(format!("{}", DeviceStatus::Maintenance), "maintenance");
        assert_eq!(format!("{}", DeviceStatus::Retired), "retired");
    }

    // -- JobStatus --

    #[test]
    fn job_status_variants() {
        let queued = JobStatus::Queued;
        let running = JobStatus::Running;
        let completed = JobStatus::Completed;
        let failed = JobStatus::Failed("timeout".to_string());
        let cancelled = JobStatus::Cancelled;

        assert_eq!(queued, JobStatus::Queued);
        assert_eq!(running, JobStatus::Running);
        assert_eq!(completed, JobStatus::Completed);
        assert_eq!(failed, JobStatus::Failed("timeout".to_string()));
        assert_eq!(cancelled, JobStatus::Cancelled);
    }

    // -- HardwareError --

    #[test]
    fn hardware_error_display() {
        let e = HardwareError::AuthenticationFailed("no token".into());
        assert!(format!("{}", e).contains("authentication failed"));

        let e = HardwareError::DeviceNotFound("foo".into());
        assert!(format!("{}", e).contains("device not found"));

        let e = HardwareError::DeviceOffline("bar".into());
        assert!(format!("{}", e).contains("device offline"));

        let e = HardwareError::CircuitTooLarge {
            qubits: 50,
            max: 32,
        };
        let msg = format!("{}", e);
        assert!(msg.contains("50"));
        assert!(msg.contains("32"));

        let e = HardwareError::JobFailed("oops".into());
        assert!(format!("{}", e).contains("job failed"));

        let e = HardwareError::NetworkError("timeout".into());
        assert!(format!("{}", e).contains("network error"));

        let e = HardwareError::RateLimited {
            retry_after_ms: 5000,
        };
        assert!(format!("{}", e).contains("5000"));
    }

    #[test]
    fn hardware_error_is_error_trait() {
        let e: Box<dyn std::error::Error> =
            Box::new(HardwareError::NetworkError("test".into()));
        assert!(e.to_string().contains("network error"));
    }

    // -- DeviceInfo --

    #[test]
    fn device_info_construction() {
        let dev = DeviceInfo {
            name: "test_device".into(),
            provider: ProviderType::LocalSimulator,
            num_qubits: 5,
            basis_gates: vec!["h".into(), "cx".into()],
            coupling_map: vec![(0, 1), (1, 2)],
            max_shots: 1000,
            status: DeviceStatus::Online,
        };
        assert_eq!(dev.name, "test_device");
        assert_eq!(dev.num_qubits, 5);
        assert_eq!(dev.basis_gates.len(), 2);
        assert_eq!(dev.coupling_map.len(), 2);
        assert_eq!(dev.status, DeviceStatus::Online);
    }

    // -- JobHandle --

    #[test]
    fn job_handle_construction() {
        let handle = JobHandle {
            job_id: "abc-123".into(),
            provider: ProviderType::IonQ,
            submitted_at: 1700000000,
        };
        assert_eq!(handle.job_id, "abc-123");
        assert_eq!(handle.provider, ProviderType::IonQ);
        assert_eq!(handle.submitted_at, 1700000000);
    }

    // -- HardwareResult --

    #[test]
    fn hardware_result_construction() {
        let mut counts = HashMap::new();
        counts.insert(vec![false, false], 500);
        counts.insert(vec![true, true], 500);
        let result = HardwareResult {
            counts,
            shots: 1000,
            execution_time_ms: 42,
            device_name: "test".into(),
        };
        assert_eq!(result.shots, 1000);
        assert_eq!(result.counts.len(), 2);
        assert_eq!(result.execution_time_ms, 42);
    }

    // -- DeviceCalibration --

    #[test]
    fn device_calibration_construction() {
        let cal = DeviceCalibration {
            device_name: "dev".into(),
            timestamp: 1700000000,
            qubit_t1: vec![100.0, 110.0],
            qubit_t2: vec![80.0, 85.0],
            readout_error: vec![(0.01, 0.02), (0.015, 0.025)],
            gate_errors: HashMap::new(),
            gate_times: HashMap::new(),
            coupling_map: vec![(0, 1)],
        };
        assert_eq!(cal.qubit_t1.len(), 2);
        assert_eq!(cal.qubit_t2.len(), 2);
        assert_eq!(cal.readout_error.len(), 2);
    }

    // -- QASM parsing helpers --

    #[test]
    fn parse_qubit_count_openqasm2() {
        let qasm = "OPENQASM 2.0;\ninclude \"qelib1.inc\";\nqreg q[5];\ncreg c[5];\nh q[0];\n";
        assert_eq!(parse_qubit_count(qasm, 1), 5);
    }

    #[test]
    fn parse_qubit_count_openqasm3() {
        let qasm = "OPENQASM 3.0;\nqubit[8] q;\nbit[8] c;\n";
        assert_eq!(parse_qubit_count(qasm, 1), 8);
    }

    #[test]
    fn parse_qubit_count_multiple_registers() {
        let qasm = "qreg a[3];\nqreg b[4];\n";
        assert_eq!(parse_qubit_count(qasm, 1), 7);
    }

    #[test]
    fn parse_qubit_count_fallback() {
        let qasm = "h q[0];\ncx q[0], q[1];\n";
        assert_eq!(parse_qubit_count(qasm, 2), 2);
    }

    #[test]
    fn parse_gate_count_basic() {
        let qasm =
            "OPENQASM 2.0;\ninclude \"qelib1.inc\";\nqreg q[2];\ncreg c[2];\nh q[0];\ncx q[0], q[1];\nmeasure q[0] -> c[0];\n";
        assert_eq!(parse_gate_count(qasm), 3);
    }

    #[test]
    fn parse_gate_count_empty() {
        let qasm = "OPENQASM 2.0;\ninclude \"qelib1.inc\";\nqreg q[2];\n";
        assert_eq!(parse_gate_count(qasm), 0);
    }

    // -- Synthetic calibration --

    #[test]
    fn synthetic_calibration_correct_sizes() {
        let coupling = vec![(0, 1), (1, 0), (1, 2), (2, 1)];
        let cal = synthetic_calibration("test", 3, &coupling);
        assert_eq!(cal.device_name, "test");
        assert_eq!(cal.qubit_t1.len(), 3);
        assert_eq!(cal.qubit_t2.len(), 3);
        assert_eq!(cal.readout_error.len(), 3);
        assert_eq!(cal.coupling_map.len(), 4);
        // Single-qubit gates: 3 types x 3 qubits = 9
        // Two-qubit gates: 4 edges
        assert!(cal.gate_errors.len() >= 9);
        assert!(cal.gate_times.len() >= 9);
    }

    #[test]
    fn synthetic_calibration_values_positive() {
        let cal = synthetic_calibration("dev", 5, &[(0, 1)]);
        for t1 in &cal.qubit_t1 {
            assert!(*t1 > 0.0, "T1 must be positive");
        }
        for t2 in &cal.qubit_t2 {
            assert!(*t2 > 0.0, "T2 must be positive");
        }
        for &(p0, p1) in &cal.readout_error {
            assert!(p0 >= 0.0 && p0 <= 1.0);
            assert!(p1 >= 0.0 && p1 <= 1.0);
        }
    }

    // -- Coupling map helpers --

    #[test]
    fn linear_coupling_map_correct() {
        let map = linear_coupling_map(4);
        // 3 edges * 2 directions = 6
        assert_eq!(map.len(), 6);
        assert!(map.contains(&(0, 1)));
        assert!(map.contains(&(1, 0)));
        assert!(map.contains(&(2, 3)));
        assert!(map.contains(&(3, 2)));
    }

    #[test]
    fn linear_coupling_map_single_qubit() {
        let map = linear_coupling_map(1);
        assert!(map.is_empty());
    }

    #[test]
    fn heavy_hex_coupling_map_has_cross_links() {
        let map = heavy_hex_coupling_map(20);
        // Should have linear edges plus cross-links.
        assert!(map.len() > linear_coupling_map(20).len());
        // Cross-link from 0 to 4 should exist.
        assert!(map.contains(&(0, 4)));
        assert!(map.contains(&(4, 0)));
    }

    // -- LocalSimulatorProvider --

    #[test]
    fn local_provider_name_and_type() {
        let prov = LocalSimulatorProvider;
        assert_eq!(prov.name(), "Local Simulator");
        assert_eq!(prov.provider_type(), ProviderType::LocalSimulator);
    }

    #[test]
    fn local_provider_devices() {
        let prov = LocalSimulatorProvider;
        let devs = prov.available_devices();
        assert_eq!(devs.len(), 1);
        assert_eq!(devs[0].name, "local_statevector_simulator");
        assert_eq!(devs[0].num_qubits, 32);
        assert_eq!(devs[0].status, DeviceStatus::Online);
        assert!(devs[0].basis_gates.contains(&"h".to_string()));
        assert!(devs[0].basis_gates.contains(&"cx".to_string()));
    }

    #[test]
    fn local_provider_calibration() {
        let prov = LocalSimulatorProvider;
        let cal = prov
            .device_calibration("local_statevector_simulator")
            .expect("calibration should exist");
        assert_eq!(cal.device_name, "local_statevector_simulator");
        assert_eq!(cal.qubit_t1.len(), 32);
        // Simulator has ideal gates.
        for &(p0, p1) in &cal.readout_error {
            assert!((p0 - 0.0).abs() < 1e-12);
            assert!((p1 - 0.0).abs() < 1e-12);
        }
        for val in cal.gate_errors.values() {
            assert!((*val - 0.0).abs() < 1e-12);
        }
    }

    #[test]
    fn local_provider_calibration_unknown_device() {
        let prov = LocalSimulatorProvider;
        assert!(prov.device_calibration("nonexistent").is_none());
    }

    #[test]
    fn local_provider_submit_and_retrieve() {
        let prov = LocalSimulatorProvider;
        let qasm = "OPENQASM 2.0;\nqreg q[2];\nh q[0];\ncx q[0], q[1];\n";
        let handle = prov
            .submit_circuit(qasm, 100, "local_statevector_simulator")
            .expect("submit should succeed");

        assert_eq!(handle.provider, ProviderType::LocalSimulator);
        assert!(handle.job_id.starts_with("local-"));

        // Job status should be completed.
        let status = prov.job_status(&handle).expect("status should succeed");
        assert_eq!(status, JobStatus::Completed);

        // Results should have the right shot count.
        let result = prov.job_results(&handle).expect("results should succeed");
        assert_eq!(result.device_name, "local_statevector_simulator");
        // Total counts should equal the number of shots.
        let total: usize = result.counts.values().sum();
        assert_eq!(total, 100);
        assert_eq!(result.shots, 100);
    }

    #[test]
    fn local_provider_submit_wrong_device() {
        let prov = LocalSimulatorProvider;
        let result = prov.submit_circuit("qreg q[2];", 10, "wrong_device");
        assert!(result.is_err());
        match result.unwrap_err() {
            HardwareError::DeviceNotFound(name) => assert_eq!(name, "wrong_device"),
            other => panic!("expected DeviceNotFound, got: {:?}", other),
        }
    }

    #[test]
    fn local_provider_circuit_too_large() {
        let prov = LocalSimulatorProvider;
        let qasm = "OPENQASM 2.0;\nqreg q[50];\n";
        let result = prov.submit_circuit(qasm, 10, "local_statevector_simulator");
        assert!(result.is_err());
        match result.unwrap_err() {
            HardwareError::CircuitTooLarge { qubits, max } => {
                assert_eq!(qubits, 50);
                assert_eq!(max, 32);
            }
            other => panic!("expected CircuitTooLarge, got: {:?}", other),
        }
    }

    #[test]
    fn local_provider_unknown_job() {
        let prov = LocalSimulatorProvider;
        let handle = JobHandle {
            job_id: "nonexistent".into(),
            provider: ProviderType::LocalSimulator,
            submitted_at: 0,
        };
        assert!(prov.job_status(&handle).is_err());
        assert!(prov.job_results(&handle).is_err());
    }

    #[test]
    fn local_provider_wrong_provider_handle() {
        let prov = LocalSimulatorProvider;
        let handle = JobHandle {
            job_id: "some-id".into(),
            provider: ProviderType::IbmQuantum,
            submitted_at: 0,
        };
        assert!(prov.job_status(&handle).is_err());
        assert!(prov.job_results(&handle).is_err());
    }

    // -- IBM Quantum stub --

    #[test]
    fn ibm_provider_name_and_type() {
        let prov = IbmQuantumProvider;
        assert_eq!(prov.name(), "IBM Quantum");
        assert_eq!(prov.provider_type(), ProviderType::IbmQuantum);
    }

    #[test]
    fn ibm_provider_devices() {
        let prov = IbmQuantumProvider;
        let devs = prov.available_devices();
        assert_eq!(devs.len(), 2);

        let brisbane = devs.iter().find(|d| d.name == "ibm_brisbane").unwrap();
        assert_eq!(brisbane.num_qubits, 127);
        assert_eq!(brisbane.provider, ProviderType::IbmQuantum);
        assert_eq!(brisbane.status, DeviceStatus::Online);

        let fez = devs.iter().find(|d| d.name == "ibm_fez").unwrap();
        assert_eq!(fez.num_qubits, 133);
    }

    #[test]
    fn ibm_provider_calibration() {
        let prov = IbmQuantumProvider;
        let cal = prov
            .device_calibration("ibm_brisbane")
            .expect("calibration should exist");
        assert_eq!(cal.qubit_t1.len(), 127);
        assert_eq!(cal.qubit_t2.len(), 127);
        assert_eq!(cal.readout_error.len(), 127);
    }

    #[test]
    fn ibm_provider_calibration_unknown_device() {
        let prov = IbmQuantumProvider;
        assert!(prov.device_calibration("nonexistent").is_none());
    }

    #[test]
    fn ibm_provider_submit_fails_auth() {
        let prov = IbmQuantumProvider;
        let result = prov.submit_circuit("qreg q[2];", 100, "ibm_brisbane");
        assert!(result.is_err());
        match result.unwrap_err() {
            HardwareError::AuthenticationFailed(msg) => {
                assert!(msg.contains("IBM Quantum"));
            }
            other => panic!("expected AuthenticationFailed, got: {:?}", other),
        }
    }

    #[test]
    fn ibm_provider_job_status_fails_auth() {
        let prov = IbmQuantumProvider;
        let handle = JobHandle {
            job_id: "x".into(),
            provider: ProviderType::IbmQuantum,
            submitted_at: 0,
        };
        assert!(prov.job_status(&handle).is_err());
        assert!(prov.job_results(&handle).is_err());
    }

    // -- IonQ stub --

    #[test]
    fn ionq_provider_name_and_type() {
        let prov = IonQProvider;
        assert_eq!(prov.name(), "IonQ");
        assert_eq!(prov.provider_type(), ProviderType::IonQ);
    }

    #[test]
    fn ionq_provider_devices() {
        let prov = IonQProvider;
        let devs = prov.available_devices();
        assert_eq!(devs.len(), 2);

        let aria = devs.iter().find(|d| d.name == "ionq_aria").unwrap();
        assert_eq!(aria.num_qubits, 25);
        // Trapped-ion: full connectivity = 25*24 = 600 edges.
        assert_eq!(aria.coupling_map.len(), 25 * 24);

        let forte = devs.iter().find(|d| d.name == "ionq_forte").unwrap();
        assert_eq!(forte.num_qubits, 36);
    }

    #[test]
    fn ionq_provider_calibration_aria() {
        let prov = IonQProvider;
        let cal = prov
            .device_calibration("ionq_aria")
            .expect("calibration should exist");
        assert_eq!(cal.qubit_t1.len(), 25);
        // Trapped-ion T1 should be very long.
        for t1 in &cal.qubit_t1 {
            assert!(*t1 > 1_000_000.0);
        }
    }

    #[test]
    fn ionq_provider_calibration_forte() {
        let prov = IonQProvider;
        let cal = prov
            .device_calibration("ionq_forte")
            .expect("calibration should exist");
        assert_eq!(cal.qubit_t1.len(), 36);
    }

    #[test]
    fn ionq_provider_calibration_unknown() {
        let prov = IonQProvider;
        assert!(prov.device_calibration("nonexistent").is_none());
    }

    #[test]
    fn ionq_provider_submit_fails_auth() {
        let prov = IonQProvider;
        let result = prov.submit_circuit("qreg q[2];", 100, "ionq_aria");
        assert!(result.is_err());
        match result.unwrap_err() {
            HardwareError::AuthenticationFailed(msg) => {
                assert!(msg.contains("IonQ"));
            }
            other => panic!("expected AuthenticationFailed, got: {:?}", other),
        }
    }

    // -- Rigetti stub --

    #[test]
    fn rigetti_provider_name_and_type() {
        let prov = RigettiProvider;
        assert_eq!(prov.name(), "Rigetti");
        assert_eq!(prov.provider_type(), ProviderType::Rigetti);
    }

    #[test]
    fn rigetti_provider_devices() {
        let prov = RigettiProvider;
        let devs = prov.available_devices();
        assert_eq!(devs.len(), 1);
        assert_eq!(devs[0].name, "rigetti_ankaa_2");
        assert_eq!(devs[0].num_qubits, 84);
    }

    #[test]
    fn rigetti_provider_calibration() {
        let prov = RigettiProvider;
        let cal = prov
            .device_calibration("rigetti_ankaa_2")
            .expect("calibration should exist");
        assert_eq!(cal.qubit_t1.len(), 84);
        assert_eq!(cal.qubit_t2.len(), 84);
    }

    #[test]
    fn rigetti_provider_calibration_unknown() {
        let prov = RigettiProvider;
        assert!(prov.device_calibration("nonexistent").is_none());
    }

    #[test]
    fn rigetti_provider_submit_fails_auth() {
        let prov = RigettiProvider;
        let result = prov.submit_circuit("qreg q[2];", 100, "rigetti_ankaa_2");
        assert!(result.is_err());
        match result.unwrap_err() {
            HardwareError::AuthenticationFailed(msg) => {
                assert!(msg.contains("Rigetti"));
            }
            other => panic!("expected AuthenticationFailed, got: {:?}", other),
        }
    }

    // -- Amazon Braket stub --

    #[test]
    fn braket_provider_name_and_type() {
        let prov = AmazonBraketProvider;
        assert_eq!(prov.name(), "Amazon Braket");
        assert_eq!(prov.provider_type(), ProviderType::AmazonBraket);
    }

    #[test]
    fn braket_provider_devices() {
        let prov = AmazonBraketProvider;
        let devs = prov.available_devices();
        assert_eq!(devs.len(), 2);

        let harmony = devs
            .iter()
            .find(|d| d.name == "braket_ionq_harmony")
            .unwrap();
        assert_eq!(harmony.num_qubits, 11);

        let aspen = devs
            .iter()
            .find(|d| d.name == "braket_rigetti_aspen_m3")
            .unwrap();
        assert_eq!(aspen.num_qubits, 79);
    }

    #[test]
    fn braket_provider_calibration() {
        let prov = AmazonBraketProvider;
        let cal = prov
            .device_calibration("braket_ionq_harmony")
            .expect("calibration should exist");
        assert_eq!(cal.qubit_t1.len(), 11);

        let cal2 = prov
            .device_calibration("braket_rigetti_aspen_m3")
            .expect("calibration should exist");
        assert_eq!(cal2.qubit_t1.len(), 79);
    }

    #[test]
    fn braket_provider_calibration_unknown() {
        let prov = AmazonBraketProvider;
        assert!(prov.device_calibration("nonexistent").is_none());
    }

    #[test]
    fn braket_provider_submit_fails_auth() {
        let prov = AmazonBraketProvider;
        let result = prov.submit_circuit("qreg q[2];", 100, "braket_ionq_harmony");
        assert!(result.is_err());
        match result.unwrap_err() {
            HardwareError::AuthenticationFailed(msg) => {
                assert!(msg.contains("AWS"));
            }
            other => panic!("expected AuthenticationFailed, got: {:?}", other),
        }
    }

    // -- ProviderRegistry --

    #[test]
    fn registry_new_is_empty() {
        let reg = ProviderRegistry::new();
        assert!(reg.all_devices().is_empty());
        assert!(reg.get(ProviderType::LocalSimulator).is_none());
    }

    #[test]
    fn registry_default_has_local_simulator() {
        let reg = ProviderRegistry::default();
        let local = reg.get(ProviderType::LocalSimulator);
        assert!(local.is_some());
        assert_eq!(local.unwrap().name(), "Local Simulator");
    }

    #[test]
    fn registry_default_devices() {
        let reg = ProviderRegistry::default();
        let devs = reg.all_devices();
        assert_eq!(devs.len(), 1);
        assert_eq!(devs[0].name, "local_statevector_simulator");
    }

    #[test]
    fn registry_register_multiple() {
        let mut reg = ProviderRegistry::new();
        reg.register(Box::new(LocalSimulatorProvider));
        reg.register(Box::new(IbmQuantumProvider));
        reg.register(Box::new(IonQProvider));
        reg.register(Box::new(RigettiProvider));
        reg.register(Box::new(AmazonBraketProvider));

        // All providers should be accessible.
        assert!(reg.get(ProviderType::LocalSimulator).is_some());
        assert!(reg.get(ProviderType::IbmQuantum).is_some());
        assert!(reg.get(ProviderType::IonQ).is_some());
        assert!(reg.get(ProviderType::Rigetti).is_some());
        assert!(reg.get(ProviderType::AmazonBraket).is_some());

        // Total devices: 1 + 2 + 2 + 1 + 2 = 8
        assert_eq!(reg.all_devices().len(), 8);
    }

    #[test]
    fn registry_get_nonexistent() {
        let reg = ProviderRegistry::default();
        assert!(reg.get(ProviderType::IbmQuantum).is_none());
    }

    #[test]
    fn registry_all_devices_aggregates() {
        let mut reg = ProviderRegistry::new();
        reg.register(Box::new(IbmQuantumProvider));
        reg.register(Box::new(IonQProvider));

        let devs = reg.all_devices();
        // IBM: 2 devices, IonQ: 2 devices
        assert_eq!(devs.len(), 4);
        let names: Vec<&str> = devs.iter().map(|d| d.name.as_str()).collect();
        assert!(names.contains(&"ibm_brisbane"));
        assert!(names.contains(&"ibm_fez"));
        assert!(names.contains(&"ionq_aria"));
        assert!(names.contains(&"ionq_forte"));
    }

    // -- Integration: submit through registry --

    #[test]
    fn registry_local_submit_integration() {
        let reg = ProviderRegistry::default();
        let local = reg.get(ProviderType::LocalSimulator).unwrap();
        let qasm = "OPENQASM 2.0;\nqreg q[2];\n";
        let handle = local
            .submit_circuit(qasm, 50, "local_statevector_simulator")
            .expect("submit should succeed");
        let status = local.job_status(&handle).expect("status should succeed");
        assert_eq!(status, JobStatus::Completed);
        let result = local.job_results(&handle).expect("results should succeed");
        let total: usize = result.counts.values().sum();
        assert_eq!(total, 50);
    }

    #[test]
    fn registry_stub_submit_through_registry() {
        let mut reg = ProviderRegistry::new();
        reg.register(Box::new(IbmQuantumProvider));
        let ibm = reg.get(ProviderType::IbmQuantum).unwrap();
        let result = ibm.submit_circuit("qreg q[2];", 100, "ibm_brisbane");
        assert!(result.is_err());
    }

    // -- Trait object safety --

    #[test]
    fn provider_trait_is_object_safe() {
        // Verify that HardwareProvider can be used as a trait object.
        let providers: Vec<Box<dyn HardwareProvider>> = vec![
            Box::new(LocalSimulatorProvider),
            Box::new(IbmQuantumProvider),
            Box::new(IonQProvider),
            Box::new(RigettiProvider),
            Box::new(AmazonBraketProvider),
        ];
        assert_eq!(providers.len(), 5);
        for p in &providers {
            assert!(!p.name().is_empty());
            assert!(!p.available_devices().is_empty());
        }
    }

    // -- Send + Sync --

    #[test]
    fn providers_are_send_sync() {
        fn assert_send_sync<T: Send + Sync>() {}
        assert_send_sync::<LocalSimulatorProvider>();
        assert_send_sync::<IbmQuantumProvider>();
        assert_send_sync::<IonQProvider>();
        assert_send_sync::<RigettiProvider>();
        assert_send_sync::<AmazonBraketProvider>();
    }
}