switchy_p2p 0.2.0

P2P communication abstraction system
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
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
//! P2P Network Simulator
//!
//! This module provides a complete P2P network simulation with realistic network conditions,
//! including latency, packet loss, and network partitions. It supports:
//!
//! - Graph-based network topology with configurable links
//! - Realistic network simulation with latency and packet loss
//! - Connection management with async message passing
//! - Network partitions for testing distributed system behavior
//! - Environment-configurable parameters for testing different conditions

use std::collections::hash_map::DefaultHasher;
use std::collections::{BTreeMap, VecDeque};
use std::fmt::{self, Display};
use std::hash::{Hash, Hasher};
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::time::Duration;
use switchy_async::sync::RwLock;
use switchy_random::{Rng, rng};

/// Get default latency from environment or use 50ms
fn default_latency() -> Duration {
    std::env::var("SIMULATOR_DEFAULT_LATENCY_MS")
        .ok()
        .and_then(|s| s.parse().ok())
        .map_or(Duration::from_millis(50), Duration::from_millis)
}

/// Get default packet loss from environment or use 1%
fn default_packet_loss() -> f64 {
    std::env::var("SIMULATOR_DEFAULT_PACKET_LOSS")
        .ok()
        .and_then(|s| s.parse().ok())
        .unwrap_or(0.01) // 1% default
}

/// Get discovery delay from environment or use 100ms
#[allow(dead_code)] // Used in Phase 2.4
fn discovery_delay() -> Duration {
    std::env::var("SIMULATOR_DISCOVERY_DELAY_MS")
        .ok()
        .and_then(|s| s.parse().ok())
        .map_or(Duration::from_millis(100), Duration::from_millis)
}

/// Get connection timeout from environment or use 30s
#[allow(dead_code)] // Used in Phase 2.3
fn connection_timeout() -> Duration {
    std::env::var("SIMULATOR_CONNECTION_TIMEOUT_SECS")
        .ok()
        .and_then(|s| s.parse().ok())
        .map_or(Duration::from_secs(30), Duration::from_secs)
}

/// Get max message size from environment or use 1MB
fn max_message_size() -> usize {
    std::env::var("SIMULATOR_MAX_MESSAGE_SIZE")
        .ok()
        .and_then(|s| s.parse().ok())
        .unwrap_or(1024 * 1024) // 1MB default
}

/// A network topology graph representing nodes and links in the P2P simulation
///
/// The `NetworkGraph` maintains the complete network topology including all nodes,
/// their connections, and link characteristics like latency and packet loss.
/// It supports dynamic topology changes including network partitions.
#[derive(Debug, Clone)]
pub struct NetworkGraph {
    nodes: BTreeMap<SimulatorNodeId, NodeInfo>,
    links: BTreeMap<(SimulatorNodeId, SimulatorNodeId), LinkInfo>,
}

/// Information about a node in the P2P network
///
/// Contains node identity, online status, registered names for discovery,
/// and message queues for each connected peer to maintain FIFO ordering.
#[derive(Debug, Clone)]
pub struct NodeInfo {
    #[allow(dead_code)] // Used in Phase 2.4
    id: SimulatorNodeId,
    #[allow(dead_code)] // Used in Phase 2.3
    is_online: bool,
    #[allow(dead_code)] // Used in Phase 2.4
    registered_names: BTreeMap<String, String>, // For DNS-like discovery
    message_queues: BTreeMap<SimulatorNodeId, VecDeque<Vec<u8>>>,
}

/// Network link characteristics between two nodes
///
/// Defines the properties of a network connection including latency, packet loss,
/// bandwidth limitations, and whether the link is currently active.
#[derive(Debug, Clone)]
pub struct LinkInfo {
    latency: Duration,
    packet_loss: f64,
    #[allow(dead_code)] // Used in Phase 2.3
    bandwidth_limit: Option<u64>, // bytes per second
    is_active: bool,
}

impl NetworkGraph {
    /// Create a new empty network graph
    ///
    /// Returns a graph with no nodes or links. Nodes and connections can be added
    /// using [`add_node`](Self::add_node) and [`connect_nodes`](Self::connect_nodes).
    #[must_use]
    pub const fn new() -> Self {
        Self {
            nodes: BTreeMap::new(),
            links: BTreeMap::new(),
        }
    }

    /// Add a new node to the network graph
    ///
    /// Creates a new node with default state (online, empty message queues, no registered names).
    /// If the node already exists, this operation has no effect.
    pub fn add_node(&mut self, node_id: SimulatorNodeId) {
        self.nodes.insert(
            node_id.clone(),
            NodeInfo {
                id: node_id,
                is_online: true,
                registered_names: BTreeMap::new(),
                message_queues: BTreeMap::new(),
            },
        );
    }

    /// Create a bidirectional connection between two nodes
    ///
    /// Establishes a network link with the specified characteristics (latency, packet loss, etc.).
    /// The connection is automatically bidirectional with identical properties in both directions.
    pub fn connect_nodes(&mut self, a: SimulatorNodeId, b: SimulatorNodeId, link: LinkInfo) {
        self.links.insert((a.clone(), b.clone()), link.clone());
        self.links.insert((b, a), link); // Bidirectional
    }

    /// Find a path between two nodes using breadth-first search
    ///
    /// Searches the network graph for an active route from the source node to the destination node.
    /// Returns the shortest path if one exists, considering only active links.
    ///
    /// # Returns
    ///
    /// * `Some(Vec<SimulatorNodeId>)` - The path from source to destination, including both endpoints
    /// * `None` - No active path exists between the nodes (network partition)
    ///
    /// # Examples
    ///
    /// ```rust
    /// use switchy_p2p::simulator::{NetworkGraph, SimulatorNodeId};
    ///
    /// let mut graph = NetworkGraph::new();
    /// let alice = SimulatorNodeId::from_seed("alice");
    /// graph.add_node(alice.clone());
    ///
    /// let path = graph.find_path(alice.clone(), alice);
    /// assert!(path.is_some());
    /// ```
    #[must_use]
    pub fn find_path(
        &self,
        from: SimulatorNodeId,
        to: SimulatorNodeId,
    ) -> Option<Vec<SimulatorNodeId>> {
        if from == to {
            return Some(vec![from]);
        }

        let mut queue = VecDeque::new();
        let mut visited = std::collections::BTreeSet::new();
        let mut parent: BTreeMap<SimulatorNodeId, SimulatorNodeId> = BTreeMap::new();

        queue.push_back(from.clone());
        visited.insert(from);

        while let Some(current) = queue.pop_front() {
            // Check all neighbors
            for ((link_from, link_to), link_info) in &self.links {
                if *link_from == current && link_info.is_active {
                    if *link_to == to {
                        // Found path, reconstruct it
                        let mut path = vec![to, current.clone()];
                        let mut node = current;
                        while let Some(prev) = parent.get(&node) {
                            path.push(prev.clone());
                            node = prev.clone();
                        }
                        path.reverse();
                        return Some(path);
                    }

                    if !visited.contains(link_to) {
                        visited.insert(link_to.clone());
                        parent.insert(link_to.clone(), current.clone());
                        queue.push_back(link_to.clone());
                    }
                }
            }
        }

        None // No path found
    }

    /// Create a network partition between two groups of nodes
    ///
    /// Removes all links between nodes in `group_a` and nodes in `group_b`,
    /// simulating a network partition where the groups cannot communicate.
    pub fn add_partition(&mut self, group_a: &[SimulatorNodeId], group_b: &[SimulatorNodeId]) {
        for a in group_a {
            for b in group_b {
                self.links.remove(&(a.clone(), b.clone()));
                self.links.remove(&(b.clone(), a.clone()));
            }
        }
    }

    /// Restore connectivity between two previously partitioned groups
    ///
    /// Re-establishes links between all nodes in `group_a` and all nodes in `group_b`
    /// using default network characteristics (environment-configurable latency and packet loss).
    pub fn heal_partition(&mut self, group_a: &[SimulatorNodeId], group_b: &[SimulatorNodeId]) {
        let default_link = LinkInfo {
            latency: default_latency(),
            packet_loss: default_packet_loss(),
            bandwidth_limit: None,
            is_active: true,
        };

        for a in group_a {
            for b in group_b {
                self.connect_nodes(a.clone(), b.clone(), default_link.clone());
            }
        }
    }

    /// Get mutable reference to a node by its ID
    ///
    /// Returns `None` if the node does not exist in the graph.
    #[must_use]
    pub fn get_node_mut(&mut self, node_id: &SimulatorNodeId) -> Option<&mut NodeInfo> {
        self.nodes.get_mut(node_id)
    }

    /// Get immutable reference to a node by its ID
    ///
    /// Returns `None` if the node does not exist in the graph.
    #[must_use]
    pub fn get_node(&self, node_id: &SimulatorNodeId) -> Option<&NodeInfo> {
        self.nodes.get(node_id)
    }
}

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

/// A unique identifier for nodes in the P2P network
///
/// 256-bit (32-byte) identifier that uniquely identifies a peer in the network.
/// Supports deterministic generation from seeds for testing and random generation for production.
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct SimulatorNodeId([u8; 32]);

impl SimulatorNodeId {
    /// Creates a deterministic node ID from a string seed.
    ///
    /// This is useful for testing scenarios where predictable node IDs are needed.
    /// The same seed will always produce the same node ID across invocations.
    #[must_use]
    pub fn from_seed(seed: &str) -> Self {
        // Convert string to u64 for seeding
        let mut hasher = DefaultHasher::new();
        seed.hash(&mut hasher);
        let seed_u64 = hasher.finish();

        let rng = Rng::from_seed(seed_u64);
        let mut bytes = [0u8; 32];
        rng.fill(&mut bytes);
        Self(bytes)
    }

    /// Creates a node ID from raw 32-byte array.
    ///
    /// This constructor allows creating a node ID from known bytes,
    /// such as when deserializing from storage or network.
    #[must_use]
    pub const fn from_bytes(bytes: [u8; 32]) -> Self {
        Self(bytes)
    }

    /// Returns the raw 32-byte representation of this node ID.
    #[must_use]
    pub const fn as_bytes(&self) -> &[u8; 32] {
        &self.0
    }

    /// Formats the node ID as a short hex string for display.
    ///
    /// Returns the first 5 bytes (10 hex characters) of the node ID,
    /// which is typically sufficient for human identification.
    #[must_use]
    pub fn fmt_short(&self) -> String {
        format!(
            "{:02x}{:02x}{:02x}{:02x}{:02x}",
            self.0[0], self.0[1], self.0[2], self.0[3], self.0[4]
        )
    }

    /// Generates a random node ID for production use.
    ///
    /// Uses the system's random number generator to create a unique 256-bit identifier.
    /// Each call produces a new, unique node ID with extremely high probability.
    #[must_use]
    pub fn generate() -> Self {
        let mut bytes = [0u8; 32];
        rng().fill(&mut bytes);
        Self(bytes)
    }
}

impl Display for SimulatorNodeId {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        // Full hex encoding for now (Iroh uses z-base-32, but hex is simpler)
        for byte in &self.0 {
            write!(f, "{byte:02x}")?;
        }
        Ok(())
    }
}

/// Main P2P simulation node
///
/// Represents a single peer in the P2P network with its own node identity,
/// shared network topology view, and active connections to other peers.
/// Supports async connection establishment and message passing.
pub struct SimulatorP2P {
    node_id: SimulatorNodeId,
    network_graph: Arc<RwLock<NetworkGraph>>, // NEW in Phase 2.2
    connections: Arc<RwLock<BTreeMap<SimulatorNodeId, SimulatorConnection>>>, // NEW in Phase 2.3
}

impl SimulatorP2P {
    /// Creates a new simulator P2P instance with a random node ID.
    ///
    /// The node starts with an empty network graph and no active connections.
    /// Use [`with_seed`](Self::with_seed) for deterministic testing scenarios.
    #[must_use]
    pub fn new() -> Self {
        Self {
            node_id: SimulatorNodeId::generate(),
            network_graph: Arc::new(RwLock::new(NetworkGraph::new())),
            connections: Arc::new(RwLock::new(BTreeMap::new())), // NEW
        }
    }

    /// Creates a simulator P2P instance with a deterministic node ID.
    ///
    /// This constructor is useful for testing scenarios where reproducible node IDs
    /// are required. The same seed will always produce the same node ID.
    #[must_use]
    pub fn with_seed(seed: &str) -> Self {
        Self {
            node_id: SimulatorNodeId::from_seed(seed),
            network_graph: Arc::new(RwLock::new(NetworkGraph::new())),
            connections: Arc::new(RwLock::new(BTreeMap::new())), // NEW
        }
    }

    /// Returns a reference to this node's unique identifier.
    #[must_use]
    pub const fn local_node_id(&self) -> &SimulatorNodeId {
        &self.node_id
    }

    /// Connect to a remote peer
    ///
    /// Establishes a connection to another node in the network, setting up bidirectional
    /// message queues and verifying network connectivity through the topology graph.
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// * No route exists to the destination node (network partition)
    /// * Connection storage fails
    ///
    pub async fn connect(&self, remote_id: SimulatorNodeId) -> Result<SimulatorConnection, String> {
        let mut graph = self.network_graph.write().await;

        // 1. Ensure both nodes exist in graph
        if !graph.nodes.contains_key(&self.node_id) {
            graph.add_node(self.node_id.clone());
        }
        if !graph.nodes.contains_key(&remote_id) {
            graph.add_node(remote_id.clone());
        }

        // 2. Create message queues for bidirectional communication
        if let Some(local_node) = graph.get_node_mut(&self.node_id) {
            local_node
                .message_queues
                .entry(remote_id.clone())
                .or_insert_with(VecDeque::new);
        }
        if let Some(remote_node) = graph.get_node_mut(&remote_id) {
            remote_node
                .message_queues
                .entry(self.node_id.clone())
                .or_insert_with(VecDeque::new);
        }

        // 3. Check connectivity
        let has_path = graph
            .find_path(self.node_id.clone(), remote_id.clone())
            .is_some();
        if !has_path {
            return Err("No route to destination".to_string());
        }

        drop(graph);

        // 4. Create connection
        let connection = SimulatorConnection {
            local_id: self.node_id.clone(),
            remote_id: remote_id.clone(),
            network_graph: Arc::clone(&self.network_graph),
            is_connected: Arc::new(AtomicBool::new(true)),
        };

        // 5. Store in connections map
        {
            let mut connections = self.connections.write().await;
            connections.insert(remote_id, connection.clone());
        }

        Ok(connection)
    }

    /// Register a peer with a discoverable name in the network
    ///
    /// Associates a human-readable name with a node ID, enabling discovery through the
    /// DNS-like lookup system. Names can be used to connect to peers without knowing
    /// their exact node ID.
    ///
    /// # Errors
    ///
    /// Returns an error if the node registration fails
    pub async fn register_peer(&self, name: &str, node_id: SimulatorNodeId) -> Result<(), String> {
        let mut graph = self.network_graph.write().await;

        // Add node to graph if not exists
        if !graph.nodes.contains_key(&node_id) {
            graph.add_node(node_id.clone());
        }

        // Register name in the node's info
        if let Some(node_info) = graph.nodes.get_mut(&node_id) {
            node_info
                .registered_names
                .insert(name.to_string(), node_id.to_string());
        }
        drop(graph);

        Ok(())
    }

    /// Discover a peer by its registered name
    ///
    /// Performs a DNS-like lookup to find the node ID associated with a given name.
    /// Includes simulated network delay to model realistic discovery latency.
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// * The name is not registered with any node
    /// * The discovery service is unavailable
    pub async fn discover(&self, name: &str) -> Result<SimulatorNodeId, String> {
        // Simulate DNS lookup delay
        let delay = discovery_delay();
        switchy_async::time::sleep(delay).await;

        let graph = self.network_graph.read().await;

        // Search through all nodes for registered name
        for (node_id, node_info) in &graph.nodes {
            if node_info.registered_names.contains_key(name) {
                return Ok(node_id.clone());
            }
        }
        drop(graph);

        Err(format!("Name '{name}' not found"))
    }

    /// Connect to a peer by its registered name
    ///
    /// Convenience method that combines discovery and connection establishment.
    /// First discovers the node ID associated with the name, then establishes
    /// a connection to that peer.
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// * Discovery fails (name not found)
    /// * Connection establishment fails (no route, etc.)
    pub async fn connect_by_name(&self, name: &str) -> Result<SimulatorConnection, String> {
        let node_id = self.discover(name).await?;
        self.connect(node_id).await
    }
}

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

/// An active connection between two peers in the P2P network
///
/// Handles message routing through the network graph with realistic latency
/// and packet loss simulation. Messages are delivered asynchronously with
/// FIFO ordering guarantees.
#[derive(Debug, Clone)]
pub struct SimulatorConnection {
    local_id: SimulatorNodeId,
    remote_id: SimulatorNodeId,
    network_graph: Arc<RwLock<NetworkGraph>>,
    is_connected: Arc<AtomicBool>,
}

impl SimulatorConnection {
    /// Send data to remote peer through network simulation
    ///
    /// Routes the message through the network graph, simulating realistic network conditions
    /// including latency delays and probabilistic packet loss. Messages are delivered
    /// asynchronously with FIFO ordering guarantees.
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// * Connection is closed
    /// * Message exceeds maximum size limit (configurable via environment)
    /// * No route exists to destination (network partition)
    /// * Network graph access fails
    pub async fn send(&mut self, data: &[u8]) -> Result<(), String> {
        if !self.is_connected.load(Ordering::Relaxed) {
            return Err("Connection closed".to_string());
        }

        // Check message size limit
        let max_size = max_message_size();
        if data.len() > max_size {
            return Err(format!(
                "Message too large: {} bytes exceeds max {}",
                data.len(),
                max_size
            ));
        }

        let graph = self.network_graph.read().await;

        // 1. Find path from local to remote
        let path = graph
            .find_path(self.local_id.clone(), self.remote_id.clone())
            .ok_or_else(|| "No route to destination".to_string())?;

        // 2. Calculate total latency along path
        let total_latency = Self::calculate_path_latency(&graph, &path);

        // 3. Check packet loss along path
        if Self::packet_lost(&graph, &path) {
            return Ok(()); // Packet dropped, but not an error (simulate UDP-like behavior)
        }

        // 4. Sleep for network latency using switchy_async
        drop(graph); // Release lock before sleeping
        switchy_async::time::sleep(total_latency).await;

        // 5. Deliver message to remote's queue
        {
            let mut graph = self.network_graph.write().await;
            if let Some(remote_node) = graph.get_node_mut(&self.remote_id)
                && let Some(queue) = remote_node.message_queues.get_mut(&self.local_id)
            {
                queue.push_back(data.to_vec());
            }
        }

        Ok(())
    }

    /// Receive data from remote peer (non-blocking)
    ///
    /// Attempts to retrieve the next message from this peer's message queue.
    /// Returns immediately if no message is available.
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// * No message is currently available in the queue
    /// * Network graph access fails
    pub async fn recv(&mut self) -> Result<Vec<u8>, String> {
        {
            let mut graph = self.network_graph.write().await;

            if let Some(local_node) = graph.get_node_mut(&self.local_id)
                && let Some(queue) = local_node.message_queues.get_mut(&self.remote_id)
                && let Some(message) = queue.pop_front()
            {
                return Ok(message);
            }
        }

        Err("No message available".to_string())
    }

    /// Returns whether the connection is still active.
    ///
    /// A connection becomes inactive after [`close`](Self::close) is called.
    #[must_use]
    pub fn is_connected(&self) -> bool {
        self.is_connected.load(Ordering::Relaxed)
    }

    /// Returns the remote peer's node ID.
    #[must_use]
    pub const fn remote_node_id(&self) -> &SimulatorNodeId {
        &self.remote_id
    }

    /// Close the connection
    ///
    /// Marks the connection as disconnected, preventing further message sending.
    /// Existing messages in queues remain available for receiving.
    ///
    /// # Errors
    ///
    /// * This method currently always succeeds but returns `Result` for future extensibility.
    pub fn close(&mut self) -> Result<(), String> {
        self.is_connected.store(false, Ordering::Relaxed);
        Ok(())
    }

    /// Calculate total latency along a path
    fn calculate_path_latency(graph: &NetworkGraph, path: &[SimulatorNodeId]) -> Duration {
        let mut total = Duration::from_millis(0);
        for window in path.windows(2) {
            if let Some(link) = graph.links.get(&(window[0].clone(), window[1].clone())) {
                total += link.latency;
            }
        }
        total
    }

    /// Check if packet should be lost based on path
    fn packet_lost(graph: &NetworkGraph, path: &[SimulatorNodeId]) -> bool {
        for window in path.windows(2) {
            if let Some(link) = graph.links.get(&(window[0].clone(), window[1].clone()))
                && rng().gen_range(0.0..1.0) < link.packet_loss
            {
                return true;
            }
        }
        false
    }
}

impl crate::traits::P2PNodeId for SimulatorNodeId {
    fn from_bytes(bytes: &[u8; 32]) -> crate::types::P2PResult<Self> {
        // Uses existing from_bytes method (takes owned array, not reference)
        Ok(Self::from_bytes(*bytes))
    }

    fn as_bytes(&self) -> &[u8; 32] {
        self.as_bytes()
    }

    fn fmt_short(&self) -> String {
        self.fmt_short()
    }
}

/// Creates a deterministic node ID for testing purposes.
///
/// This is a convenience function that wraps [`SimulatorNodeId::from_seed`].
/// The same name will always produce the same node ID.
#[must_use]
pub fn test_node_id(name: &str) -> SimulatorNodeId {
    SimulatorNodeId::from_seed(name)
}

#[cfg(test)]
impl SimulatorP2P {
    /// Create a test setup with two connected peers
    ///
    /// Returns a tuple of (`simulator_instance`, `alice_id`, `bob_id`) where Alice and Bob
    /// are connected in the network graph with low-latency, high-reliability links
    /// suitable for testing scenarios.
    #[must_use]
    pub fn test_setup() -> (Self, SimulatorNodeId, SimulatorNodeId) {
        let alice = Self::new();
        let alice_id = alice.local_node_id().clone();

        let bob = Self::new();
        let bob_id = bob.local_node_id().clone();

        // Connect them in the network graph with default link
        {
            let mut graph = alice.network_graph.blocking_write();
            graph.connect_nodes(
                alice_id.clone(),
                bob_id.clone(),
                LinkInfo {
                    latency: Duration::from_millis(10),
                    packet_loss: 0.0,
                    bandwidth_limit: None,
                    is_active: true,
                },
            );
        }

        (alice, alice_id, bob_id)
    }
}

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

    // === SimulatorNodeId Tests ===

    #[test_log::test]
    fn test_node_id_deterministic() {
        let id1 = test_node_id("alice");
        let id2 = test_node_id("alice");
        assert_eq!(id1, id2);
    }

    #[test_log::test]
    fn test_node_id_different() {
        let alice = test_node_id("alice");
        let bob = test_node_id("bob");
        assert_ne!(alice, bob);
    }

    #[test_log::test]
    fn test_fmt_short() {
        let id = test_node_id("test");
        let short = id.fmt_short();
        assert_eq!(short.len(), 10); // 5 bytes = 10 hex chars
    }

    #[test_log::test]
    fn test_node_id_from_bytes() {
        let bytes = [42u8; 32];
        let id = SimulatorNodeId::from_bytes(bytes);
        assert_eq!(id.as_bytes(), &bytes);
    }

    #[test_log::test]
    fn test_node_id_display() {
        let bytes = [
            0xAB, 0xCD, 0xEF, 0x01, 0x23, 0x45, 0x67, 0x89, 0x0A, 0xBC, 0xDE, 0xF0, 0x12, 0x34,
            0x56, 0x78, 0x9A, 0xBC, 0xDE, 0xF0, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88,
            0x99, 0xAA, 0xBB, 0xCC,
        ];
        let id = SimulatorNodeId::from_bytes(bytes);
        let display = format!("{id}");
        assert_eq!(display.len(), 64); // 32 bytes = 64 hex chars
        assert!(display.starts_with("abcdef"));
    }

    #[test_log::test]
    fn test_node_id_generate_creates_unique_ids() {
        let id1 = SimulatorNodeId::generate();
        let id2 = SimulatorNodeId::generate();
        // Random IDs should be different (extremely high probability)
        assert_ne!(id1, id2);
    }

    #[test_log::test]
    fn test_node_id_ordering() {
        let id1 = SimulatorNodeId::from_bytes([1u8; 32]);
        let id2 = SimulatorNodeId::from_bytes([2u8; 32]);
        assert!(id1 < id2);
        assert!(id2 > id1);
    }

    // === NetworkGraph Tests ===

    #[test_log::test]
    fn test_network_graph_new() {
        let graph = NetworkGraph::new();
        assert!(graph.nodes.is_empty());
        assert!(graph.links.is_empty());
    }

    #[test_log::test]
    fn test_network_graph_add_node() {
        let mut graph = NetworkGraph::new();
        let node_id = test_node_id("alice");

        graph.add_node(node_id.clone());

        assert!(graph.nodes.contains_key(&node_id));
        let node = graph.get_node(&node_id).unwrap();
        assert_eq!(node.id, node_id);
        assert!(node.is_online);
        assert!(node.registered_names.is_empty());
        assert!(node.message_queues.is_empty());
    }

    #[test_log::test]
    fn test_network_graph_add_node_idempotent() {
        let mut graph = NetworkGraph::new();
        let node_id = test_node_id("alice");

        graph.add_node(node_id.clone());
        graph.add_node(node_id); // Add again

        // Should still only have one node
        assert_eq!(graph.nodes.len(), 1);
    }

    #[test_log::test]
    fn test_network_graph_connect_nodes() {
        let mut graph = NetworkGraph::new();
        let alice = test_node_id("alice");
        let bob = test_node_id("bob");

        let link = LinkInfo {
            latency: Duration::from_millis(10),
            packet_loss: 0.01,
            bandwidth_limit: Some(1_000_000),
            is_active: true,
        };

        graph.connect_nodes(alice.clone(), bob.clone(), link);

        // Should create bidirectional links
        assert!(graph.links.contains_key(&(alice.clone(), bob.clone())));
        assert!(graph.links.contains_key(&(bob.clone(), alice.clone())));

        let forward_link = &graph.links[&(alice, bob)];
        assert_eq!(forward_link.latency, Duration::from_millis(10));
        assert!((forward_link.packet_loss - 0.01).abs() < f64::EPSILON);
        assert!(forward_link.is_active);
    }

    #[test_log::test]
    fn test_network_graph_find_path_same_node() {
        let graph = NetworkGraph::new();
        let alice = test_node_id("alice");

        let path = graph.find_path(alice.clone(), alice.clone());

        assert_eq!(path, Some(vec![alice]));
    }

    #[test_log::test]
    fn test_network_graph_find_path_direct() {
        let mut graph = NetworkGraph::new();
        let alice = test_node_id("alice");
        let bob = test_node_id("bob");

        graph.add_node(alice.clone());
        graph.add_node(bob.clone());
        graph.connect_nodes(
            alice.clone(),
            bob.clone(),
            LinkInfo {
                latency: Duration::from_millis(10),
                packet_loss: 0.0,
                bandwidth_limit: None,
                is_active: true,
            },
        );

        let path = graph.find_path(alice.clone(), bob.clone());

        assert_eq!(path, Some(vec![alice, bob]));
    }

    #[test_log::test]
    fn test_network_graph_find_path_multi_hop() {
        let mut graph = NetworkGraph::new();
        let alice = test_node_id("alice");
        let bob = test_node_id("bob");
        let charlie = test_node_id("charlie");

        graph.add_node(alice.clone());
        graph.add_node(bob.clone());
        graph.add_node(charlie.clone());

        let link = LinkInfo {
            latency: Duration::from_millis(10),
            packet_loss: 0.0,
            bandwidth_limit: None,
            is_active: true,
        };

        // Create path: alice -> bob -> charlie
        graph.connect_nodes(alice.clone(), bob.clone(), link.clone());
        graph.connect_nodes(bob.clone(), charlie.clone(), link);

        let path = graph.find_path(alice.clone(), charlie.clone());

        assert_eq!(path, Some(vec![alice, bob, charlie]));
    }

    #[test_log::test]
    fn test_network_graph_find_path_no_route() {
        let mut graph = NetworkGraph::new();
        let alice = test_node_id("alice");
        let bob = test_node_id("bob");

        // Add nodes but don't connect them
        graph.add_node(alice.clone());
        graph.add_node(bob.clone());

        let path = graph.find_path(alice, bob);

        assert_eq!(path, None);
    }

    #[test_log::test]
    fn test_network_graph_find_path_inactive_link() {
        let mut graph = NetworkGraph::new();
        let alice = test_node_id("alice");
        let bob = test_node_id("bob");

        graph.add_node(alice.clone());
        graph.add_node(bob.clone());

        // Create inactive link
        graph.connect_nodes(
            alice.clone(),
            bob.clone(),
            LinkInfo {
                latency: Duration::from_millis(10),
                packet_loss: 0.0,
                bandwidth_limit: None,
                is_active: false,
            },
        );

        let path = graph.find_path(alice, bob);

        // Should not find path through inactive link
        assert_eq!(path, None);
    }

    #[test_log::test]
    fn test_network_graph_add_partition() {
        let mut graph = NetworkGraph::new();
        let alice = test_node_id("alice");
        let bob = test_node_id("bob");
        let charlie = test_node_id("charlie");
        let dave = test_node_id("dave");

        graph.add_node(alice.clone());
        graph.add_node(bob.clone());
        graph.add_node(charlie.clone());
        graph.add_node(dave.clone());

        let link = LinkInfo {
            latency: Duration::from_millis(10),
            packet_loss: 0.0,
            bandwidth_limit: None,
            is_active: true,
        };

        // Connect all nodes
        graph.connect_nodes(alice.clone(), charlie.clone(), link.clone());
        graph.connect_nodes(alice.clone(), dave.clone(), link.clone());
        graph.connect_nodes(bob.clone(), charlie.clone(), link.clone());
        graph.connect_nodes(bob.clone(), dave.clone(), link);

        // Partition: {alice, bob} vs {charlie, dave}
        let group_a = vec![alice.clone(), bob.clone()];
        let group_b = vec![charlie.clone(), dave.clone()];
        graph.add_partition(&group_a, &group_b);

        // Verify no links between groups
        assert!(!graph.links.contains_key(&(alice.clone(), charlie.clone())));
        assert!(!graph.links.contains_key(&(alice.clone(), dave.clone())));
        assert!(!graph.links.contains_key(&(bob.clone(), charlie.clone())));
        assert!(!graph.links.contains_key(&(bob, dave)));

        // Verify no path exists
        assert_eq!(graph.find_path(alice, charlie), None);
    }

    #[test_log::test]
    fn test_network_graph_heal_partition() {
        let mut graph = NetworkGraph::new();
        let alice = test_node_id("alice");
        let bob = test_node_id("bob");

        graph.add_node(alice.clone());
        graph.add_node(bob.clone());

        // Create partition (no links)
        let group_a = vec![alice.clone()];
        let group_b = vec![bob.clone()];

        // Heal partition
        graph.heal_partition(&group_a, &group_b);

        // Should now have bidirectional links
        assert!(graph.links.contains_key(&(alice.clone(), bob.clone())));
        assert!(graph.links.contains_key(&(bob.clone(), alice.clone())));

        // Should have path
        assert!(graph.find_path(alice, bob).is_some());
    }

    #[test_log::test]
    fn test_network_graph_heal_partition_multiple_nodes() {
        // Test heal_partition with multiple nodes in each group
        let mut graph = NetworkGraph::new();
        let alice = test_node_id("heal_alice");
        let bob = test_node_id("heal_bob");
        let charlie = test_node_id("heal_charlie");
        let dave = test_node_id("heal_dave");

        graph.add_node(alice.clone());
        graph.add_node(bob.clone());
        graph.add_node(charlie.clone());
        graph.add_node(dave.clone());

        // Initially partitioned: {alice, bob} vs {charlie, dave}
        // No links between groups
        let group_a = vec![alice.clone(), bob.clone()];
        let group_b = vec![charlie.clone(), dave.clone()];

        // Heal partition
        graph.heal_partition(&group_a, &group_b);

        // Should create links from each node in group_a to each node in group_b
        // Total 4 links (bidirectional, so 8 entries in the links map)
        assert!(graph.links.contains_key(&(alice.clone(), charlie.clone())));
        assert!(graph.links.contains_key(&(alice.clone(), dave.clone())));
        assert!(graph.links.contains_key(&(bob.clone(), charlie.clone())));
        assert!(graph.links.contains_key(&(bob.clone(), dave.clone())));

        // Reverse links should also exist
        assert!(graph.links.contains_key(&(charlie.clone(), alice.clone())));
        assert!(graph.links.contains_key(&(dave.clone(), alice.clone())));
        assert!(graph.links.contains_key(&(charlie.clone(), bob.clone())));
        assert!(graph.links.contains_key(&(dave.clone(), bob.clone())));

        // All cross-group paths should now exist
        assert!(graph.find_path(alice.clone(), charlie.clone()).is_some());
        assert!(graph.find_path(alice, dave.clone()).is_some());
        assert!(graph.find_path(bob.clone(), charlie).is_some());
        assert!(graph.find_path(bob, dave).is_some());
    }

    #[test_log::test]
    fn test_network_graph_get_node_mut() {
        let mut graph = NetworkGraph::new();
        let alice = test_node_id("alice");

        graph.add_node(alice.clone());

        let node = graph.get_node_mut(&alice).unwrap();
        node.registered_names
            .insert("test".to_string(), "value".to_string());

        let node = graph.get_node(&alice).unwrap();
        assert!(node.registered_names.contains_key("test"));
    }

    #[test_log::test]
    fn test_network_graph_get_node_nonexistent() {
        let graph = NetworkGraph::new();
        let alice = test_node_id("alice");

        assert!(graph.get_node(&alice).is_none());
    }

    #[test_log::test]
    fn test_network_graph_get_node_mut_nonexistent() {
        let mut graph = NetworkGraph::new();
        let alice = test_node_id("alice");

        assert!(graph.get_node_mut(&alice).is_none());
    }

    // === SimulatorP2P Tests ===

    #[test_log::test]
    fn test_simulator_p2p_new() {
        let sim = SimulatorP2P::new();
        let id = sim.local_node_id();
        assert_eq!(id.as_bytes().len(), 32);
    }

    #[test_log::test]
    fn test_simulator_p2p_with_seed() {
        let sim1 = SimulatorP2P::with_seed("alice");
        let sim2 = SimulatorP2P::with_seed("alice");
        assert_eq!(sim1.local_node_id(), sim2.local_node_id());
    }

    #[test_log::test(switchy_async::test)]
    async fn test_simulator_p2p_connect_creates_queues() {
        let alice = SimulatorP2P::with_seed("alice");
        let bob_id = test_node_id("bob");

        // Setup network graph with link
        {
            let mut graph = alice.network_graph.write().await;
            graph.add_node(alice.local_node_id().clone());
            graph.add_node(bob_id.clone());
            graph.connect_nodes(
                alice.local_node_id().clone(),
                bob_id.clone(),
                LinkInfo {
                    latency: Duration::from_millis(10),
                    packet_loss: 0.0,
                    bandwidth_limit: None,
                    is_active: true,
                },
            );
        }

        let conn = alice.connect(bob_id.clone()).await.unwrap();

        assert!(conn.is_connected());
        assert_eq!(conn.remote_node_id(), &bob_id);

        // Verify queues were created
        let alice_node = alice
            .network_graph
            .read()
            .await
            .get_node(alice.local_node_id())
            .unwrap()
            .clone();
        assert!(alice_node.message_queues.contains_key(&bob_id));
    }

    #[test_log::test(switchy_async::test)]
    async fn test_simulator_p2p_connect_no_route() {
        let alice = SimulatorP2P::with_seed("alice");
        let bob_id = test_node_id("bob");

        // Add bob to graph but don't create link
        {
            let mut graph = alice.network_graph.write().await;
            graph.add_node(alice.local_node_id().clone());
            graph.add_node(bob_id.clone());
        }

        let result = alice.connect(bob_id).await;

        assert!(result.is_err());
        assert_eq!(result.unwrap_err(), "No route to destination");
    }

    #[test_log::test(switchy_async::test)]
    async fn test_simulator_p2p_register_peer() {
        let sim = SimulatorP2P::with_seed("alice");
        let bob_id = test_node_id("bob");

        let result = sim.register_peer("bob", bob_id.clone()).await;

        assert!(result.is_ok());

        // Verify registration by checking the graph
        let node = sim
            .network_graph
            .read()
            .await
            .get_node(&bob_id)
            .unwrap()
            .clone();
        assert!(node.registered_names.contains_key("bob"));
    }

    // === SimulatorConnection Tests ===
    // Note: Tests involving send/recv with latency simulation are omitted
    // as they require proper time mocking which isn't fully implemented yet

    #[test_log::test(switchy_async::test)]
    async fn test_simulator_connection_recv_empty_queue() {
        let (alice, _alice_id, bob_id) = SimulatorP2P::test_setup();

        let mut conn = alice.connect(bob_id).await.unwrap();

        let result = conn.recv().await;

        assert!(result.is_err());
        assert_eq!(result.unwrap_err(), "No message available");
    }

    #[test_log::test(switchy_async::test)]
    async fn test_simulator_connection_send_after_close() {
        let (alice, _alice_id, bob_id) = SimulatorP2P::test_setup();

        let mut conn = alice.connect(bob_id).await.unwrap();

        conn.close().unwrap();

        let result = conn.send(b"test").await;

        assert!(result.is_err());
        assert_eq!(result.unwrap_err(), "Connection closed");
    }

    #[test_log::test(switchy_async::test)]
    async fn test_simulator_connection_message_too_large() {
        let (alice, _alice_id, bob_id) = SimulatorP2P::test_setup();

        let mut conn = alice.connect(bob_id).await.unwrap();

        // Create message larger than max size
        let max_size = max_message_size();
        let large_data = vec![0u8; max_size + 1];

        let result = conn.send(&large_data).await;

        assert!(result.is_err());
        assert!(result.unwrap_err().contains("Message too large"));
    }

    #[test_log::test(switchy_async::test)]
    async fn test_simulator_connection_close_idempotent() {
        let (alice, _alice_id, bob_id) = SimulatorP2P::test_setup();

        let mut conn = alice.connect(bob_id).await.unwrap();

        assert!(conn.is_connected());

        conn.close().unwrap();
        assert!(!conn.is_connected());

        // Close again - should succeed
        conn.close().unwrap();
        assert!(!conn.is_connected());
    }

    #[test_log::test(switchy_async::test)]
    async fn test_simulator_reconnect_after_close() {
        let (alice, _alice_id, bob_id) = SimulatorP2P::test_setup();

        // First connection
        let mut conn1 = alice.connect(bob_id.clone()).await.unwrap();
        assert!(conn1.is_connected());
        assert_eq!(conn1.remote_node_id(), &bob_id);

        // Close the first connection
        conn1.close().unwrap();
        assert!(!conn1.is_connected());

        // Re-connect to the same peer
        let conn2 = alice.connect(bob_id.clone()).await.unwrap();
        assert!(conn2.is_connected());
        assert_eq!(conn2.remote_node_id(), &bob_id);

        // First connection should still be closed
        assert!(!conn1.is_connected());
    }

    #[test_log::test]
    fn test_simulator_connection_calculate_path_latency() {
        let mut graph = NetworkGraph::new();
        let alice = test_node_id("alice");
        let bob = test_node_id("bob");
        let charlie = test_node_id("charlie");

        graph.add_node(alice.clone());
        graph.add_node(bob.clone());
        graph.add_node(charlie.clone());

        graph.connect_nodes(
            alice.clone(),
            bob.clone(),
            LinkInfo {
                latency: Duration::from_millis(10),
                packet_loss: 0.0,
                bandwidth_limit: None,
                is_active: true,
            },
        );
        graph.connect_nodes(
            bob.clone(),
            charlie.clone(),
            LinkInfo {
                latency: Duration::from_millis(20),
                packet_loss: 0.0,
                bandwidth_limit: None,
                is_active: true,
            },
        );

        let path = vec![alice, bob, charlie];
        let latency = SimulatorConnection::calculate_path_latency(&graph, &path);

        assert_eq!(latency, Duration::from_millis(30));
    }

    #[test_log::test]
    fn test_simulator_connection_calculate_path_latency_empty_path() {
        let graph = NetworkGraph::new();
        let path = vec![];

        let latency = SimulatorConnection::calculate_path_latency(&graph, &path);

        assert_eq!(latency, Duration::from_millis(0));
    }

    #[test_log::test]
    fn test_simulator_connection_calculate_path_latency_single_node() {
        let graph = NetworkGraph::new();
        let alice = test_node_id("alice");
        let path = vec![alice];

        let latency = SimulatorConnection::calculate_path_latency(&graph, &path);

        assert_eq!(latency, Duration::from_millis(0));
    }

    // === P2PNodeId Trait Implementation Tests ===

    #[test_log::test]
    fn test_p2p_node_id_trait_from_bytes() {
        use crate::traits::P2PNodeId;

        let bytes = [123u8; 32];
        let id = <SimulatorNodeId as P2PNodeId>::from_bytes(&bytes).unwrap();

        assert_eq!(id.as_bytes(), &bytes);
    }

    #[test_log::test]
    fn test_p2p_node_id_trait_as_bytes() {
        use crate::traits::P2PNodeId;

        let bytes = [42u8; 32];
        let id = <SimulatorNodeId as P2PNodeId>::from_bytes(&bytes).unwrap();

        assert_eq!(id.as_bytes(), &bytes);
    }

    #[test_log::test]
    fn test_p2p_node_id_trait_fmt_short() {
        use crate::traits::P2PNodeId;

        let bytes = [0xAB; 32];
        let id = <SimulatorNodeId as P2PNodeId>::from_bytes(&bytes).unwrap();

        let short = id.fmt_short();
        assert_eq!(short.len(), 10);
        assert_eq!(short, "ababababab");
    }

    // === Network Partition and Healing Tests ===

    #[test_log::test(switchy_async::test)]
    async fn test_network_partition_blocks_path_finding() {
        let alice = SimulatorP2P::with_seed("alice_partition_path");
        let bob_id = test_node_id("bob_partition_path");
        let charlie_id = test_node_id("charlie_partition_path");
        let alice_id = alice.local_node_id().clone();
        let shared_graph = alice.network_graph.clone();

        // Setup: alice -> bob -> charlie
        {
            let mut graph = shared_graph.write().await;
            graph.add_node(alice_id.clone());
            graph.add_node(bob_id.clone());
            graph.add_node(charlie_id.clone());

            let link = LinkInfo {
                latency: Duration::from_millis(1),
                packet_loss: 0.0,
                bandwidth_limit: None,
                is_active: true,
            };

            graph.connect_nodes(alice_id.clone(), bob_id.clone(), link.clone());
            graph.connect_nodes(bob_id.clone(), charlie_id.clone(), link);
        }

        // Verify path exists initially
        assert!(
            shared_graph
                .read()
                .await
                .find_path(alice_id.clone(), charlie_id.clone())
                .is_some()
        );

        // Create partition between bob and charlie
        {
            let mut graph = shared_graph.write().await;
            graph.add_partition(
                &[alice_id.clone(), bob_id.clone()],
                std::slice::from_ref(&charlie_id),
            );
        }

        // Path should no longer exist
        assert!(
            shared_graph
                .read()
                .await
                .find_path(alice_id.clone(), charlie_id.clone())
                .is_none()
        );

        // Heal the partition
        {
            let mut graph = shared_graph.write().await;
            graph.heal_partition(&[bob_id], std::slice::from_ref(&charlie_id));
        }

        // Path should exist again
        assert!(
            shared_graph
                .read()
                .await
                .find_path(alice_id, charlie_id)
                .is_some()
        );
    }

    #[test_log::test(switchy_async::test)]
    async fn test_simulator_p2p_register_peer_new_node() {
        let sim = SimulatorP2P::with_seed("register_new");
        let new_id = test_node_id("new_peer");

        // Register a peer that doesn't exist in the graph yet
        sim.register_peer("new_peer", new_id.clone()).await.unwrap();

        // The node should now exist in the graph
        let graph = sim.network_graph.read().await;
        assert!(graph.get_node(&new_id).is_some());
        drop(graph);
    }

    #[test_log::test(switchy_async::test)]
    async fn test_simulator_p2p_connect_adds_nodes_to_graph() {
        let alice = SimulatorP2P::with_seed("alice_auto_add");
        let bob_id = test_node_id("bob_auto_add");

        // Initially, neither node should be in the graph (graph is empty)
        assert!(alice.network_graph.read().await.nodes.is_empty());

        // Setup connection (this should auto-add both nodes)
        {
            let mut graph = alice.network_graph.write().await;
            graph.connect_nodes(
                alice.local_node_id().clone(),
                bob_id.clone(),
                LinkInfo {
                    latency: Duration::from_millis(1),
                    packet_loss: 0.0,
                    bandwidth_limit: None,
                    is_active: true,
                },
            );
        }

        // Connect should auto-add both nodes to the graph
        let _conn = alice.connect(bob_id.clone()).await.unwrap();

        // Verify both nodes are in the graph
        let graph = alice.network_graph.read().await;
        assert!(graph.get_node(alice.local_node_id()).is_some());
        assert!(graph.get_node(&bob_id).is_some());
        drop(graph);
    }

    // === Edge Case Tests ===

    #[test_log::test]
    fn test_network_graph_find_path_shortest() {
        // Test that find_path returns shortest path (BFS behavior)
        let mut graph = NetworkGraph::new();
        let a = test_node_id("node_a");
        let b = test_node_id("node_b");
        let c = test_node_id("node_c");
        let d = test_node_id("node_d");

        graph.add_node(a.clone());
        graph.add_node(b.clone());
        graph.add_node(c.clone());
        graph.add_node(d.clone());

        let link = LinkInfo {
            latency: Duration::from_millis(10),
            packet_loss: 0.0,
            bandwidth_limit: None,
            is_active: true,
        };

        // Create two paths: a -> b -> c -> d (long) and a -> d (short)
        graph.connect_nodes(a.clone(), b.clone(), link.clone());
        graph.connect_nodes(b, c.clone(), link.clone());
        graph.connect_nodes(c, d.clone(), link.clone());
        graph.connect_nodes(a.clone(), d.clone(), link); // Direct link

        let path = graph.find_path(a.clone(), d.clone()).unwrap();

        // BFS should find the shortest path (a -> d)
        assert_eq!(path.len(), 2);
        assert_eq!(path[0], a);
        assert_eq!(path[1], d);
    }

    #[test_log::test]
    fn test_network_graph_find_path_cyclic_graph() {
        // Test that BFS correctly handles graphs with cycles without infinite loops
        let mut graph = NetworkGraph::new();
        let a = test_node_id("cycle_a");
        let b = test_node_id("cycle_b");
        let c = test_node_id("cycle_c");
        let d = test_node_id("cycle_d");

        graph.add_node(a.clone());
        graph.add_node(b.clone());
        graph.add_node(c.clone());
        graph.add_node(d.clone());

        let link = LinkInfo {
            latency: Duration::from_millis(10),
            packet_loss: 0.0,
            bandwidth_limit: None,
            is_active: true,
        };

        // Create a graph with a cycle: a -> b -> c -> a (cycle) and c -> d
        // Note: connect_nodes creates bidirectional links, so c->a also means a->c
        graph.connect_nodes(a.clone(), b.clone(), link.clone());
        graph.connect_nodes(b, c.clone(), link.clone());
        graph.connect_nodes(c.clone(), a.clone(), link.clone()); // Creates cycle (but also a->c link)
        graph.connect_nodes(c, d.clone(), link); // Path to destination

        // Path should still be found despite cycle - BFS finds shortest path
        // Due to bidirectional links, a->c is direct, so shortest path is a -> c -> d (length 3)
        let path = graph.find_path(a.clone(), d.clone()).unwrap();

        // BFS should find shortest path through the cycle graph
        assert_eq!(path.len(), 3, "BFS should find shortest path a -> c -> d");
        assert_eq!(path[0], a);
        assert_eq!(path[2], d);

        // Verify path doesn't contain duplicates (no infinite loop in BFS)
        let unique_nodes: std::collections::BTreeSet<_> = path.iter().collect();
        assert_eq!(
            unique_nodes.len(),
            path.len(),
            "Path should not contain duplicate nodes"
        );
    }

    #[test_log::test]
    fn test_simulator_connection_calculate_path_latency_missing_links() {
        // Test latency calculation when some links in path are missing from graph
        let mut graph = NetworkGraph::new();
        let a = test_node_id("lat_a");
        let b = test_node_id("lat_b");
        let c = test_node_id("lat_c");

        graph.add_node(a.clone());
        graph.add_node(b.clone());
        graph.add_node(c.clone());

        // Only add link a -> b, not b -> c
        graph.connect_nodes(
            a.clone(),
            b.clone(),
            LinkInfo {
                latency: Duration::from_millis(50),
                packet_loss: 0.0,
                bandwidth_limit: None,
                is_active: true,
            },
        );

        let path = vec![a, b, c];
        let latency = SimulatorConnection::calculate_path_latency(&graph, &path);

        // Should only count the latency of existing links (a -> b)
        assert_eq!(latency, Duration::from_millis(50));
    }

    // === Discovery Tests ===
    // Note: These tests use real_time because discover() has a simulated delay

    #[test_log::test(switchy_async::test(real_time))]
    async fn test_discover_returns_registered_node_id() {
        let sim = SimulatorP2P::with_seed("discover_test");
        let peer_id = test_node_id("discoverable_peer");

        // Register a peer with a name
        sim.register_peer("my-peer", peer_id.clone()).await.unwrap();

        // Discover should return the correct node ID
        let discovered_id = sim.discover("my-peer").await.unwrap();
        assert_eq!(discovered_id, peer_id);
    }

    #[test_log::test(switchy_async::test(real_time))]
    async fn test_discover_name_not_found_returns_error() {
        let sim = SimulatorP2P::with_seed("discover_notfound_test");

        // Try to discover a name that was never registered
        let result = sim.discover("nonexistent-peer").await;

        assert!(result.is_err());
        let err = result.unwrap_err();
        assert!(
            err.contains("not found"),
            "Expected 'not found' error, got: {err}"
        );
    }

    #[test_log::test(switchy_async::test(real_time))]
    async fn test_discover_multiple_registered_names() {
        let sim = SimulatorP2P::with_seed("discover_multi_test");
        let peer1_id = test_node_id("peer1");
        let peer2_id = test_node_id("peer2");

        // Register multiple peers
        sim.register_peer("first-peer", peer1_id.clone())
            .await
            .unwrap();
        sim.register_peer("second-peer", peer2_id.clone())
            .await
            .unwrap();

        // Both should be discoverable
        let discovered1 = sim.discover("first-peer").await.unwrap();
        let discovered2 = sim.discover("second-peer").await.unwrap();

        assert_eq!(discovered1, peer1_id);
        assert_eq!(discovered2, peer2_id);
        assert_ne!(discovered1, discovered2);
    }

    // === connect_by_name Tests ===
    // Note: These tests use real_time because connect_by_name calls discover()

    #[test_log::test(switchy_async::test(real_time))]
    async fn test_connect_by_name_success() {
        let alice = SimulatorP2P::with_seed("alice_cbn");
        let bob_id = test_node_id("bob_cbn");

        // Register bob and set up the network link
        alice.register_peer("bob", bob_id.clone()).await.unwrap();
        {
            let mut graph = alice.network_graph.write().await;
            graph.add_node(alice.local_node_id().clone());
            graph.connect_nodes(
                alice.local_node_id().clone(),
                bob_id.clone(),
                LinkInfo {
                    latency: Duration::from_millis(1),
                    packet_loss: 0.0,
                    bandwidth_limit: None,
                    is_active: true,
                },
            );
        }

        // Connect by name should work
        let conn = alice.connect_by_name("bob").await.unwrap();

        assert!(conn.is_connected());
        assert_eq!(conn.remote_node_id(), &bob_id);
    }

    #[test_log::test(switchy_async::test(real_time))]
    async fn test_connect_by_name_discovery_fails() {
        let alice = SimulatorP2P::with_seed("alice_cbn_fail");

        // Don't register any peer, connect_by_name should fail during discovery
        let result = alice.connect_by_name("unknown-peer").await;

        assert!(result.is_err());
        let err = result.unwrap_err();
        assert!(
            err.contains("not found"),
            "Expected discovery error, got: {err}"
        );
    }

    #[test_log::test(switchy_async::test(real_time))]
    async fn test_connect_by_name_connection_fails_no_route() {
        let alice = SimulatorP2P::with_seed("alice_cbn_noroute");
        let bob_id = test_node_id("bob_cbn_noroute");

        // Register bob but don't create a network link
        alice
            .register_peer("bob-noroute", bob_id.clone())
            .await
            .unwrap();
        {
            let mut graph = alice.network_graph.write().await;
            graph.add_node(alice.local_node_id().clone());
            // bob is added by register_peer but no link exists
        }

        // Discovery should succeed, but connection should fail
        let result = alice.connect_by_name("bob-noroute").await;

        assert!(result.is_err());
        let err = result.unwrap_err();
        assert!(
            err.contains("No route"),
            "Expected 'No route' error, got: {err}"
        );
    }

    // === Packet Loss Edge Case Tests ===

    #[test_log::test]
    fn test_packet_lost_zero_packet_loss_never_drops() {
        // With 0% packet loss, packets should never be dropped
        let mut graph = NetworkGraph::new();
        let a = test_node_id("pl_zero_a");
        let b = test_node_id("pl_zero_b");

        graph.add_node(a.clone());
        graph.add_node(b.clone());
        graph.connect_nodes(
            a.clone(),
            b.clone(),
            LinkInfo {
                latency: Duration::from_millis(1),
                packet_loss: 0.0, // 0% loss
                bandwidth_limit: None,
                is_active: true,
            },
        );

        let path = vec![a, b];

        // Run many times to verify no packet loss
        for _ in 0..100 {
            assert!(
                !SimulatorConnection::packet_lost(&graph, &path),
                "Packet should never be lost with 0% packet loss"
            );
        }
    }

    #[test_log::test]
    fn test_packet_lost_empty_path_never_drops() {
        let graph = NetworkGraph::new();
        let path: Vec<SimulatorNodeId> = vec![];

        // Empty path has no links to lose packets on
        assert!(!SimulatorConnection::packet_lost(&graph, &path));
    }

    #[test_log::test]
    fn test_packet_lost_single_node_path_never_drops() {
        let graph = NetworkGraph::new();
        let a = test_node_id("pl_single");
        let path = vec![a];

        // Single node path has no links to lose packets on
        assert!(!SimulatorConnection::packet_lost(&graph, &path));
    }

    // === Send After Network Partition Test ===

    #[test_log::test(switchy_async::test)]
    async fn test_send_fails_after_network_partition() {
        let alice = SimulatorP2P::with_seed("alice_partition_send");
        let bob_id = test_node_id("bob_partition_send");
        let alice_id = alice.local_node_id().clone();

        // Setup network with link (no latency to avoid time issues in simulator mode)
        {
            let mut graph = alice.network_graph.write().await;
            graph.add_node(alice_id.clone());
            graph.add_node(bob_id.clone());
            graph.connect_nodes(
                alice_id.clone(),
                bob_id.clone(),
                LinkInfo {
                    latency: Duration::from_millis(0),
                    packet_loss: 0.0,
                    bandwidth_limit: None,
                    is_active: true,
                },
            );
        }

        // Establish connection (should succeed)
        let mut conn = alice.connect(bob_id.clone()).await.unwrap();
        assert!(conn.is_connected());

        // Now create a network partition that removes the route
        {
            let mut graph = alice.network_graph.write().await;
            graph.add_partition(&[alice_id], &[bob_id]);
        }

        // Send should now fail because route no longer exists
        let result = conn.send(b"hello after partition").await;
        assert!(result.is_err());
        let err = result.unwrap_err();
        assert!(
            err.contains("No route"),
            "Expected 'No route' error after partition, got: {err}"
        );
    }

    #[test_log::test(switchy_async::test)]
    async fn test_message_delivery_fifo_ordering() {
        // Test that messages are delivered in FIFO order
        let alice = SimulatorP2P::with_seed("alice_fifo");
        let bob_id = test_node_id("bob_fifo");
        let alice_id = alice.local_node_id().clone();

        // Setup network (no latency to avoid time issues in simulator mode)
        {
            let mut graph = alice.network_graph.write().await;
            graph.add_node(alice_id.clone());
            graph.add_node(bob_id.clone());
            graph.connect_nodes(
                alice_id.clone(),
                bob_id.clone(),
                LinkInfo {
                    latency: Duration::from_millis(0),
                    packet_loss: 0.0,
                    bandwidth_limit: None,
                    is_active: true,
                },
            );
        }

        // Connect from alice to bob
        let mut conn = alice.connect(bob_id.clone()).await.unwrap();

        // Send multiple messages
        conn.send(b"message1").await.unwrap();
        conn.send(b"message2").await.unwrap();
        conn.send(b"message3").await.unwrap();

        // Create bob's view of the connection to receive
        let bob = SimulatorP2P {
            node_id: bob_id.clone(),
            network_graph: alice.network_graph.clone(),
            connections: Arc::new(RwLock::new(BTreeMap::new())),
        };
        let mut bob_conn = bob.connect(alice_id).await.unwrap();

        // Messages should be received in FIFO order
        let msg1 = bob_conn.recv().await.unwrap();
        let msg2 = bob_conn.recv().await.unwrap();
        let msg3 = bob_conn.recv().await.unwrap();

        assert_eq!(msg1, b"message1");
        assert_eq!(msg2, b"message2");
        assert_eq!(msg3, b"message3");
    }
}