peat-btle 0.4.0

Bluetooth Low Energy mesh transport for Peat Protocol
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
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
// UniFFI bindings for peat-btle
//
// This module provides UniFFI-compatible wrappers around the core peat-btle types.
// It generates Kotlin and Swift bindings automatically.
//
// Note: uniffi::setup_scaffolding!() is called in lib.rs (must be at crate root)

#![allow(missing_docs)]

use std::sync::Arc;

// Initialize Android logger on first use
#[cfg(target_os = "android")]
static ANDROID_LOGGER_INIT: std::sync::Once = std::sync::Once::new();

#[cfg(target_os = "android")]
fn ensure_android_logger() {
    ANDROID_LOGGER_INIT.call_once(|| {
        android_logger::init_once(
            android_logger::Config::default()
                .with_max_level(log::LevelFilter::Info)
                .with_tag("PeatFFI"),
        );
    });
}

use crate::observer::DisconnectReason as ObserverDisconnectReason;
use crate::peat_mesh::{self, DataReceivedResult as InternalDataReceivedResult};
use crate::peer::{
    ConnectionState as InternalConnectionState,
    FullStateCountSummary as InternalFullStateCountSummary, IndirectPeer as InternalIndirectPeer,
    PeatPeer as InternalPeatPeer, PeerConnectionState as InternalPeerConnectionState,
    StateCountSummary as InternalStateCountSummary,
};
use crate::platform::DisconnectReason as PlatformDisconnectReason;
use crate::security::{
    DeviceIdentity as InternalDeviceIdentity, IdentityAttestation as InternalIdentityAttestation,
    MembershipPolicy, MeshGenesis as InternalMeshGenesis, RegistryResult,
};
use crate::sync::crdt::{EventType as InternalEventType, PeripheralType as InternalPeripheralType};
use crate::NodeId;

// ============================================================================
// Enums
// ============================================================================

#[derive(Debug, Clone, Copy, PartialEq, Eq, uniffi::Enum)]
pub enum PeripheralType {
    Unknown,
    SoldierSensor,
    FixedSensor,
    Relay,
}

impl From<InternalPeripheralType> for PeripheralType {
    fn from(pt: InternalPeripheralType) -> Self {
        match pt {
            InternalPeripheralType::Unknown => PeripheralType::Unknown,
            InternalPeripheralType::SoldierSensor => PeripheralType::SoldierSensor,
            InternalPeripheralType::FixedSensor => PeripheralType::FixedSensor,
            InternalPeripheralType::Relay => PeripheralType::Relay,
        }
    }
}

impl From<PeripheralType> for InternalPeripheralType {
    fn from(pt: PeripheralType) -> Self {
        match pt {
            PeripheralType::Unknown => InternalPeripheralType::Unknown,
            PeripheralType::SoldierSensor => InternalPeripheralType::SoldierSensor,
            PeripheralType::FixedSensor => InternalPeripheralType::FixedSensor,
            PeripheralType::Relay => InternalPeripheralType::Relay,
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, uniffi::Enum)]
pub enum EventType {
    None,
    Ping,
    NeedAssist,
    Emergency,
    Moving,
    InPosition,
    Ack,
}

impl From<InternalEventType> for EventType {
    fn from(et: InternalEventType) -> Self {
        match et {
            InternalEventType::None => EventType::None,
            InternalEventType::Ping => EventType::Ping,
            InternalEventType::NeedAssist => EventType::NeedAssist,
            InternalEventType::Emergency => EventType::Emergency,
            InternalEventType::Moving => EventType::Moving,
            InternalEventType::InPosition => EventType::InPosition,
            InternalEventType::Ack => EventType::Ack,
        }
    }
}

impl From<EventType> for InternalEventType {
    fn from(et: EventType) -> Self {
        match et {
            EventType::None => InternalEventType::None,
            EventType::Ping => InternalEventType::Ping,
            EventType::NeedAssist => InternalEventType::NeedAssist,
            EventType::Emergency => InternalEventType::Emergency,
            EventType::Moving => InternalEventType::Moving,
            EventType::InPosition => InternalEventType::InPosition,
            EventType::Ack => InternalEventType::Ack,
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, uniffi::Enum)]
pub enum DisconnectReason {
    LocalRequest,
    RemoteRequest,
    Timeout,
    LinkLoss,
    ConnectionFailed,
    Unknown,
}

impl From<DisconnectReason> for ObserverDisconnectReason {
    fn from(r: DisconnectReason) -> Self {
        match r {
            DisconnectReason::LocalRequest => ObserverDisconnectReason::LocalRequest,
            DisconnectReason::RemoteRequest => ObserverDisconnectReason::RemoteRequest,
            DisconnectReason::Timeout => ObserverDisconnectReason::Timeout,
            DisconnectReason::LinkLoss => ObserverDisconnectReason::LinkLoss,
            DisconnectReason::ConnectionFailed => ObserverDisconnectReason::ConnectionFailed,
            DisconnectReason::Unknown => ObserverDisconnectReason::Unknown,
        }
    }
}

impl From<ObserverDisconnectReason> for DisconnectReason {
    fn from(r: ObserverDisconnectReason) -> Self {
        match r {
            ObserverDisconnectReason::LocalRequest => DisconnectReason::LocalRequest,
            ObserverDisconnectReason::RemoteRequest => DisconnectReason::RemoteRequest,
            ObserverDisconnectReason::Timeout => DisconnectReason::Timeout,
            ObserverDisconnectReason::LinkLoss => DisconnectReason::LinkLoss,
            ObserverDisconnectReason::ConnectionFailed => DisconnectReason::ConnectionFailed,
            ObserverDisconnectReason::Unknown => DisconnectReason::Unknown,
        }
    }
}

impl From<PlatformDisconnectReason> for DisconnectReason {
    fn from(r: PlatformDisconnectReason) -> Self {
        match r {
            PlatformDisconnectReason::LocalRequest => DisconnectReason::LocalRequest,
            PlatformDisconnectReason::RemoteRequest => DisconnectReason::RemoteRequest,
            PlatformDisconnectReason::Timeout => DisconnectReason::Timeout,
            PlatformDisconnectReason::LinkLoss => DisconnectReason::LinkLoss,
            PlatformDisconnectReason::ConnectionFailed => DisconnectReason::ConnectionFailed,
            PlatformDisconnectReason::Unknown => DisconnectReason::Unknown,
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, uniffi::Enum)]
pub enum ConnectionState {
    Discovered,
    Connecting,
    Connected,
    Degraded,
    Disconnecting,
    Disconnected,
    Lost,
}

impl From<InternalConnectionState> for ConnectionState {
    fn from(s: InternalConnectionState) -> Self {
        match s {
            InternalConnectionState::Discovered => ConnectionState::Discovered,
            InternalConnectionState::Connecting => ConnectionState::Connecting,
            InternalConnectionState::Connected => ConnectionState::Connected,
            InternalConnectionState::Degraded => ConnectionState::Degraded,
            InternalConnectionState::Disconnecting => ConnectionState::Disconnecting,
            InternalConnectionState::Disconnected => ConnectionState::Disconnected,
            InternalConnectionState::Lost => ConnectionState::Lost,
        }
    }
}

impl From<ConnectionState> for InternalConnectionState {
    fn from(s: ConnectionState) -> Self {
        match s {
            ConnectionState::Discovered => InternalConnectionState::Discovered,
            ConnectionState::Connecting => InternalConnectionState::Connecting,
            ConnectionState::Connected => InternalConnectionState::Connected,
            ConnectionState::Degraded => InternalConnectionState::Degraded,
            ConnectionState::Disconnecting => InternalConnectionState::Disconnecting,
            ConnectionState::Disconnected => InternalConnectionState::Disconnected,
            ConnectionState::Lost => InternalConnectionState::Lost,
        }
    }
}

/// Convert raw u8 event_type to EventType enum
fn event_type_from_u8(value: u8) -> Option<EventType> {
    match value {
        0 => Some(EventType::None),
        1 => Some(EventType::Ping),
        2 => Some(EventType::NeedAssist),
        3 => Some(EventType::Emergency),
        4 => Some(EventType::Moving),
        5 => Some(EventType::InPosition),
        6 => Some(EventType::Ack),
        _ => None,
    }
}

// ============================================================================
// Data Structures (Records)
// ============================================================================

#[derive(Debug, Clone, uniffi::Record)]
pub struct PeatPeer {
    pub node_id: u32,
    pub identifier: String,
    pub name: Option<String>,
    pub mesh_id: Option<String>,
    pub rssi: i8,
    pub is_connected: bool,
    pub last_seen_ms: u64,
}

impl From<InternalPeatPeer> for PeatPeer {
    fn from(p: InternalPeatPeer) -> Self {
        PeatPeer {
            node_id: p.node_id.as_u32(),
            identifier: p.identifier.clone(),
            name: p.name.clone(),
            mesh_id: p.mesh_id.clone(),
            rssi: p.rssi,
            is_connected: p.is_connected,
            last_seen_ms: p.last_seen_ms,
        }
    }
}

#[derive(Debug, Clone, uniffi::Record)]
pub struct DataReceivedResult {
    pub source_node: u32,
    pub is_emergency: bool,
    pub is_ack: bool,
    pub counter_changed: bool,
    pub emergency_changed: bool,
    pub total_count: u64,
    pub event_timestamp: u64,
    pub relay_data: Option<Vec<u8>>,
    pub origin_node: Option<u32>,
    pub hop_count: u8,
    pub callsign: Option<String>,
    pub battery_percent: Option<u8>,
    pub heart_rate: Option<u8>,
    pub event_type: Option<EventType>,
    pub latitude: Option<f32>,
    pub longitude: Option<f32>,
    pub altitude: Option<f32>,
    /// Sender's activity level — 0=Standing, 3=PossibleFall, 4=Prone,
    /// 4+ reserved for sender-side extensions. Mirrors
    /// `HealthStatus::activity` from the merged peripheral.
    pub activity_level: Option<u8>,
    /// Sender's health alerts bitfield, e.g. `ALERT_MAN_DOWN = 0x01`.
    /// Mirrors `HealthStatus::alerts` from the merged peripheral.
    /// Hosts (peat-atak-plugin) can flip OFFLINE state directly from
    /// peripheral broadcasts via this field, without needing the
    /// higher-level 0xB6 platforms translator-frame to fire.
    pub alerts: Option<u8>,

    /// ADR-059 Amendment 3 — set when the receive dispatch decoded a
    /// 0xB6 translator frame on this call. `None` for legacy/delta/
    /// reserved-marker paths and for builds without the
    /// `translator-codec` feature. Defined unconditionally on the
    /// UniFFI struct shape so the binding contract is stable across
    /// feature combos. Hosts forward populated entries through
    /// peat-ffi's `publishDocumentWithOriginJni(.., "ble")`.
    pub decoded_translator_frame: Option<DecodedTranslatorFrame>,

    /// Set when the receive dispatch decoded a peat-lite Document
    /// envelope (`MessageType::Document`) on this call. `None` for
    /// every other receive path (legacy, delta-marker, 0xB6 translator,
    /// builds without the `peat-lite-frame` feature). Defined
    /// unconditionally on the UniFFI struct shape so Kotlin/Swift
    /// hosts see a stable accessor across feature combos. Hosts
    /// forward populated entries through peat-ffi's
    /// `publishDocumentWithOriginJni(collection, body_utf8, "ble")`
    /// once `body_utf8` validates as JSON; opaque (non-UTF-8) bodies
    /// are addressable via the raw `body` field.
    pub peat_lite_document: Option<PeatLiteDocumentFrame>,
}

/// ADR-059 Amendment 3 — payload returned in
/// [`DataReceivedResult::decoded_translator_frame`] when a 0xB6
/// translator frame decodes successfully. Defined unconditionally on
/// peat-btle's direct UniFFI binding shape so Kotlin hosts (the AAR
/// consumed by peat-atak-plugin) call the same field accessors against
/// any peat-btle build.
///
/// **Apple FFI scope.** iOS / macOS consumers go through the separate
/// `peat-apple-ffi` crate (`ios/peat-apple-ffi/`), which has its own
/// narrower `DataReceivedResult` and field-by-field translation;
/// Amendment 3 isn't yet exposed there. Tracked as a follow-up — no
/// Apple host actively consumes peat-btle's translator path today.
#[derive(Debug, Clone, uniffi::Record)]
pub struct DecodedTranslatorFrame {
    /// `BleTranslator` collection name, e.g. `"tracks"` / `"platforms"`.
    pub collection: String,
    /// serde-JSON serialization of the decoded `Document`.
    pub doc_json: String,
    /// BLE peer identifier from the receive context.
    pub peer: Option<String>,
}

impl From<crate::peat_mesh::DecodedTranslatorFrame> for DecodedTranslatorFrame {
    fn from(f: crate::peat_mesh::DecodedTranslatorFrame) -> Self {
        Self {
            collection: f.collection,
            doc_json: f.doc_json,
            peer: f.peer,
        }
    }
}

/// Universal-Document-transport payload returned in
/// [`DataReceivedResult::peat_lite_document`] when a peat-lite
/// `MessageType::Document` envelope decodes successfully on the
/// receive dispatch. Mirrors the internal
/// [`crate::peat_mesh::PeatLiteDocumentFrame`] across the FFI boundary
/// — Kotlin/Swift hosts need this projection because UniFFI Records
/// can't reach internal-only types.
///
/// **Apple FFI scope.** iOS / macOS consumers go through the separate
/// `peat-apple-ffi` crate (`ios/peat-apple-ffi/`), which has its own
/// narrower `DataReceivedResult` and field-by-field translation; the
/// peat-lite frame surface isn't yet wired there. Tracked as a
/// follow-up — no Apple host actively consumes peat-btle's peat-lite
/// path today.
///
/// `body` is the raw envelope body bytes (peat-btle does not
/// interpret); `body_utf8` is the same bytes projected as a UTF-8
/// string when valid, `None` for non-UTF-8 bodies. Consumers that
/// know the body is JSON-encoded (peat-mesh's
/// `transport::document_codec` produces JSON) parse `body_utf8` as
/// JSON; consumers carrying raw binary bodies (future M5Stack /
/// LoRa adapters with binary schemas) read `body` directly.
#[derive(Debug, Clone, uniffi::Record)]
pub struct PeatLiteDocumentFrame {
    /// Source node id from the peat-lite header. Polled hosts use
    /// this for loop-prevention and dedup tracking.
    pub source_node_id: u32,
    /// Sequence number from the peat-lite header. Polled hosts use
    /// this to detect duplicate deliveries.
    pub seq_num: u32,
    /// Flags byte from the Document envelope (bit 0 = tombstone).
    pub flags: u8,
    /// Convenience: tombstone bit (`flags & 0x01`) extracted so
    /// Kotlin/Swift consumers don't reach for the bit-twiddle.
    pub is_tombstone: bool,
    /// Collection name (UTF-8). Doc-store routing key alongside
    /// `doc_id`.
    pub collection: String,
    /// Document id (UTF-8). Empty signals
    /// "publisher-delegated id assignment."
    pub doc_id: String,
    /// Unix epoch milliseconds.
    pub timestamp_ms: i64,
    /// Opaque body bytes — peat-btle does not interpret. Consumers
    /// that know the schema parse via `body_utf8` (when the body is
    /// UTF-8 / JSON) or read these bytes directly (binary bodies).
    pub body: Vec<u8>,
    /// `body` interpreted as UTF-8. `None` when the bytes are not
    /// valid UTF-8 (binary-only consumers should read `body`). When
    /// populated by peat-mesh's `transport::document_codec`, this is
    /// a JSON document the host parses.
    pub body_utf8: Option<String>,
}

impl From<crate::peat_mesh::PeatLiteDocumentFrame> for PeatLiteDocumentFrame {
    fn from(f: crate::peat_mesh::PeatLiteDocumentFrame) -> Self {
        let is_tombstone = f.is_tombstone();
        let body_utf8 = std::str::from_utf8(&f.body).ok().map(|s| s.to_string());
        Self {
            source_node_id: f.source_node_id,
            seq_num: f.seq_num,
            flags: f.flags,
            is_tombstone,
            collection: f.collection,
            doc_id: f.doc_id,
            timestamp_ms: f.timestamp_ms,
            body: f.body,
            body_utf8,
        }
    }
}

impl From<InternalDataReceivedResult> for DataReceivedResult {
    fn from(r: InternalDataReceivedResult) -> Self {
        DataReceivedResult {
            source_node: r.source_node.as_u32(),
            is_emergency: r.is_emergency,
            is_ack: r.is_ack,
            counter_changed: r.counter_changed,
            emergency_changed: r.emergency_changed,
            total_count: r.total_count,
            event_timestamp: r.event_timestamp,
            relay_data: r.relay_data,
            origin_node: r.origin_node.map(|n| n.as_u32()),
            hop_count: r.hop_count,
            callsign: r.callsign,
            battery_percent: r.battery_percent,
            heart_rate: r.heart_rate,
            event_type: r.event_type.and_then(event_type_from_u8),
            latitude: r.latitude,
            longitude: r.longitude,
            altitude: r.altitude,
            activity_level: r.activity_level,
            alerts: r.alerts,
            decoded_translator_frame: r.decoded_translator_frame.map(Into::into),
            peat_lite_document: r.peat_lite_document.map(Into::into),
        }
    }
}

#[derive(Debug, Clone, uniffi::Record)]
pub struct PeerConnectionState {
    pub node_id: u32,
    pub identifier: String,
    pub state: ConnectionState,
    pub discovered_at: u64,
    pub connected_at: Option<u64>,
    pub disconnected_at: Option<u64>,
    pub disconnect_reason: Option<DisconnectReason>,
    pub last_rssi: Option<i8>,
    pub connection_count: u32,
    pub documents_synced: u32,
    pub bytes_received: u64,
    pub bytes_sent: u64,
    pub last_seen_ms: u64,
    pub name: Option<String>,
    pub mesh_id: Option<String>,
}

impl From<InternalPeerConnectionState> for PeerConnectionState {
    fn from(p: InternalPeerConnectionState) -> Self {
        PeerConnectionState {
            node_id: p.node_id.as_u32(),
            identifier: p.identifier,
            state: p.state.into(),
            discovered_at: p.discovered_at,
            connected_at: p.connected_at,
            disconnected_at: p.disconnected_at,
            disconnect_reason: p.disconnect_reason.map(|r| r.into()),
            last_rssi: p.last_rssi,
            connection_count: p.connection_count,
            documents_synced: p.documents_synced,
            bytes_received: p.bytes_received,
            bytes_sent: p.bytes_sent,
            last_seen_ms: p.last_seen_ms,
            name: p.name,
            mesh_id: p.mesh_id,
        }
    }
}

#[derive(Debug, Clone, Copy, uniffi::Record)]
pub struct StateCountSummary {
    pub discovered: u32,
    pub connecting: u32,
    pub connected: u32,
    pub degraded: u32,
    pub disconnecting: u32,
    pub disconnected: u32,
    pub lost: u32,
}

impl From<InternalStateCountSummary> for StateCountSummary {
    fn from(s: InternalStateCountSummary) -> Self {
        StateCountSummary {
            discovered: s.discovered as u32,
            connecting: s.connecting as u32,
            connected: s.connected as u32,
            degraded: s.degraded as u32,
            disconnecting: s.disconnecting as u32,
            disconnected: s.disconnected as u32,
            lost: s.lost as u32,
        }
    }
}

/// Via-peer routing entry for indirect peer
#[derive(Debug, Clone, uniffi::Record)]
pub struct ViaPeerRoute {
    pub via_node_id: u32,
    pub hop_count: u8,
}

#[derive(Debug, Clone, uniffi::Record)]
pub struct IndirectPeer {
    pub node_id: u32,
    pub min_hops: u8,
    pub via_peers: Vec<ViaPeerRoute>,
    pub discovered_at: u64,
    pub last_seen_ms: u64,
    pub messages_received: u32,
    pub callsign: Option<String>,
}

impl From<InternalIndirectPeer> for IndirectPeer {
    fn from(p: InternalIndirectPeer) -> Self {
        IndirectPeer {
            node_id: p.node_id.as_u32(),
            min_hops: p.min_hops,
            via_peers: p
                .via_peers
                .iter()
                .map(|(&node_id, &hop_count)| ViaPeerRoute {
                    via_node_id: node_id.as_u32(),
                    hop_count,
                })
                .collect(),
            discovered_at: p.discovered_at,
            last_seen_ms: p.last_seen_ms,
            messages_received: p.messages_received,
            callsign: p.callsign,
        }
    }
}

#[derive(Debug, Clone, Copy, uniffi::Record)]
pub struct FullStateCountSummary {
    pub direct: StateCountSummary,
    pub one_hop: u32,
    pub two_hop: u32,
    pub three_hop: u32,
}

impl From<InternalFullStateCountSummary> for FullStateCountSummary {
    fn from(s: InternalFullStateCountSummary) -> Self {
        FullStateCountSummary {
            direct: s.direct.into(),
            one_hop: s.one_hop as u32,
            two_hop: s.two_hop as u32,
            three_hop: s.three_hop as u32,
        }
    }
}

// ============================================================================
// PeatMesh Object
// ============================================================================

#[derive(uniffi::Object)]
pub struct PeatMesh {
    inner: peat_mesh::PeatMesh,
}

#[uniffi::export]
impl PeatMesh {
    /// Create a basic PeatMesh
    #[uniffi::constructor]
    pub fn new(node_id: u32, callsign: &str, mesh_id: &str) -> Arc<Self> {
        #[cfg(target_os = "android")]
        ensure_android_logger();

        let config = crate::PeatMeshConfig::new(NodeId::new(node_id), callsign, mesh_id);
        Arc::new(Self {
            inner: peat_mesh::PeatMesh::new(config),
        })
    }

    /// Create a PeatMesh with peripheral type
    #[uniffi::constructor]
    pub fn new_with_peripheral(
        node_id: u32,
        callsign: &str,
        mesh_id: &str,
        peripheral_type: PeripheralType,
    ) -> Arc<Self> {
        #[cfg(target_os = "android")]
        ensure_android_logger();

        let config = crate::PeatMeshConfig::new(NodeId::new(node_id), callsign, mesh_id)
            .with_peripheral_type(peripheral_type.into());
        Arc::new(Self {
            inner: peat_mesh::PeatMesh::new(config),
        })
    }

    /// Create a PeatMesh from genesis (recommended for production)
    #[uniffi::constructor]
    pub fn new_from_genesis(
        callsign: &str,
        identity: &DeviceIdentity,
        genesis: &MeshGenesis,
    ) -> Arc<Self> {
        #[cfg(target_os = "android")]
        ensure_android_logger();

        Arc::new(Self {
            inner: peat_mesh::PeatMesh::from_genesis(
                &genesis.inner,
                identity.inner.clone(),
                callsign,
            ),
        })
    }

    // ==================== Transport Layer ====================

    /// Decrypt data received over BLE (transport layer only)
    pub fn decrypt_only(&self, data: &[u8]) -> Option<Vec<u8>> {
        self.inner.decrypt_only(data)
    }

    /// Build the current document for transmission
    pub fn build_document(&self) -> Vec<u8> {
        self.inner.build_document()
    }

    /// Periodic tick - call every sync interval
    pub fn tick(&self, now_ms: u64) -> Option<Vec<u8>> {
        self.inner.tick(now_ms)
    }

    /// Build a delta document for a specific peer.
    ///
    /// This includes only operations that have changed since the last sync
    /// with this peer, including app-layer documents (CannedMessages, etc.).
    /// Returns None if there's nothing new to send.
    pub fn build_delta_document_for_peer(&self, peer_id: u32, now_ms: u64) -> Option<Vec<u8>> {
        self.inner
            .build_delta_document_for_peer(&crate::NodeId::new(peer_id), now_ms)
    }

    /// Build a full delta document containing all current state.
    ///
    /// Unlike `build_delta_document_for_peer`, this includes all state
    /// regardless of what has been sent before. Use for broadcasts or
    /// new peer connections. Includes app-layer documents.
    pub fn build_full_delta_document(&self, now_ms: u64) -> Vec<u8> {
        self.inner.build_full_delta_document(now_ms)
    }

    // ==================== Emergency/Ack ====================

    /// Send emergency alert
    pub fn send_emergency(&self, timestamp_ms: u64) -> Vec<u8> {
        self.inner.send_emergency(timestamp_ms)
    }

    /// Send ACK
    pub fn send_ack(&self, timestamp_ms: u64) -> Vec<u8> {
        self.inner.send_ack(timestamp_ms)
    }

    /// Check if emergency is currently active
    pub fn is_emergency_active(&self) -> bool {
        self.inner.is_emergency_active()
    }

    /// Check if ACK is currently active
    pub fn is_ack_active(&self) -> bool {
        self.inner.is_ack_active()
    }

    /// Broadcast arbitrary bytes over the mesh.
    ///
    /// Takes raw payload bytes, encrypts them (if encryption is enabled),
    /// and returns bytes ready to send to all connected peers.
    ///
    /// This is useful for sending extension data like CannedMessages from peat-lite.
    pub fn broadcast_bytes(&self, payload: &[u8]) -> Vec<u8> {
        self.inner.broadcast_bytes(payload)
    }

    /// Build a wire-ready peat-lite Document frame for transmission
    /// (Universal Document transport, ADR-035).
    ///
    /// The Android Kotlin consumer (peat-atak-plugin via peat-ffi)
    /// hands the envelope payload bytes produced by peat-mesh's
    /// `transport::document_codec::encode_document` (or any future
    /// equivalent codec — peat-btle stays codec-agnostic) to this
    /// method; it wraps with the 16-byte peat-lite header
    /// (`MessageType::Document`, this node's id, an internal monotonic
    /// `seq_num`), encrypts via the same path
    /// `broadcast_bytes` / typed-frame publishers use, and returns the
    /// bytes ready for GATT broadcast.
    ///
    /// **Apple FFI scope.** iOS / macOS consumers go through the
    /// separate `peat-apple-ffi` crate (`ios/peat-apple-ffi/`), which
    /// has its own UniFFI scaffolding and does not import these
    /// bindings. The peat-lite path isn't yet exposed there — tracked
    /// as [peat-btle #58](https://github.com/defenseunicorns/peat-btle/issues/58).
    /// No Apple host actively consumes peat-btle's peat-lite path
    /// today, so the iOS gap stays a follow-up rather than a blocker.
    ///
    /// Returns `None` only when the underlying codec rejects the
    /// envelope (e.g. malformed input, oversize payload). A `Some`
    /// return is the typical path; consumers should branch on it
    /// without retrying — re-publishing the same malformed bytes
    /// yields the same `None`.
    ///
    /// **Receive-side dedup primitive.** Each call advances the
    /// internal `peat_lite_seq` counter so polled-host receive-side
    /// dedup on `(source_node_id, seq_num)` always sees a unique pair
    /// per outbound frame. Locked at the wrapper tier by
    /// `tests/peat_lite_uniffi_e2e.rs::uniffi_publish_seq_num_strictly_increasing`
    /// so a regression to a per-call seq parameter is caught at the
    /// surface every consumer hits, not just the internal struct.
    #[cfg(feature = "peat-lite-frame")]
    pub fn publish_peat_lite_document(&self, envelope_payload: &[u8]) -> Option<Vec<u8>> {
        self.inner.publish_peat_lite_document(envelope_payload)
    }

    // ==================== BLE Callbacks ====================

    /// Call when a BLE device is discovered
    pub fn on_ble_discovered(
        &self,
        identifier: &str,
        name: Option<String>,
        rssi: i8,
        mesh_id: Option<String>,
        now_ms: u64,
    ) -> Option<PeatPeer> {
        self.inner
            .on_ble_discovered(
                identifier,
                name.as_deref(),
                rssi,
                mesh_id.as_deref(),
                now_ms,
            )
            .map(|p| p.into())
    }

    /// Call when a BLE connection is established
    pub fn on_ble_connected(&self, identifier: &str, now_ms: u64) {
        self.inner.on_ble_connected(identifier, now_ms);
    }

    /// Call when a remote device connects to us (incoming peripheral connection)
    ///
    /// Unlike on_ble_connected(), this creates the peer if it doesn't exist yet.
    /// Use this when acting as a GATT server and a central connects to us.
    pub fn on_incoming_connection(&self, identifier: &str, node_id: u32, now_ms: u64) -> bool {
        self.inner
            .on_incoming_connection(identifier, NodeId::new(node_id), now_ms)
    }

    /// Call when a BLE connection is lost
    pub fn on_ble_disconnected(&self, identifier: &str, reason: DisconnectReason) -> Option<u32> {
        self.inner
            .on_ble_disconnected(identifier, reason.into())
            .map(|n| n.as_u32())
    }

    /// Call when BLE data is received from a known peer
    pub fn on_ble_data_received(
        &self,
        identifier: &str,
        data: &[u8],
        now_ms: u64,
    ) -> Option<DataReceivedResult> {
        self.inner
            .on_ble_data_received(identifier, data, now_ms)
            .map(|r| r.into())
    }

    /// Call when BLE data is received from an unknown source (e.g., broadcast)
    pub fn on_ble_data_received_anonymous(
        &self,
        identifier: &str,
        data: &[u8],
        now_ms: u64,
    ) -> Option<DataReceivedResult> {
        self.inner
            .on_ble_data_received_anonymous(identifier, data, now_ms)
            .map(|r| r.into())
    }

    /// Mark this `PeatMesh` as having a polled-field consumer (ADR-059
    /// Amendment 3). Hosts that read
    /// [`DataReceivedResult.decodedTranslatorFrame`] per receive and
    /// forward through their own publish path SHOULD call this once
    /// at startup, before any GATT receive arrives. Without this
    /// attestation, the receive dispatch fires
    /// `PeatEvent::TranslatorNoCallback` for every decoded frame.
    /// Idempotent — calling again is a no-op.
    ///
    /// Defined unconditionally on peat-btle's direct UniFFI binding
    /// shape so the same Kotlin signature is callable against any
    /// peat-btle build, regardless of `translator-codec` feature
    /// combo. Apple FFI parity (`peat-apple-ffi`) is a tracked
    /// follow-up; Swift / iOS consumers do not yet see this method.
    pub fn acknowledge_polled_translator_consumer(&self) {
        self.inner.acknowledge_polled_translator_consumer();
    }

    // ==================== Peer Management ====================

    /// Get count of discovered peers
    pub fn peer_count(&self) -> u32 {
        self.inner.peer_count() as u32
    }

    /// Get count of connected peers
    pub fn connected_count(&self) -> u32 {
        self.inner.connected_count() as u32
    }

    /// Get total mesh count
    pub fn total_count(&self) -> u32 {
        self.inner.total_count() as u32
    }

    /// Get callsign for a peer
    pub fn get_peer_callsign(&self, node_id: u32) -> Option<String> {
        self.inner.get_peer_callsign(NodeId::new(node_id))
    }

    /// Get list of connected peers
    pub fn get_connected_peers(&self) -> Vec<PeatPeer> {
        self.inner
            .get_connected_peers()
            .into_iter()
            .map(|p| p.into())
            .collect()
    }

    /// Get count of degraded peers (connected but poor signal)
    pub fn degraded_peer_count(&self) -> u32 {
        self.inner.get_degraded_peers().len() as u32
    }

    /// Get count of recently disconnected peers
    pub fn recently_disconnected_count(&self, within_ms: u64, now_ms: u64) -> u32 {
        self.inner
            .get_recently_disconnected(within_ms, now_ms)
            .len() as u32
    }

    /// Get count of lost peers (disconnected and timed out)
    pub fn lost_peer_count(&self) -> u32 {
        self.inner.get_lost_peers().len() as u32
    }

    /// Check if a peer is known
    pub fn is_peer_known(&self, node_id: u32) -> bool {
        self.inner.is_peer_known(NodeId::new(node_id))
    }

    /// Check if mesh matches (for filtering BLE discovery)
    pub fn matches_mesh(&self, device_mesh_id: Option<String>) -> bool {
        self.inner.matches_mesh(device_mesh_id.as_deref())
    }

    /// Get connection state for a specific peer
    pub fn get_peer_connection_state(&self, node_id: u32) -> Option<PeerConnectionState> {
        self.inner
            .get_peer_connection_state(NodeId::new(node_id))
            .map(|p| p.into())
    }

    /// Get all degraded peers (connected but poor signal quality)
    pub fn get_degraded_peers(&self) -> Vec<PeerConnectionState> {
        self.inner
            .get_degraded_peers()
            .into_iter()
            .map(|p| p.into())
            .collect()
    }

    /// Get all lost peers (disconnected and timed out)
    pub fn get_lost_peers(&self) -> Vec<PeerConnectionState> {
        self.inner
            .get_lost_peers()
            .into_iter()
            .map(|p| p.into())
            .collect()
    }

    /// Get connection state counts (direct peers)
    pub fn get_connection_state_counts(&self) -> StateCountSummary {
        self.inner.get_connection_state_counts().into()
    }

    /// Get indirect (multi-hop) peers
    pub fn get_indirect_peers(&self) -> Vec<IndirectPeer> {
        self.inner
            .get_indirect_peers()
            .into_iter()
            .map(|p| p.into())
            .collect()
    }

    /// Get full state counts including indirect peers
    pub fn get_full_state_counts(&self) -> FullStateCountSummary {
        self.inner.get_full_state_counts().into()
    }

    // ==================== Location & State ====================

    /// Update own location
    pub fn update_location(&self, latitude: f32, longitude: f32, altitude: Option<f32>) {
        self.inner.update_location(latitude, longitude, altitude);
    }

    /// Clear own location
    pub fn clear_location(&self) {
        self.inner.clear_location();
    }

    /// Update own callsign
    pub fn update_callsign(&self, callsign: &str) {
        self.inner.update_callsign(callsign);
    }

    /// Update own heart rate
    pub fn update_heart_rate(&self, bpm: u8) {
        self.inner.update_heart_rate(bpm);
    }

    /// Replace the alert-flags bitfield on the local peripheral. Callers
    /// OR together `HealthStatus::ALERT_*` constants (e.g. `ALERT_MAN_DOWN`
    /// when sensing Prone, `ALERT_LOW_BATTERY` when battery drops) into a
    /// single `u8`; passing `0` clears all alerts.
    pub fn update_alerts(&self, alerts: u8) {
        self.inner.update_alerts(alerts);
    }

    /// Set peripheral event
    pub fn set_peripheral_event(&self, event_type: EventType, timestamp_ms: u64) {
        self.inner
            .set_peripheral_event(event_type.into(), timestamp_ms);
    }

    /// Clear peripheral event
    pub fn clear_peripheral_event(&self) {
        self.inner.clear_peripheral_event();
    }

    /// Update all peripheral state at once (efficient for encrypted transmission)
    #[allow(clippy::too_many_arguments)]
    pub fn update_peripheral_state(
        &self,
        callsign: &str,
        battery_percent: u8,
        heart_rate: Option<u8>,
        latitude: Option<f32>,
        longitude: Option<f32>,
        altitude: Option<f32>,
        event_type: Option<EventType>,
        timestamp_ms: u64,
    ) {
        self.inner.update_peripheral_state(
            callsign,
            battery_percent,
            heart_rate,
            latitude,
            longitude,
            altitude,
            event_type.map(|e| e.into()),
            timestamp_ms,
        );
    }

    // ==================== Identity ====================

    /// Check if mesh has a cryptographic identity
    pub fn has_identity(&self) -> bool {
        self.inner.has_identity()
    }

    /// Get own public key
    pub fn get_public_key(&self) -> Option<Vec<u8>> {
        self.inner.public_key().map(|k| k.to_vec())
    }

    /// Create an identity attestation
    pub fn create_attestation(&self, timestamp_ms: u64) -> Option<Vec<u8>> {
        self.inner
            .create_attestation(timestamp_ms)
            .map(|a| a.encode())
    }

    /// Verify a peer's identity from attestation bytes
    /// Returns true if identity was registered or verified, false otherwise
    pub fn verify_peer_identity(&self, attestation_bytes: &[u8]) -> bool {
        if let Some(attestation) = InternalIdentityAttestation::decode(attestation_bytes) {
            matches!(
                self.inner.verify_peer_identity(&attestation),
                RegistryResult::Registered | RegistryResult::Verified
            )
        } else {
            false
        }
    }

    /// Check if a peer's identity is known
    pub fn is_peer_identity_known(&self, node_id: u32) -> bool {
        self.inner.is_peer_identity_known(NodeId::new(node_id))
    }

    /// Get count of known identities
    pub fn known_identity_count(&self) -> u32 {
        self.inner.known_identity_count() as u32
    }

    /// Sign data with own identity
    pub fn sign(&self, message: &[u8]) -> Option<Vec<u8>> {
        self.inner.sign(message).map(|s| s.to_vec())
    }

    /// Verify a peer's signature
    pub fn verify_peer_signature(&self, node_id: u32, message: &[u8], signature: &[u8]) -> bool {
        if signature.len() != 64 {
            return false;
        }
        let mut sig_array = [0u8; 64];
        sig_array.copy_from_slice(signature);
        self.inner
            .verify_peer_signature(NodeId::new(node_id), message, &sig_array)
    }

    // ==================== Encryption ====================

    /// Check if encryption is enabled
    pub fn is_encryption_enabled(&self) -> bool {
        self.inner.is_encryption_enabled()
    }

    // ==================== Relay ====================

    /// Check if relay is enabled
    pub fn is_relay_enabled(&self) -> bool {
        self.inner.is_relay_enabled()
    }

    // ==================== CannedMessage Integration ====================
    // These methods enable proper CRDT sync for peat-lite CannedMessages,
    // using document identity for deduplication instead of raw relay.

    /// Check if a CannedMessage has been seen recently.
    ///
    /// Uses document identity (source_node + timestamp) for deduplication.
    /// This prevents broadcast storms when relaying CannedMessages.
    ///
    /// Returns true if the message should be processed, false if it's a duplicate.
    pub fn check_canned_message(&self, source_node: u32, timestamp: u64, ttl_ms: u64) -> bool {
        self.inner
            .check_canned_message(source_node, timestamp, ttl_ms)
    }

    /// Mark a CannedMessage as seen (for deduplication).
    ///
    /// Call this after receiving and processing a CannedMessage to prevent
    /// reprocessing the same message from other relay paths.
    pub fn mark_canned_message_seen(&self, source_node: u32, timestamp: u64) {
        self.inner.mark_canned_message_seen(source_node, timestamp);
    }

    /// Get the list of connected peer identifiers for relay.
    ///
    /// Used by the Kotlin layer to relay CannedMessages to other peers
    /// after deduplication check.
    pub fn get_connected_peer_identifiers(&self) -> Vec<String> {
        self.inner.get_connected_peer_identifiers()
    }

    /// Get the number of stored app documents.
    pub fn app_document_count(&self) -> u32 {
        self.inner.app_document_count() as u32
    }
}

/// ADR-059 Amendment 2 — host-side wiring for cross-transport receive.
///
/// Lives in a separate `#[uniffi::export]` impl block gated on both
/// `translator-codec` and `uniffi` so that builds with only `uniffi`
/// enabled (no translator-codec) compile cleanly — `#[uniffi::export]`
/// at the impl level processes every method without checking inner
/// cfg gates, so cfg-gated methods inside the main impl trigger
/// "trait not found" errors when the trait itself is gated out.
#[cfg(all(feature = "translator-codec", feature = "uniffi"))]
#[uniffi::export]
impl PeatMesh {
    /// Install the callback invoked for each successfully-decoded
    /// inbound translator frame. Hosts implement
    /// [`crate::DecodedDocumentJsonCallback`] in Kotlin / Swift and
    /// forward each `on_document` call into peat-ffi's existing
    /// `publishDocument`-shaped FFI with `origin="ble"`. Idempotent —
    /// calling again replaces the previous callback.
    pub fn set_decoded_document_json_callback(
        &self,
        cb: Box<dyn crate::DecodedDocumentJsonCallback>,
    ) {
        self.inner.set_decoded_document_json_callback(cb);
    }
}

// ============================================================================
// DeviceIdentity Object
// ============================================================================

#[derive(uniffi::Object)]
pub struct DeviceIdentity {
    inner: InternalDeviceIdentity,
}

#[uniffi::export]
impl DeviceIdentity {
    /// Generate a new random identity
    #[uniffi::constructor]
    pub fn generate() -> Arc<Self> {
        Arc::new(Self {
            inner: InternalDeviceIdentity::generate(),
        })
    }

    /// Get public key bytes
    pub fn get_public_key(&self) -> Vec<u8> {
        self.inner.public_key().to_vec()
    }

    /// Get private key bytes (for secure storage)
    pub fn get_private_key(&self) -> Vec<u8> {
        self.inner.private_key_bytes().to_vec()
    }

    /// Get derived node ID
    pub fn get_node_id(&self) -> u32 {
        self.inner.node_id().as_u32()
    }

    /// Create an attestation proving identity ownership
    pub fn create_attestation(&self, timestamp_ms: u64) -> Vec<u8> {
        self.inner.create_attestation(timestamp_ms).encode()
    }

    /// Sign data
    pub fn sign(&self, message: &[u8]) -> Vec<u8> {
        self.inner.sign(message).to_vec()
    }
}

// ============================================================================
// MeshGenesis Object
// ============================================================================

#[derive(uniffi::Object)]
pub struct MeshGenesis {
    inner: InternalMeshGenesis,
}

#[uniffi::export]
impl MeshGenesis {
    /// Create a new mesh as founder
    #[uniffi::constructor]
    pub fn create(mesh_name: &str, founder_identity: &DeviceIdentity) -> Arc<Self> {
        Arc::new(Self {
            inner: InternalMeshGenesis::create(
                mesh_name,
                &founder_identity.inner,
                MembershipPolicy::Open,
            ),
        })
    }

    /// Get mesh ID
    pub fn get_mesh_id(&self) -> String {
        self.inner.mesh_id()
    }

    /// Get encryption secret for mesh
    pub fn get_encryption_secret(&self) -> Vec<u8> {
        self.inner.encryption_secret().to_vec()
    }

    /// Encode genesis to bytes for storage/transmission
    pub fn encode(&self) -> Vec<u8> {
        self.inner.encode()
    }
}

// ============================================================================
// IdentityAttestation Object
// ============================================================================

#[derive(uniffi::Object)]
pub struct IdentityAttestation {
    inner: InternalIdentityAttestation,
}

#[uniffi::export]
impl IdentityAttestation {
    /// Verify attestation is valid
    pub fn verify(&self) -> bool {
        self.inner.verify()
    }

    /// Get node ID from attestation
    pub fn get_node_id(&self) -> u32 {
        self.inner.node_id.as_u32()
    }

    /// Get public key from attestation
    pub fn get_public_key(&self) -> Vec<u8> {
        self.inner.public_key.to_vec()
    }
}

// ============================================================================
// Namespace Functions
// ============================================================================

/// Derive a node ID from a MAC address string (format: "AA:BB:CC:DD:EE:FF")
#[uniffi::export]
pub fn derive_node_id_from_mac(mac_address: &str) -> u32 {
    NodeId::from_mac_string(mac_address)
        .map(|n| n.as_u32())
        .unwrap_or(0)
}

/// Create a PeatMesh with encryption enabled (returns null if secret is wrong length)
#[uniffi::export]
pub fn create_peat_mesh_with_encryption(
    node_id: u32,
    callsign: &str,
    mesh_id: &str,
    encryption_secret: &[u8],
) -> Option<std::sync::Arc<PeatMesh>> {
    if encryption_secret.len() != 32 {
        return None;
    }
    let mut secret = [0u8; 32];
    secret.copy_from_slice(encryption_secret);
    let config =
        crate::PeatMeshConfig::new(NodeId::new(node_id), callsign, mesh_id).with_encryption(secret);
    Some(std::sync::Arc::new(PeatMesh {
        inner: peat_mesh::PeatMesh::new(config),
    }))
}

/// Restore a DeviceIdentity from private key bytes (returns null if invalid)
#[uniffi::export]
pub fn restore_device_identity(private_key: &[u8]) -> Option<std::sync::Arc<DeviceIdentity>> {
    if private_key.len() < 32 {
        return None;
    }
    let mut key_bytes = [0u8; 32];
    key_bytes.copy_from_slice(&private_key[..32]);
    InternalDeviceIdentity::from_private_key(&key_bytes)
        .ok()
        .map(|inner| std::sync::Arc::new(DeviceIdentity { inner }))
}

/// Decode a MeshGenesis from bytes (returns null if invalid)
#[uniffi::export]
pub fn decode_mesh_genesis(encoded: &[u8]) -> Option<std::sync::Arc<MeshGenesis>> {
    InternalMeshGenesis::decode(encoded).map(|inner| std::sync::Arc::new(MeshGenesis { inner }))
}

/// Decode an IdentityAttestation from bytes (returns null if invalid)
#[uniffi::export]
pub fn decode_identity_attestation(encoded: &[u8]) -> Option<std::sync::Arc<IdentityAttestation>> {
    InternalIdentityAttestation::decode(encoded)
        .map(|inner| std::sync::Arc::new(IdentityAttestation { inner }))
}

// ============================================================================
// Helper Functions
// ============================================================================

// ============================================================================
// Reconnection Manager (auto-reconnect with exponential backoff)
// ============================================================================

use crate::reconnect::{
    PeerReconnectionStats as InternalPeerReconnectionStats,
    ReconnectionConfig as InternalReconnectionConfig,
    ReconnectionManager as InternalReconnectionManager,
    ReconnectionStatus as InternalReconnectionStatus,
};

/// Configuration for reconnection behavior
#[derive(Debug, Clone, uniffi::Record)]
pub struct ReconnectionConfig {
    /// Base delay between reconnection attempts in milliseconds
    pub base_delay_ms: u64,
    /// Maximum delay between attempts in milliseconds
    pub max_delay_ms: u64,
    /// Maximum number of reconnection attempts before giving up
    pub max_attempts: u32,
    /// Interval for checking which peers need reconnection in milliseconds
    pub check_interval_ms: u64,
    /// Use flat delay instead of exponential backoff
    pub use_flat_delay: bool,
    /// Auto-reset attempt counter when max_attempts is exhausted
    pub reset_on_exhaustion: bool,
}

impl Default for ReconnectionConfig {
    fn default() -> Self {
        Self {
            base_delay_ms: 2000,
            max_delay_ms: 60000,
            max_attempts: 10,
            check_interval_ms: 5000,
            use_flat_delay: false,
            reset_on_exhaustion: false,
        }
    }
}

impl From<ReconnectionConfig> for InternalReconnectionConfig {
    fn from(c: ReconnectionConfig) -> Self {
        let mut config = InternalReconnectionConfig::new(
            std::time::Duration::from_millis(c.base_delay_ms),
            std::time::Duration::from_millis(c.max_delay_ms),
            c.max_attempts,
            std::time::Duration::from_millis(c.check_interval_ms),
        );
        config.use_flat_delay = c.use_flat_delay;
        config.reset_on_exhaustion = c.reset_on_exhaustion;
        config
    }
}

/// Result of checking if a peer should be reconnected
#[derive(Debug, Clone, PartialEq, Eq, uniffi::Enum)]
pub enum ReconnectionStatus {
    /// Ready to attempt reconnection
    Ready,
    /// Waiting for backoff delay to expire
    Waiting {
        /// Time remaining until next attempt is allowed in milliseconds
        remaining_ms: u64,
    },
    /// Maximum attempts exceeded, peer is abandoned
    Exhausted {
        /// Number of attempts that were made
        attempts: u32,
    },
    /// Peer is not being tracked for reconnection
    NotTracked,
}

impl From<InternalReconnectionStatus> for ReconnectionStatus {
    fn from(s: InternalReconnectionStatus) -> Self {
        match s {
            InternalReconnectionStatus::Ready => ReconnectionStatus::Ready,
            InternalReconnectionStatus::Waiting { remaining } => ReconnectionStatus::Waiting {
                remaining_ms: remaining.as_millis() as u64,
            },
            InternalReconnectionStatus::Exhausted { attempts } => {
                ReconnectionStatus::Exhausted { attempts }
            }
            InternalReconnectionStatus::NotTracked => ReconnectionStatus::NotTracked,
        }
    }
}

/// Statistics for a peer's reconnection state
#[derive(Debug, Clone, uniffi::Record)]
pub struct PeerReconnectionStats {
    /// Number of attempts made
    pub attempts: u32,
    /// Maximum allowed attempts
    pub max_attempts: u32,
    /// How long since the peer disconnected in milliseconds
    pub disconnected_duration_ms: u64,
    /// Time until next reconnection attempt in milliseconds (0 if ready, u64::MAX if exhausted)
    pub next_attempt_delay_ms: u64,
}

impl From<InternalPeerReconnectionStats> for PeerReconnectionStats {
    fn from(s: InternalPeerReconnectionStats) -> Self {
        PeerReconnectionStats {
            attempts: s.attempts,
            max_attempts: s.max_attempts,
            disconnected_duration_ms: s.disconnected_duration.as_millis() as u64,
            next_attempt_delay_ms: s.next_attempt_delay.as_millis() as u64,
        }
    }
}

/// Manager for auto-reconnection with exponential backoff
#[derive(uniffi::Object)]
pub struct ReconnectionManager {
    inner: std::sync::Mutex<InternalReconnectionManager>,
}

#[uniffi::export]
impl ReconnectionManager {
    /// Create a new reconnection manager with the given configuration
    #[uniffi::constructor]
    pub fn new(config: ReconnectionConfig) -> Arc<Self> {
        Arc::new(Self {
            inner: std::sync::Mutex::new(InternalReconnectionManager::new(config.into())),
        })
    }

    /// Create a manager with default configuration
    #[uniffi::constructor]
    pub fn with_defaults() -> Arc<Self> {
        Arc::new(Self {
            inner: std::sync::Mutex::new(InternalReconnectionManager::with_defaults()),
        })
    }

    /// Track a peer for reconnection after disconnection
    pub fn track_disconnection(&self, address: String) {
        self.inner.lock().unwrap().track_disconnection(address);
    }

    /// Check if a peer is being tracked for reconnection
    pub fn is_tracked(&self, address: &str) -> bool {
        self.inner.lock().unwrap().is_tracked(address)
    }

    /// Get the reconnection status for a peer
    pub fn get_status(&self, address: &str) -> ReconnectionStatus {
        self.inner.lock().unwrap().get_status(address).into()
    }

    /// Get all peers that are ready for a reconnection attempt
    pub fn get_peers_to_reconnect(&self) -> Vec<String> {
        self.inner.lock().unwrap().get_peers_to_reconnect()
    }

    /// Record a reconnection attempt for a peer
    pub fn record_attempt(&self, address: &str) {
        self.inner.lock().unwrap().record_attempt(address);
    }

    /// Called when a connection succeeds
    pub fn on_connection_success(&self, address: &str) {
        self.inner.lock().unwrap().on_connection_success(address);
    }

    /// Stop tracking a peer
    pub fn stop_tracking(&self, address: &str) {
        self.inner.lock().unwrap().stop_tracking(address);
    }

    /// Clear all reconnection tracking
    pub fn clear(&self) {
        self.inner.lock().unwrap().clear();
    }

    /// Get the number of peers being tracked
    pub fn tracked_count(&self) -> u32 {
        self.inner.lock().unwrap().tracked_count() as u32
    }

    /// Get statistics for a peer
    pub fn get_peer_stats(&self, address: &str) -> Option<PeerReconnectionStats> {
        self.inner
            .lock()
            .unwrap()
            .get_peer_stats(address)
            .map(|s| s.into())
    }

    /// Get the check interval from configuration in milliseconds
    pub fn check_interval_ms(&self) -> u64 {
        self.inner.lock().unwrap().check_interval().as_millis() as u64
    }
}

// ============================================================================
// Peer Lifetime Manager (stale peer cleanup)
// ============================================================================

use crate::peer_lifetime::{
    PeerInfo as InternalPeerInfo, PeerLifetimeConfig as InternalPeerLifetimeConfig,
    PeerLifetimeManager as InternalPeerLifetimeManager,
    PeerLifetimeStats as InternalPeerLifetimeStats, StalePeerInfo as InternalStalePeerInfo,
    StaleReason as InternalStaleReason,
};

/// Configuration for peer lifetime management
#[derive(Debug, Clone, uniffi::Record)]
pub struct PeerLifetimeConfig {
    /// Timeout for disconnected peers in milliseconds
    pub disconnected_timeout_ms: u64,
    /// Timeout for connected peers in milliseconds
    pub connected_timeout_ms: u64,
    /// Interval for cleanup checks in milliseconds
    pub cleanup_interval_ms: u64,
}

impl Default for PeerLifetimeConfig {
    fn default() -> Self {
        Self {
            disconnected_timeout_ms: 30000,
            connected_timeout_ms: 60000,
            cleanup_interval_ms: 10000,
        }
    }
}

impl From<PeerLifetimeConfig> for InternalPeerLifetimeConfig {
    fn from(c: PeerLifetimeConfig) -> Self {
        InternalPeerLifetimeConfig::new(
            std::time::Duration::from_millis(c.disconnected_timeout_ms),
            std::time::Duration::from_millis(c.connected_timeout_ms),
            std::time::Duration::from_millis(c.cleanup_interval_ms),
        )
    }
}

/// Reason a peer is considered stale
#[derive(Debug, Clone, Copy, PartialEq, Eq, uniffi::Enum)]
pub enum StaleReason {
    /// Disconnected peer hasn't been seen in a while
    DisconnectedTimeout,
    /// Connected peer hasn't had activity (possible ghost connection)
    ConnectedTimeout,
}

impl From<InternalStaleReason> for StaleReason {
    fn from(r: InternalStaleReason) -> Self {
        match r {
            InternalStaleReason::DisconnectedTimeout => StaleReason::DisconnectedTimeout,
            InternalStaleReason::ConnectedTimeout => StaleReason::ConnectedTimeout,
        }
    }
}

/// Information about a stale peer
#[derive(Debug, Clone, uniffi::Record)]
pub struct StalePeerInfo {
    /// Peer address
    pub address: String,
    /// Why the peer is considered stale
    pub reason: StaleReason,
    /// How long since the peer was last seen in milliseconds
    pub time_since_last_seen_ms: u64,
    /// Whether the peer was connected when it went stale
    pub was_connected: bool,
}

impl From<InternalStalePeerInfo> for StalePeerInfo {
    fn from(p: InternalStalePeerInfo) -> Self {
        StalePeerInfo {
            address: p.address,
            reason: p.reason.into(),
            time_since_last_seen_ms: p.time_since_last_seen.as_millis() as u64,
            was_connected: p.was_connected,
        }
    }
}

/// Statistics about tracked peers
#[derive(Debug, Clone, Copy, uniffi::Record)]
pub struct PeerLifetimeStats {
    /// Total number of tracked peers
    pub total_tracked: u32,
    /// Number of connected peers
    pub connected: u32,
    /// Number of disconnected peers
    pub disconnected: u32,
}

impl From<InternalPeerLifetimeStats> for PeerLifetimeStats {
    fn from(s: InternalPeerLifetimeStats) -> Self {
        PeerLifetimeStats {
            total_tracked: s.total_tracked as u32,
            connected: s.connected as u32,
            disconnected: s.disconnected as u32,
        }
    }
}

/// Detailed information about a peer
#[derive(Debug, Clone, uniffi::Record)]
pub struct PeerInfo {
    /// Whether the peer is currently connected
    pub connected: bool,
    /// Time since last activity in milliseconds
    pub time_since_last_seen_ms: u64,
    /// Time since first discovery in milliseconds
    pub time_since_first_seen_ms: u64,
    /// Time since disconnect in milliseconds (if disconnected)
    pub time_since_disconnect_ms: Option<u64>,
}

impl From<InternalPeerInfo> for PeerInfo {
    fn from(p: InternalPeerInfo) -> Self {
        PeerInfo {
            connected: p.connected,
            time_since_last_seen_ms: p.time_since_last_seen.as_millis() as u64,
            time_since_first_seen_ms: p.time_since_first_seen.as_millis() as u64,
            time_since_disconnect_ms: p.time_since_disconnect.map(|d| d.as_millis() as u64),
        }
    }
}

/// Manager for peer lifetime and stale peer cleanup
#[derive(uniffi::Object)]
pub struct PeerLifetimeManager {
    inner: std::sync::Mutex<InternalPeerLifetimeManager>,
}

#[uniffi::export]
impl PeerLifetimeManager {
    /// Create a new peer lifetime manager with the given configuration
    #[uniffi::constructor]
    pub fn new(config: PeerLifetimeConfig) -> Arc<Self> {
        Arc::new(Self {
            inner: std::sync::Mutex::new(InternalPeerLifetimeManager::new(config.into())),
        })
    }

    /// Create a manager with default configuration
    #[uniffi::constructor]
    pub fn with_defaults() -> Arc<Self> {
        Arc::new(Self {
            inner: std::sync::Mutex::new(InternalPeerLifetimeManager::with_defaults()),
        })
    }

    /// Record activity for a peer
    pub fn on_peer_activity(&self, address: &str, connected: bool) {
        self.inner
            .lock()
            .unwrap()
            .on_peer_activity(address, connected);
    }

    /// Record that a peer has disconnected
    pub fn on_peer_disconnected(&self, address: &str) {
        self.inner.lock().unwrap().on_peer_disconnected(address);
    }

    /// Check if a peer is being tracked
    pub fn is_tracked(&self, address: &str) -> bool {
        self.inner.lock().unwrap().is_tracked(address)
    }

    /// Check if a peer is connected
    pub fn is_connected(&self, address: &str) -> bool {
        self.inner.lock().unwrap().is_connected(address)
    }

    /// Get the list of stale peers that should be removed
    pub fn get_stale_peers(&self) -> Vec<StalePeerInfo> {
        self.inner
            .lock()
            .unwrap()
            .get_stale_peers()
            .into_iter()
            .map(|p| p.into())
            .collect()
    }

    /// Get just the addresses of stale peers
    pub fn get_stale_peer_addresses(&self) -> Vec<String> {
        self.inner.lock().unwrap().get_stale_peer_addresses()
    }

    /// Remove a peer from tracking
    pub fn remove_peer(&self, address: &str) -> bool {
        self.inner.lock().unwrap().remove_peer(address)
    }

    /// Remove all stale peers and return their info
    pub fn cleanup_stale_peers(&self) -> Vec<StalePeerInfo> {
        self.inner
            .lock()
            .unwrap()
            .cleanup_stale_peers()
            .into_iter()
            .map(|p| p.into())
            .collect()
    }

    /// Get statistics about tracked peers
    pub fn stats(&self) -> PeerLifetimeStats {
        self.inner.lock().unwrap().stats().into()
    }

    /// Get detailed info about a specific peer
    pub fn get_peer_info(&self, address: &str) -> Option<PeerInfo> {
        self.inner
            .lock()
            .unwrap()
            .get_peer_info(address)
            .map(|p| p.into())
    }

    /// Clear all tracked peers
    pub fn clear(&self) {
        self.inner.lock().unwrap().clear();
    }

    /// Get the number of tracked peers
    pub fn tracked_count(&self) -> u32 {
        self.inner.lock().unwrap().tracked_count() as u32
    }

    /// Get the cleanup interval from configuration in milliseconds
    pub fn cleanup_interval_ms(&self) -> u64 {
        self.inner.lock().unwrap().cleanup_interval().as_millis() as u64
    }
}

// ============================================================================
// Address Rotation Handler (BLE address rotation for WearOS)
// ============================================================================

use crate::address_rotation::{
    AddressRotationHandler as InternalAddressRotationHandler,
    AddressRotationStats as InternalAddressRotationStats,
    DeviceLookupResult as InternalDeviceLookupResult, DevicePattern as InternalDevicePattern,
};

/// Patterns that indicate a device may rotate its BLE address
#[derive(Debug, Clone, Copy, PartialEq, Eq, uniffi::Enum)]
pub enum DevicePattern {
    /// WearTAK on WearOS (WT-WEAROS-XXXX)
    WearTak,
    /// Generic WearOS device (WEAROS-XXXX)
    WearOs,
    /// Peat mesh device (PEAT_MESH-XXXX or PEAT-XXXX)
    Peat,
    /// Unknown pattern (may still rotate addresses)
    Unknown,
}

impl From<InternalDevicePattern> for DevicePattern {
    fn from(p: InternalDevicePattern) -> Self {
        match p {
            InternalDevicePattern::WearTak => DevicePattern::WearTak,
            InternalDevicePattern::WearOs => DevicePattern::WearOs,
            InternalDevicePattern::Peat => DevicePattern::Peat,
            InternalDevicePattern::Unknown => DevicePattern::Unknown,
        }
    }
}

impl DevicePattern {
    /// Check if this device type is known to rotate addresses
    pub fn rotates_addresses(&self) -> bool {
        matches!(self, DevicePattern::WearTak | DevicePattern::WearOs)
    }
}

/// Result of looking up a device by name
#[derive(Debug, Clone, uniffi::Record)]
pub struct DeviceLookupResult {
    /// The node ID for this device
    pub node_id: u32,
    /// The current known address
    pub current_address: String,
    /// Whether the address has changed
    pub address_changed: bool,
    /// The previous address (if changed)
    pub previous_address: Option<String>,
}

impl From<InternalDeviceLookupResult> for DeviceLookupResult {
    fn from(r: InternalDeviceLookupResult) -> Self {
        DeviceLookupResult {
            node_id: r.node_id.as_u32(),
            current_address: r.current_address,
            address_changed: r.address_changed,
            previous_address: r.previous_address,
        }
    }
}

/// Statistics about address rotation handling
#[derive(Debug, Clone, Copy, uniffi::Record)]
pub struct AddressRotationStats {
    /// Number of devices tracked by name
    pub devices_with_names: u32,
    /// Total number of devices tracked
    pub total_devices: u32,
    /// Number of address mappings
    pub address_mappings: u32,
}

impl From<InternalAddressRotationStats> for AddressRotationStats {
    fn from(s: InternalAddressRotationStats) -> Self {
        AddressRotationStats {
            devices_with_names: s.devices_with_names as u32,
            total_devices: s.total_devices as u32,
            address_mappings: s.address_mappings as u32,
        }
    }
}

/// Handler for BLE address rotation
#[derive(uniffi::Object)]
pub struct AddressRotationHandler {
    inner: std::sync::Mutex<InternalAddressRotationHandler>,
}

#[uniffi::export]
impl AddressRotationHandler {
    /// Create a new address rotation handler
    #[uniffi::constructor]
    pub fn new() -> Arc<Self> {
        Arc::new(Self {
            inner: std::sync::Mutex::new(InternalAddressRotationHandler::new()),
        })
    }

    /// Register a new device
    pub fn register_device(&self, name: &str, address: &str, node_id: u32) {
        self.inner
            .lock()
            .unwrap()
            .register_device(name, address, NodeId::new(node_id));
    }

    /// Look up a device by name
    pub fn lookup_by_name(&self, name: &str) -> Option<u32> {
        self.inner
            .lock()
            .unwrap()
            .lookup_by_name(name)
            .map(|n| n.as_u32())
    }

    /// Look up a device by address
    pub fn lookup_by_address(&self, address: &str) -> Option<u32> {
        self.inner
            .lock()
            .unwrap()
            .lookup_by_address(address)
            .map(|n| n.as_u32())
    }

    /// Get the current address for a node
    pub fn get_address(&self, node_id: u32) -> Option<String> {
        self.inner
            .lock()
            .unwrap()
            .get_address(&NodeId::new(node_id))
            .cloned()
    }

    /// Get the name for a node
    pub fn get_name(&self, node_id: u32) -> Option<String> {
        self.inner
            .lock()
            .unwrap()
            .get_name(&NodeId::new(node_id))
            .cloned()
    }

    /// Handle a device discovery, detecting address rotation
    pub fn on_device_discovered(&self, name: &str, address: &str) -> Option<DeviceLookupResult> {
        self.inner
            .lock()
            .unwrap()
            .on_device_discovered(name, address)
            .map(|r| r.into())
    }

    /// Update the address for a device (used when address rotation is detected)
    pub fn update_address(&self, name: &str, new_address: &str) -> bool {
        self.inner.lock().unwrap().update_address(name, new_address)
    }

    /// Update the name for a device
    pub fn update_name(&self, node_id: u32, new_name: &str) {
        self.inner
            .lock()
            .unwrap()
            .update_name(NodeId::new(node_id), new_name);
    }

    /// Remove a device from all mappings
    pub fn remove_device(&self, node_id: u32) {
        self.inner
            .lock()
            .unwrap()
            .remove_device(&NodeId::new(node_id));
    }

    /// Clear all mappings
    pub fn clear(&self) {
        self.inner.lock().unwrap().clear();
    }

    /// Get the number of tracked devices
    pub fn device_count(&self) -> u32 {
        self.inner.lock().unwrap().device_count() as u32
    }

    /// Get statistics about tracked mappings
    pub fn stats(&self) -> AddressRotationStats {
        self.inner.lock().unwrap().stats().into()
    }
}

// ============================================================================
// Address Rotation Helper Functions
// ============================================================================

/// Detect the device pattern from a BLE device name
#[uniffi::export]
pub fn detect_device_pattern(name: &str) -> DevicePattern {
    crate::address_rotation::detect_device_pattern(name).into()
}

/// Check if a device name matches a WearTAK/WearOS pattern
#[uniffi::export]
pub fn is_weartak_device(name: &str) -> bool {
    crate::address_rotation::is_weartak_device(name)
}

/// Normalize a WearTAK device name (removes "WT-" prefix if present)
#[uniffi::export]
pub fn normalize_weartak_name(name: &str) -> String {
    crate::address_rotation::normalize_weartak_name(name).to_string()
}

/// Check if a device pattern is known to rotate addresses
#[uniffi::export]
pub fn device_pattern_rotates_addresses(pattern: DevicePattern) -> bool {
    pattern.rotates_addresses()
}

// ============================================================================
// Tests
// ============================================================================

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

    // ==================== Enum round-trip conversions ====================

    #[test]
    fn test_peripheral_type_round_trip() {
        let variants = [
            (PeripheralType::Unknown, InternalPeripheralType::Unknown),
            (
                PeripheralType::SoldierSensor,
                InternalPeripheralType::SoldierSensor,
            ),
            (
                PeripheralType::FixedSensor,
                InternalPeripheralType::FixedSensor,
            ),
            (PeripheralType::Relay, InternalPeripheralType::Relay),
        ];
        for (uniffi_val, internal_val) in &variants {
            let converted: InternalPeripheralType = (*uniffi_val).into();
            assert_eq!(converted, *internal_val);
            let back: PeripheralType = converted.into();
            assert_eq!(back, *uniffi_val);
        }
    }

    #[test]
    fn test_event_type_round_trip() {
        let variants = [
            (EventType::None, InternalEventType::None),
            (EventType::Ping, InternalEventType::Ping),
            (EventType::NeedAssist, InternalEventType::NeedAssist),
            (EventType::Emergency, InternalEventType::Emergency),
            (EventType::Moving, InternalEventType::Moving),
            (EventType::InPosition, InternalEventType::InPosition),
            (EventType::Ack, InternalEventType::Ack),
        ];
        for (uniffi_val, internal_val) in &variants {
            let converted: InternalEventType = (*uniffi_val).into();
            assert_eq!(converted, *internal_val);
            let back: EventType = converted.into();
            assert_eq!(back, *uniffi_val);
        }
    }

    #[test]
    fn test_disconnect_reason_round_trip_observer() {
        let variants = [
            (
                DisconnectReason::LocalRequest,
                ObserverDisconnectReason::LocalRequest,
            ),
            (
                DisconnectReason::RemoteRequest,
                ObserverDisconnectReason::RemoteRequest,
            ),
            (DisconnectReason::Timeout, ObserverDisconnectReason::Timeout),
            (
                DisconnectReason::LinkLoss,
                ObserverDisconnectReason::LinkLoss,
            ),
            (
                DisconnectReason::ConnectionFailed,
                ObserverDisconnectReason::ConnectionFailed,
            ),
            (DisconnectReason::Unknown, ObserverDisconnectReason::Unknown),
        ];
        for (uniffi_val, observer_val) in &variants {
            let converted: ObserverDisconnectReason = (*uniffi_val).into();
            assert_eq!(converted, *observer_val);
            let back: DisconnectReason = converted.into();
            assert_eq!(back, *uniffi_val);
        }
    }

    #[test]
    fn test_disconnect_reason_from_platform() {
        let variants = [
            (
                PlatformDisconnectReason::LocalRequest,
                DisconnectReason::LocalRequest,
            ),
            (
                PlatformDisconnectReason::RemoteRequest,
                DisconnectReason::RemoteRequest,
            ),
            (PlatformDisconnectReason::Timeout, DisconnectReason::Timeout),
            (
                PlatformDisconnectReason::LinkLoss,
                DisconnectReason::LinkLoss,
            ),
            (
                PlatformDisconnectReason::ConnectionFailed,
                DisconnectReason::ConnectionFailed,
            ),
            (PlatformDisconnectReason::Unknown, DisconnectReason::Unknown),
        ];
        for (platform_val, expected) in &variants {
            let converted: DisconnectReason = (*platform_val).into();
            assert_eq!(converted, *expected);
        }
    }

    #[test]
    fn test_connection_state_round_trip() {
        let variants = [
            (
                ConnectionState::Discovered,
                InternalConnectionState::Discovered,
            ),
            (
                ConnectionState::Connecting,
                InternalConnectionState::Connecting,
            ),
            (
                ConnectionState::Connected,
                InternalConnectionState::Connected,
            ),
            (ConnectionState::Degraded, InternalConnectionState::Degraded),
            (
                ConnectionState::Disconnecting,
                InternalConnectionState::Disconnecting,
            ),
            (
                ConnectionState::Disconnected,
                InternalConnectionState::Disconnected,
            ),
            (ConnectionState::Lost, InternalConnectionState::Lost),
        ];
        for (uniffi_val, internal_val) in &variants {
            let converted: InternalConnectionState = (*uniffi_val).into();
            assert_eq!(converted, *internal_val);
            let back: ConnectionState = converted.into();
            assert_eq!(back, *uniffi_val);
        }
    }

    // ==================== event_type_from_u8 ====================

    #[test]
    fn test_event_type_from_u8_valid() {
        assert_eq!(event_type_from_u8(0), Some(EventType::None));
        assert_eq!(event_type_from_u8(1), Some(EventType::Ping));
        assert_eq!(event_type_from_u8(2), Some(EventType::NeedAssist));
        assert_eq!(event_type_from_u8(3), Some(EventType::Emergency));
        assert_eq!(event_type_from_u8(4), Some(EventType::Moving));
        assert_eq!(event_type_from_u8(5), Some(EventType::InPosition));
        assert_eq!(event_type_from_u8(6), Some(EventType::Ack));
    }

    #[test]
    fn test_event_type_from_u8_invalid() {
        assert_eq!(event_type_from_u8(7), None);
        assert_eq!(event_type_from_u8(255), None);
    }

    // ==================== PeatMesh constructors ====================

    #[test]
    fn test_hive_mesh_new() {
        let mesh = PeatMesh::new(42, "ALPHA", "test-mesh");
        assert_eq!(mesh.peer_count(), 0);
        assert_eq!(mesh.connected_count(), 0);
        assert!(!mesh.is_emergency_active());
        assert!(!mesh.is_ack_active());
    }

    #[test]
    fn test_hive_mesh_new_with_peripheral() {
        let mesh = PeatMesh::new_with_peripheral(42, "BRAVO", "test-mesh", PeripheralType::Relay);
        assert_eq!(mesh.peer_count(), 0);
    }

    #[test]
    fn test_hive_mesh_from_genesis() {
        let identity = DeviceIdentity::generate();
        let genesis = MeshGenesis::create("test-network", &identity);
        let mesh = PeatMesh::new_from_genesis("CHARLIE", &identity, &genesis);
        assert!(mesh.has_identity());
        assert!(mesh.is_encryption_enabled());
    }

    // ==================== Namespace functions ====================

    #[test]
    fn test_derive_node_id_from_mac_valid() {
        let id = derive_node_id_from_mac("AA:BB:CC:DD:EE:FF");
        assert_ne!(id, 0);
    }

    #[test]
    fn test_derive_node_id_from_mac_invalid() {
        assert_eq!(derive_node_id_from_mac("not-a-mac"), 0);
        assert_eq!(derive_node_id_from_mac(""), 0);
    }

    #[test]
    fn test_create_peat_mesh_with_encryption_valid() {
        let secret = [0xABu8; 32];
        let mesh = create_peat_mesh_with_encryption(1, "TEST", "mesh-1", &secret);
        assert!(mesh.is_some());
        assert!(mesh.unwrap().is_encryption_enabled());
    }

    #[test]
    fn test_create_peat_mesh_with_encryption_wrong_length() {
        assert!(create_peat_mesh_with_encryption(1, "TEST", "mesh-1", &[0u8; 16]).is_none());
        assert!(create_peat_mesh_with_encryption(1, "TEST", "mesh-1", &[]).is_none());
        assert!(create_peat_mesh_with_encryption(1, "TEST", "mesh-1", &[0u8; 64]).is_none());
    }

    // ==================== DeviceIdentity ====================

    #[test]
    fn test_device_identity_generate() {
        let id = DeviceIdentity::generate();
        assert_eq!(id.get_public_key().len(), 32);
        assert_eq!(id.get_private_key().len(), 32);
        assert_ne!(id.get_node_id(), 0);
    }

    #[test]
    fn test_device_identity_deterministic_node_id() {
        let id = DeviceIdentity::generate();
        let node_id_1 = id.get_node_id();
        let node_id_2 = id.get_node_id();
        assert_eq!(node_id_1, node_id_2);
    }

    #[test]
    fn test_device_identity_sign_and_attestation() {
        let id = DeviceIdentity::generate();
        let sig = id.sign(b"test message");
        assert_eq!(sig.len(), 64);

        let attestation = id.create_attestation(1000);
        assert!(!attestation.is_empty());
    }

    #[test]
    fn test_restore_device_identity_round_trip() {
        let id = DeviceIdentity::generate();
        let private_key = id.get_private_key();
        let restored = restore_device_identity(&private_key);
        assert!(restored.is_some());
        let restored = restored.unwrap();
        assert_eq!(restored.get_public_key(), id.get_public_key());
        assert_eq!(restored.get_node_id(), id.get_node_id());
    }

    #[test]
    fn test_restore_device_identity_invalid() {
        assert!(restore_device_identity(&[]).is_none());
        assert!(restore_device_identity(&[0u8; 16]).is_none());
    }

    // ==================== MeshGenesis ====================

    #[test]
    fn test_mesh_genesis_create() {
        let identity = DeviceIdentity::generate();
        let genesis = MeshGenesis::create("my-mesh", &identity);
        assert!(!genesis.get_mesh_id().is_empty());
        assert_eq!(genesis.get_encryption_secret().len(), 32);
    }

    #[test]
    fn test_mesh_genesis_encode_decode_round_trip() {
        let identity = DeviceIdentity::generate();
        let genesis = MeshGenesis::create("round-trip-mesh", &identity);
        let encoded = genesis.encode();
        assert!(!encoded.is_empty());

        let decoded = decode_mesh_genesis(&encoded);
        assert!(decoded.is_some());
        let decoded = decoded.unwrap();
        assert_eq!(decoded.get_mesh_id(), genesis.get_mesh_id());
        assert_eq!(
            decoded.get_encryption_secret(),
            genesis.get_encryption_secret()
        );
    }

    #[test]
    fn test_decode_mesh_genesis_invalid() {
        assert!(decode_mesh_genesis(&[]).is_none());
        assert!(decode_mesh_genesis(&[0xFF; 10]).is_none());
    }

    // ==================== IdentityAttestation ====================

    #[test]
    fn test_identity_attestation_round_trip() {
        let identity = DeviceIdentity::generate();
        let attestation_bytes = identity.create_attestation(5000);
        let attestation = decode_identity_attestation(&attestation_bytes);
        assert!(attestation.is_some());
        let attestation = attestation.unwrap();
        assert!(attestation.verify());
        assert_eq!(attestation.get_node_id(), identity.get_node_id());
        assert_eq!(attestation.get_public_key(), identity.get_public_key());
    }

    #[test]
    fn test_decode_identity_attestation_invalid() {
        assert!(decode_identity_attestation(&[]).is_none());
        assert!(decode_identity_attestation(&[0xFF; 10]).is_none());
    }

    // ==================== HiveMesh identity operations ====================

    #[test]
    fn test_hive_mesh_identity_verify_peer() {
        let id_a = DeviceIdentity::generate();
        let genesis = MeshGenesis::create("id-test", &id_a);
        let mesh_a = PeatMesh::new_from_genesis("ALPHA", &id_a, &genesis);

        let id_b = DeviceIdentity::generate();
        let attestation_bytes = id_b.create_attestation(1000);

        let initial_count = mesh_a.known_identity_count();

        // Verify peer identity via the mesh
        assert!(mesh_a.verify_peer_identity(&attestation_bytes));
        assert!(mesh_a.is_peer_identity_known(id_b.get_node_id()));
        assert_eq!(mesh_a.known_identity_count(), initial_count + 1);
    }

    #[test]
    fn test_hive_mesh_verify_peer_identity_invalid() {
        let id = DeviceIdentity::generate();
        let genesis = MeshGenesis::create("test", &id);
        let mesh = PeatMesh::new_from_genesis("TEST", &id, &genesis);
        assert!(!mesh.verify_peer_identity(&[]));
        assert!(!mesh.verify_peer_identity(&[0xFF; 10]));
    }

    #[test]
    fn test_hive_mesh_sign_and_verify() {
        let id_a = DeviceIdentity::generate();
        let genesis = MeshGenesis::create("sig-test", &id_a);
        let mesh = PeatMesh::new_from_genesis("ALPHA", &id_a, &genesis);

        let message = b"important data";
        let signature = mesh.sign(message);
        assert!(signature.is_some());
        let signature = signature.unwrap();
        assert_eq!(signature.len(), 64);
    }

    #[test]
    fn test_hive_mesh_verify_peer_signature_wrong_length() {
        let id = DeviceIdentity::generate();
        let genesis = MeshGenesis::create("test", &id);
        let mesh = PeatMesh::new_from_genesis("TEST", &id, &genesis);
        // Wrong signature length should return false
        assert!(!mesh.verify_peer_signature(42, b"msg", &[0u8; 32]));
        assert!(!mesh.verify_peer_signature(42, b"msg", &[]));
    }

    // ==================== HiveMesh data operations ====================

    #[test]
    fn test_hive_mesh_build_document() {
        let mesh = PeatMesh::new(1, "TEST", "mesh");
        let doc = mesh.build_document();
        assert!(!doc.is_empty());
    }

    #[test]
    fn test_hive_mesh_emergency_cycle() {
        let mesh = PeatMesh::new(1, "TEST", "mesh");
        assert!(!mesh.is_emergency_active());

        let data = mesh.send_emergency(1000);
        assert!(!data.is_empty());
        assert!(mesh.is_emergency_active());

        let ack_data = mesh.send_ack(2000);
        assert!(!ack_data.is_empty());
        assert!(mesh.is_ack_active());
    }

    #[test]
    fn test_hive_mesh_update_location() {
        let mesh = PeatMesh::new(1, "TEST", "mesh");
        mesh.update_location(37.7749, -122.4194, Some(10.0));
        mesh.clear_location();
        // No panic = success
    }

    #[test]
    fn test_hive_mesh_update_peripheral_state() {
        let mesh = PeatMesh::new(1, "TEST", "mesh");
        mesh.update_peripheral_state(
            "ALPHA",
            85,
            Some(72),
            Some(37.7749),
            Some(-122.4194),
            Some(10.0),
            Some(EventType::Moving),
            1000,
        );
        // No panic = success
    }

    #[test]
    fn test_hive_mesh_matches_mesh() {
        let mesh = PeatMesh::new(1, "TEST", "my-mesh");
        assert!(mesh.matches_mesh(Some("my-mesh".to_string())));
        assert!(!mesh.matches_mesh(Some("other-mesh".to_string())));
    }

    #[test]
    fn test_hive_mesh_peer_not_known() {
        let mesh = PeatMesh::new(1, "TEST", "mesh");
        assert!(!mesh.is_peer_known(999));
        assert!(mesh.get_peer_callsign(999).is_none());
        assert!(mesh.get_peer_connection_state(999).is_none());
    }

    #[test]
    fn test_hive_mesh_empty_peer_lists() {
        let mesh = PeatMesh::new(1, "TEST", "mesh");
        assert!(mesh.get_connected_peers().is_empty());
        assert!(mesh.get_degraded_peers().is_empty());
        assert!(mesh.get_lost_peers().is_empty());
        assert!(mesh.get_indirect_peers().is_empty());
        assert!(mesh.get_connected_peer_identifiers().is_empty());
    }

    #[test]
    fn test_hive_mesh_state_counts_initial() {
        let mesh = PeatMesh::new(1, "TEST", "mesh");
        let counts = mesh.get_connection_state_counts();
        assert_eq!(counts.discovered, 0);
        assert_eq!(counts.connected, 0);
        assert_eq!(counts.lost, 0);

        let full = mesh.get_full_state_counts();
        assert_eq!(full.direct.connected, 0);
        assert_eq!(full.one_hop, 0);
    }

    #[test]
    fn test_hive_mesh_tick_returns_none_initially() {
        let mesh = PeatMesh::new(1, "TEST", "mesh");
        // First tick with no peers should return None
        assert!(mesh.tick(1000).is_none());
    }

    #[test]
    fn test_hive_mesh_delta_document() {
        let mesh = PeatMesh::new(1, "TEST", "mesh");
        // Delta document for unknown peer still returns data (full state)
        let delta = mesh.build_delta_document_for_peer(999, 1000);
        assert!(delta.is_some());
        // Full delta should always return something
        let full = mesh.build_full_delta_document(1000);
        assert!(!full.is_empty());
    }

    #[test]
    fn test_hive_mesh_broadcast_bytes() {
        let mesh = PeatMesh::new(1, "TEST", "mesh");
        let result = mesh.broadcast_bytes(b"test payload");
        assert!(!result.is_empty());
    }

    #[test]
    fn test_hive_mesh_canned_message_dedup() {
        let mesh = PeatMesh::new(1, "TEST", "mesh");
        // First check should return true (not seen)
        assert!(mesh.check_canned_message(42, 1000, 5000));
        // Mark as seen
        mesh.mark_canned_message_seen(42, 1000);
        // Second check should return false (already seen)
        assert!(!mesh.check_canned_message(42, 1000, 5000));
    }

    // ==================== ReconnectionManager ====================

    #[test]
    fn test_reconnection_manager_defaults() {
        let mgr = ReconnectionManager::with_defaults();
        assert_eq!(mgr.tracked_count(), 0);
        assert!(mgr.check_interval_ms() > 0);
    }

    #[test]
    fn test_reconnection_manager_track_and_status() {
        let mgr = ReconnectionManager::new(ReconnectionConfig {
            base_delay_ms: 100,
            max_delay_ms: 1000,
            max_attempts: 3,
            check_interval_ms: 500,
            use_flat_delay: false,
            reset_on_exhaustion: false,
        });

        mgr.track_disconnection("AA:BB:CC:DD:EE:FF".to_string());
        assert!(mgr.is_tracked("AA:BB:CC:DD:EE:FF"));
        assert_eq!(mgr.tracked_count(), 1);

        let status = mgr.get_status("AA:BB:CC:DD:EE:FF");
        // Should be either Ready or Waiting
        assert!(matches!(
            status,
            ReconnectionStatus::Ready | ReconnectionStatus::Waiting { .. }
        ));

        assert_eq!(mgr.get_status("unknown"), ReconnectionStatus::NotTracked);
    }

    #[test]
    fn test_reconnection_manager_connection_success() {
        let mgr = ReconnectionManager::with_defaults();
        mgr.track_disconnection("peer-1".to_string());
        assert_eq!(mgr.tracked_count(), 1);
        mgr.on_connection_success("peer-1");
        assert!(!mgr.is_tracked("peer-1"));
    }

    #[test]
    fn test_reconnection_manager_clear() {
        let mgr = ReconnectionManager::with_defaults();
        mgr.track_disconnection("a".to_string());
        mgr.track_disconnection("b".to_string());
        assert_eq!(mgr.tracked_count(), 2);
        mgr.clear();
        assert_eq!(mgr.tracked_count(), 0);
    }

    // ==================== PeerLifetimeManager ====================

    #[test]
    fn test_peer_lifetime_manager_defaults() {
        let mgr = PeerLifetimeManager::with_defaults();
        assert_eq!(mgr.tracked_count(), 0);
        assert!(mgr.cleanup_interval_ms() > 0);
    }

    #[test]
    fn test_peer_lifetime_manager_track_peer() {
        let mgr = PeerLifetimeManager::with_defaults();
        mgr.on_peer_activity("peer-1", true);
        assert!(mgr.is_tracked("peer-1"));
        assert!(mgr.is_connected("peer-1"));
        assert_eq!(mgr.tracked_count(), 1);

        let stats = mgr.stats();
        assert_eq!(stats.total_tracked, 1);
        assert_eq!(stats.connected, 1);
        assert_eq!(stats.disconnected, 0);
    }

    #[test]
    fn test_peer_lifetime_manager_disconnect() {
        let mgr = PeerLifetimeManager::with_defaults();
        mgr.on_peer_activity("peer-1", true);
        mgr.on_peer_disconnected("peer-1");
        assert!(mgr.is_tracked("peer-1"));
        assert!(!mgr.is_connected("peer-1"));
    }

    #[test]
    fn test_peer_lifetime_manager_remove() {
        let mgr = PeerLifetimeManager::with_defaults();
        mgr.on_peer_activity("peer-1", true);
        assert!(mgr.remove_peer("peer-1"));
        assert!(!mgr.is_tracked("peer-1"));
        assert!(!mgr.remove_peer("peer-1")); // already removed
    }

    #[test]
    fn test_peer_lifetime_manager_clear() {
        let mgr = PeerLifetimeManager::with_defaults();
        mgr.on_peer_activity("a", true);
        mgr.on_peer_activity("b", false);
        mgr.clear();
        assert_eq!(mgr.tracked_count(), 0);
    }

    // ==================== AddressRotationHandler ====================

    #[test]
    fn test_address_rotation_handler_register_and_lookup() {
        let handler = AddressRotationHandler::new();
        handler.register_device("WT-WEAROS-1234", "AA:BB:CC:DD:EE:FF", 42);
        assert_eq!(handler.lookup_by_name("WT-WEAROS-1234"), Some(42));
        assert_eq!(handler.lookup_by_address("AA:BB:CC:DD:EE:FF"), Some(42));
        assert_eq!(
            handler.get_address(42),
            Some("AA:BB:CC:DD:EE:FF".to_string())
        );
        assert_eq!(handler.get_name(42), Some("WT-WEAROS-1234".to_string()));
    }

    #[test]
    fn test_address_rotation_handler_unknown_lookups() {
        let handler = AddressRotationHandler::new();
        assert!(handler.lookup_by_name("unknown").is_none());
        assert!(handler.lookup_by_address("00:00:00:00:00:00").is_none());
        assert!(handler.get_address(999).is_none());
        assert!(handler.get_name(999).is_none());
    }

    #[test]
    fn test_address_rotation_handler_remove_and_clear() {
        let handler = AddressRotationHandler::new();
        handler.register_device("dev-1", "addr-1", 1);
        handler.register_device("dev-2", "addr-2", 2);
        assert_eq!(handler.device_count(), 2);

        handler.remove_device(1);
        assert!(handler.lookup_by_name("dev-1").is_none());

        handler.clear();
        assert_eq!(handler.device_count(), 0);
    }

    // ==================== Namespace helper functions ====================

    #[test]
    fn test_detect_device_pattern_weartak() {
        assert_eq!(
            detect_device_pattern("WT-WEAROS-1234"),
            DevicePattern::WearTak
        );
    }

    #[test]
    fn test_is_weartak_device_fn() {
        assert!(is_weartak_device("WT-WEAROS-1234"));
        assert!(!is_weartak_device("SomeOtherDevice"));
    }

    #[test]
    fn test_device_pattern_rotates() {
        assert!(device_pattern_rotates_addresses(DevicePattern::WearTak));
        assert!(device_pattern_rotates_addresses(DevicePattern::WearOs));
        assert!(!device_pattern_rotates_addresses(DevicePattern::Peat));
        assert!(!device_pattern_rotates_addresses(DevicePattern::Unknown));
    }

    // ==================== BLE callback handling ====================

    #[test]
    fn test_hive_mesh_on_ble_discovered() {
        let mesh = PeatMesh::new(1, "TEST", "my-mesh");
        // Name must be "PEAT_MESH-XXXXXXXX" format to parse node ID
        let peer = mesh.on_ble_discovered(
            "AA:BB:CC:DD:EE:FF",
            Some("PEAT_MESH-00000002".to_string()),
            -50,
            Some("my-mesh".to_string()),
            1000,
        );
        assert!(peer.is_some());
        let peer = peer.unwrap();
        assert_eq!(peer.identifier, "AA:BB:CC:DD:EE:FF");
        assert_eq!(peer.rssi, -50);
    }

    #[test]
    fn test_hive_mesh_on_ble_discovered_no_name() {
        let mesh = PeatMesh::new(1, "TEST", "my-mesh");
        // No name means node ID can't be parsed, so None returned
        let peer = mesh.on_ble_discovered(
            "AA:BB:CC:DD:EE:FF",
            None,
            -70,
            Some("my-mesh".to_string()),
            1000,
        );
        assert!(peer.is_none());
    }

    #[test]
    fn test_hive_mesh_on_ble_discovered_wrong_mesh() {
        let mesh = PeatMesh::new(1, "TEST", "my-mesh");
        let peer = mesh.on_ble_discovered(
            "AA:BB:CC:DD:EE:FF",
            Some("PEAT_MESH-00000002".to_string()),
            -50,
            Some("other-mesh".to_string()),
            1000,
        );
        assert!(peer.is_none());
    }

    #[test]
    fn test_hive_mesh_on_ble_disconnected_unknown_peer() {
        let mesh = PeatMesh::new(1, "TEST", "mesh");
        let result = mesh.on_ble_disconnected("unknown-addr", DisconnectReason::Timeout);
        assert!(result.is_none());
    }

    #[test]
    fn test_hive_mesh_on_ble_data_received_invalid() {
        let mesh = PeatMesh::new(1, "TEST", "mesh");
        // No peer registered for this identifier
        let result = mesh.on_ble_data_received("unknown", &[0xFF; 10], 1000);
        assert!(result.is_none());
    }

    #[test]
    fn test_hive_mesh_decrypt_only_no_encryption() {
        let mesh = PeatMesh::new(1, "TEST", "mesh");
        // Without encryption, decrypt_only should return None or the data
        let result = mesh.decrypt_only(&[0x01, 0x02, 0x03]);
        // Depends on implementation - just ensure no panic
        let _ = result;
    }

    // ==================== Encrypted mesh data flow ====================

    #[test]
    fn test_encrypted_mesh_document_round_trip() {
        let id_a = DeviceIdentity::generate();
        let genesis = MeshGenesis::create("enc-test", &id_a);
        let mesh_a = PeatMesh::new_from_genesis("ALPHA", &id_a, &genesis);

        let id_b = DeviceIdentity::generate();
        let secret = genesis.get_encryption_secret();
        let mesh_b = create_peat_mesh_with_encryption(
            id_b.get_node_id(),
            "BRAVO",
            &genesis.get_mesh_id(),
            &secret,
        )
        .expect("should create encrypted mesh");

        // Build document from A
        let doc = mesh_a.build_document();
        assert!(!doc.is_empty());

        // B should be able to decrypt it
        let decrypted = mesh_b.decrypt_only(&doc);
        assert!(decrypted.is_some());
    }
}