pvxs-sys 0.1.1

Low-level FFI bindings for EPICS PVXS library
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
// Copyright 2026 Tine Zata
// SPDX-License-Identifier: MPL-2.0
use crossbeam_channel as channel;
use cxx::UniquePtr;
use std::collections::HashMap;
use std::thread;

use crate::{
    bridge, compute_alarm_for_scalar, AlarmConfig, AlarmMetadata, AlarmSeverity, AlarmStatus,
    ControlMetadata, DisplayMetadata, PvxsError, Result, Value,
};

/// Internal server implementation
///
/// Low-level server that manages PVs without automatic alarm handling.
/// Users should typically use the `Server` type instead, which provides
/// managed PVs with automatic alarm and validation logic.
pub(crate) struct ServerImpl {
    inner: UniquePtr<bridge::ServerWrapper>,
}

impl ServerImpl {
    /// Create a server from environment variables
    ///
    /// Reads configuration from EPICS environment variables for network setup.
    ///
    /// # Errors
    ///
    /// Returns an error if the server cannot be created or configured.
    pub fn from_env() -> Result<Self> {
        let inner = bridge::server_create_from_env()?;
        Ok(Self { inner })
    }

    /// Create an isolated server for testing
    ///
    /// Creates a server that operates in isolation, using system-assigned ports
    /// and avoiding conflicts with other servers. Ideal for unit tests.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use pvxs_sys::server::ServerImpl;
    ///
    /// let server = ServerImpl::start_isolated()?;
    /// println!("Isolated server started on TCP port {}", server.tcp_port());
    /// server.stop_drop()?;
    /// # Ok::<(), pvxs_sys::PvxsError>(())
    /// ```
    pub fn create_isolated() -> Result<Self> {
        let inner = bridge::server_create_isolated()?;
        Ok(Self { inner })
    }

    /// Start the server
    ///
    /// Begins listening for client connections and serving PVs.
    ///
    /// # Errors
    ///
    /// Returns an error if the server cannot be started (e.g., port conflicts).
    pub fn start(&mut self) -> Result<()> {
        bridge::server_start(self.inner.pin_mut())?;
        Ok(())
    }

    /// Stop the server
    ///
    /// Stops listening for connections and shuts down the server.
    ///
    /// # Errors
    ///
    /// Returns an error if the server cannot be stopped cleanly.
    pub fn stop(&mut self) -> Result<()> {
        bridge::server_stop(self.inner.pin_mut())?;
        Ok(())
    }

    /// Add a PV to the server (internal use only)
    ///
    /// Makes a process variable available to clients under the given name.
    /// This is now internal - use create_pv_* methods instead.
    ///
    /// # Arguments
    ///
    /// * `name` - The PV name that clients will use
    /// * `pv` - The SharedPV to add
    pub(crate) fn add_pv(&mut self, name: &str, pv: &mut SharedPV) -> Result<()> {
        bridge::server_add_pv(self.inner.pin_mut(), name.to_string(), pv.inner.pin_mut())?;
        Ok(())
    }

    /// Remove a PV from the server
    ///
    /// Removes the PV with the given name from the server.
    ///
    /// # Arguments
    ///
    /// * `name` - The name of the PV to remove
    pub fn remove_pv(&mut self, name: &str) -> Result<()> {
        bridge::server_remove_pv(self.inner.pin_mut(), name.to_string())?;
        Ok(())
    }

    // TODO: TZ: Review later if needed
    /*
    /// Add a static source to the server
    ///
    /// Static sources provide collections of PVs with a common configuration.
    ///
    /// # Arguments
    ///
    /// * `name` - Name for this source
    /// * `source` - The StaticSource to add
    /// * `order` - Priority order (lower numbers have higher priority)
    pub fn add_source(&mut self, name: &str, source: &mut StaticSource, order: i32) -> Result<()> {
        bridge::server_add_source(self.inner.pin_mut(), name.to_string(), source.inner.pin_mut(), order)?;
        Ok(())
    }*/

    /// Get the TCP port the server is listening on
    ///
    /// Returns 0 if the server is not started.
    pub fn tcp_port(&self) -> u16 {
        bridge::server_get_tcp_port(&self.inner)
    }

    /// Get the UDP port the server is using
    ///
    /// Returns 0 if the server is not started.
    pub fn udp_port(&self) -> u16 {
        bridge::server_get_udp_port(&self.inner)
    }

    /// Create and add a new mailbox SharedPV with a double value and metadata
    ///
    /// Mailbox PVs allow both reading and writing by clients.
    /// The PV is automatically added to the server with the given name.
    ///
    /// # Arguments
    ///
    /// * `name` - The PV name that clients will use
    /// * `initial_value` - Initial value for the PV
    /// * `metadata` - Metadata for the scalar PV
    ///
    /// # Example
    ///
    /// ```no_run
    /// # use pvxs_sys::{Server, NTScalarMetadataBuilder};
    /// # let mut server = Server::start_isolated().unwrap();
    /// let pv = server.create_pv_double("test:double", 42.5, NTScalarMetadataBuilder::new())?;
    /// # Ok::<(), pvxs_sys::PvxsError>(())
    /// ```
    pub fn create_pv_double(
        &mut self,
        name: &str,
        initial_value: f64,
        metadata: NTScalarMetadataBuilder,
    ) -> Result<SharedPV> {
        let mut pv = SharedPV::create_mailbox()?;
        pv.open_double(initial_value, metadata)?;
        self.add_pv(name, &mut pv)?;
        Ok(pv)
    }

    /// Create and add a new mailbox SharedPV with a double array value and metadata
    ///
    /// Create should fail if array is empty.
    /// The PV is automatically added to the server with the given name.
    ///
    /// # Arguments
    ///
    /// * `name` - The PV name that clients will use
    /// * `initial_value` - Initial array value for the PV
    /// * `metadata` - Metadata for the scalar array PV
    pub fn create_pv_double_array(
        &mut self,
        name: &str,
        initial_value: Vec<f64>,
        metadata: NTScalarMetadataBuilder,
    ) -> Result<SharedPV> {
        if initial_value.is_empty() {
            return Err(PvxsError::new("Initial double array cannot be empty"));
        }
        let mut pv = SharedPV::create_mailbox()?;
        pv.open_double_array(initial_value, metadata)?;
        self.add_pv(name, &mut pv)?;
        Ok(pv)
    }

    /// Create and add a new mailbox SharedPV with an int32 value and metadata
    ///
    /// The PV is automatically added to the server with the given name.
    ///
    /// # Arguments
    ///
    /// * `name` - The PV name that clients will use
    /// * `initial_value` - Initial value for the PV
    /// * `metadata` - Metadata for the scalar PV
    pub fn create_pv_int32(
        &mut self,
        name: &str,
        initial_value: i32,
        metadata: NTScalarMetadataBuilder,
    ) -> Result<SharedPV> {
        let mut pv = SharedPV::create_mailbox()?;
        pv.open_int32(initial_value, metadata)?;
        self.add_pv(name, &mut pv)?;
        Ok(pv)
    }

    /// Create and add a new mailbox SharedPV with an int32 array value and metadata
    ///
    /// Create should fail if array is empty.
    /// The PV is automatically added to the server with the given name.
    ///
    /// # Arguments
    ///
    /// * `name` - The PV name that clients will use
    /// * `initial_value` - Initial array value for the PV
    /// * `metadata` - Metadata for the array PV
    pub fn create_pv_int32_array(
        &mut self,
        name: &str,
        initial_value: Vec<i32>,
        metadata: NTScalarMetadataBuilder,
    ) -> Result<SharedPV> {
        if initial_value.is_empty() {
            return Err(PvxsError::new("Initial int32 array cannot be empty"));
        }
        let mut pv = SharedPV::create_mailbox()?;
        pv.open_int32_array(initial_value, metadata)?;
        self.add_pv(name, &mut pv)?;
        Ok(pv)
    }

    /// Create and add a new mailbox SharedPV with a string value and metadata
    ///
    /// The PV is automatically added to the server with the given name.
    ///
    /// # Arguments
    ///
    /// * `name` - The PV name that clients will use
    /// * `initial_value` - Initial value for the PV
    /// * `metadata` - Metadata for the string PV
    pub fn create_pv_string(
        &mut self,
        name: &str,
        initial_value: &str,
        metadata: NTScalarMetadataBuilder,
    ) -> Result<SharedPV> {
        let mut pv = SharedPV::create_mailbox()?;
        pv.open_string(initial_value, metadata)?;
        self.add_pv(name, &mut pv)?;
        Ok(pv)
    }

    /// Create and add a new mailbox SharedPV with a string array value and metadata
    ///
    /// Create should fail if array is empty.
    /// The PV is automatically added to the server with the given name.
    ///
    /// # Arguments
    ///
    /// * `name` - The PV name that clients will use
    /// * `initial_value` - Initial array value for the PV
    /// * `metadata` - Metadata for the string array PV
    pub fn create_pv_string_array(
        &mut self,
        name: &str,
        initial_value: Vec<String>,
        metadata: NTScalarMetadataBuilder,
    ) -> Result<SharedPV> {
        if initial_value.is_empty() {
            return Err(PvxsError::new("Initial string array cannot be empty"));
        }
        let mut pv = SharedPV::create_mailbox()?;
        pv.open_string_array(initial_value, metadata)?;
        self.add_pv(name, &mut pv)?;
        Ok(pv)
    }

    /// Create and add a new mailbox SharedPV with an enum value and metadata
    ///
    /// The PV is automatically added to the server with the given name.
    ///
    /// # Arguments
    ///
    /// * `name` - The PV name that clients will use
    /// * `choices` - List of string choices for the enum
    /// * `selected_index` - Initial selected index (0-based)
    /// * `metadata` - Metadata for the enum PV
    pub fn create_pv_enum(
        &mut self,
        name: &str,
        choices: Vec<&str>,
        selected_index: i16,
        metadata: NTEnumMetadataBuilder,
    ) -> Result<SharedPV> {
        let mut pv = SharedPV::create_mailbox()?;
        pv.open_enum(choices, selected_index, metadata)?;
        self.add_pv(name, &mut pv)?;
        Ok(pv)
    }

    // TODO: TZ - template for readonly PVs if needed in the future
    /*
    /// Create and add a new readonly SharedPV with a double value and metadata
    ///
    /// Readonly PVs only allow reading by clients.
    /// The PV is automatically added to the server with the given name.
    ///
    /// # Arguments
    ///
    /// * `name` - The PV name that clients will use
    /// * `initial_value` - Initial value for the PV
    /// * `metadata` - Metadata for the scalar PV
    pub fn create_readonly_pv_double(&mut self, name: &str, initial_value: f64, metadata: NTScalarMetadataBuilder) -> Result<SharedPV> {
        let mut pv = SharedPV::create_readonly()?;
        pv.open_double(initial_value, metadata)?;
        self.add_pv(name, &mut pv)?;
        Ok(pv)
    }*/
}

/// Fetched double value with alarm information
#[derive(Debug, Clone)]
pub struct FetchedDouble {
    pub value: f64,
    pub alarm_severity: AlarmSeverity,
    pub alarm_status: AlarmStatus,
    pub alarm_message: String,
    pub display_metadata: Option<DisplayMetadata>,
    pub control_metadata: Option<ControlMetadata>,
    pub alarm_metadata: Option<AlarmMetadata>,
}

/// Fetched int32 value with alarm information
#[derive(Debug, Clone)]
pub struct FetchedInt32 {
    pub value: i32,
    pub alarm_severity: AlarmSeverity,
    pub alarm_status: AlarmStatus,
    pub alarm_message: String,
    pub display_metadata: Option<DisplayMetadata>,
    pub control_metadata: Option<ControlMetadata>,
    pub alarm_metadata: Option<AlarmMetadata>,
}

/// Fetched string value with alarm information
#[derive(Debug, Clone)]
pub struct FetchedString {
    pub value: String,
    pub alarm_severity: AlarmSeverity,
    pub alarm_status: AlarmStatus,
    pub alarm_message: String,
}

/// Fetched double array value with alarm information
#[derive(Debug, Clone)]
pub struct FetchedDoubleArray {
    pub value: Vec<f64>,
    pub alarm_severity: AlarmSeverity,
    pub alarm_status: AlarmStatus,
    pub alarm_message: String,
    pub display_metadata: Option<DisplayMetadata>,
    pub control_metadata: Option<ControlMetadata>,
    pub alarm_metadata: Option<AlarmMetadata>,
}

/// Fetched int32 array value with alarm information
#[derive(Debug, Clone)]
pub struct FetchedInt32Array {
    pub value: Vec<i32>,
    pub alarm_severity: AlarmSeverity,
    pub alarm_status: AlarmStatus,
    pub alarm_message: String,
    pub display_metadata: Option<DisplayMetadata>,
    pub control_metadata: Option<ControlMetadata>,
    pub alarm_metadata: Option<AlarmMetadata>,
}

/// Fetched string array value with alarm information
#[derive(Debug, Clone)]
pub struct FetchedStringArray {
    pub value: Vec<String>,
    pub alarm_severity: AlarmSeverity,
    pub alarm_status: AlarmStatus,
    pub alarm_message: String,
}

/// Fetched enum value with alarm information
#[derive(Debug, Clone)]
pub struct FetchedEnum {
    pub value: i16,
    pub value_choices: Vec<String>,
    pub alarm_severity: AlarmSeverity,
    pub alarm_status: AlarmStatus,
    pub alarm_message: String,
}

enum ManagerCommand {
    CreateDouble {
        name: String,
        initial: f64,
        metadata: NTScalarMetadataBuilder,
        reply: channel::Sender<Result<()>>,
    },
    CreateDoubleArray {
        name: String,
        initial: Vec<f64>,
        metadata: NTScalarMetadataBuilder,
        reply: channel::Sender<Result<()>>,
    },
    CreateInt32 {
        name: String,
        initial: i32,
        metadata: NTScalarMetadataBuilder,
        reply: channel::Sender<Result<()>>,
    },
    CreateInt32Array {
        name: String,
        initial: Vec<i32>,
        metadata: NTScalarMetadataBuilder,
        reply: channel::Sender<Result<()>>,
    },
    CreateString {
        name: String,
        initial: String,
        metadata: NTScalarMetadataBuilder,
        reply: channel::Sender<Result<()>>,
    },
    CreateStringArray {
        name: String,
        initial: Vec<String>,
        metadata: NTScalarMetadataBuilder,
        reply: channel::Sender<Result<()>>,
    },
    CreateEnum {
        name: String,
        choices: Vec<String>,
        selected_index: i16,
        metadata: NTEnumMetadataBuilder,
        reply: channel::Sender<Result<()>>,
    },
    PostDouble {
        name: String,
        value: f64,
        reply: channel::Sender<Result<()>>,
    },
    PostDoubleArray {
        name: String,
        value: Vec<f64>,
        reply: channel::Sender<Result<()>>,
    },
    PostInt32 {
        name: String,
        value: i32,
        reply: channel::Sender<Result<()>>,
    },
    PostInt32Array {
        name: String,
        value: Vec<i32>,
        reply: channel::Sender<Result<()>>,
    },
    PostString {
        name: String,
        value: String,
        reply: channel::Sender<Result<()>>,
    },
    PostStringArray {
        name: String,
        value: Vec<String>,
        reply: channel::Sender<Result<()>>,
    },
    PostEnum {
        name: String,
        value: i16,
        reply: channel::Sender<Result<()>>,
    },
    Remove {
        name: String,
        reply: channel::Sender<Result<()>>,
    },
    FetchDouble {
        name: String,
        reply: channel::Sender<Result<FetchedDouble>>,
    },
    FetchInt32 {
        name: String,
        reply: channel::Sender<Result<FetchedInt32>>,
    },
    FetchString {
        name: String,
        reply: channel::Sender<Result<FetchedString>>,
    },
    FetchDoubleArray {
        name: String,
        reply: channel::Sender<Result<FetchedDoubleArray>>,
    },
    FetchInt32Array {
        name: String,
        reply: channel::Sender<Result<FetchedInt32Array>>,
    },
    FetchStringArray {
        name: String,
        reply: channel::Sender<Result<FetchedStringArray>>,
    },
    FetchEnum {
        name: String,
        reply: channel::Sender<Result<FetchedEnum>>,
    },
    Stop {
        reply: channel::Sender<Result<()>>,
    },
}

enum ManagedPv {
    Double {
        pv: SharedPV,
        alarm: AlarmConfig,
        last: f64,
    },
    DoubleArray(SharedPV),
    Int32 {
        pv: SharedPV,
        alarm: AlarmConfig,
        last: i32,
    },
    Int32Array(SharedPV),
    String(SharedPV),
    StringArray(SharedPV),
    PvEnum(SharedPV),
}

/// Handle to a running PVXS server
///
/// Provides methods to interact with a running server without blocking.
/// Can be cloned and shared across threads.
#[derive(Clone)]
pub struct ServerHandle {
    tx: channel::Sender<ManagerCommand>,
    tcp_port: u16,
    udp_port: u16,
}

impl ServerHandle {
    pub fn tcp_port(&self) -> u16 {
        self.tcp_port
    }

    pub fn udp_port(&self) -> u16 {
        self.udp_port
    }

    pub fn create_pv_double(
        &self,
        name: &str,
        initial: f64,
        metadata: NTScalarMetadataBuilder,
    ) -> Result<()> {
        let (reply_tx, reply_rx) = channel::bounded(1);
        self.tx
            .send(ManagerCommand::CreateDouble {
                name: name.to_string(),
                initial,
                metadata,
                reply: reply_tx,
            })
            .map_err(|_| PvxsError::new("Server worker stopped"))?;
        reply_rx
            .recv()
            .map_err(|_| PvxsError::new("Server worker stopped"))?
    }

    pub fn create_pv_double_array(
        &self,
        name: &str,
        initial: Vec<f64>,
        metadata: NTScalarMetadataBuilder,
    ) -> Result<()> {
        let (reply_tx, reply_rx) = channel::bounded(1);
        self.tx
            .send(ManagerCommand::CreateDoubleArray {
                name: name.to_string(),
                initial,
                metadata,
                reply: reply_tx,
            })
            .map_err(|_| PvxsError::new("Server worker stopped"))?;
        reply_rx
            .recv()
            .map_err(|_| PvxsError::new("Server worker stopped"))?
    }

    pub fn create_pv_int32(
        &self,
        name: &str,
        initial: i32,
        metadata: NTScalarMetadataBuilder,
    ) -> Result<()> {
        let (reply_tx, reply_rx) = channel::bounded(1);
        self.tx
            .send(ManagerCommand::CreateInt32 {
                name: name.to_string(),
                initial,
                metadata,
                reply: reply_tx,
            })
            .map_err(|_| PvxsError::new("Server worker stopped"))?;
        reply_rx
            .recv()
            .map_err(|_| PvxsError::new("Server worker stopped"))?
    }

    pub fn create_pv_int32_array(
        &self,
        name: &str,
        initial: Vec<i32>,
        metadata: NTScalarMetadataBuilder,
    ) -> Result<()> {
        let (reply_tx, reply_rx) = channel::bounded(1);
        self.tx
            .send(ManagerCommand::CreateInt32Array {
                name: name.to_string(),
                initial,
                metadata,
                reply: reply_tx,
            })
            .map_err(|_| PvxsError::new("Server worker stopped"))?;
        reply_rx
            .recv()
            .map_err(|_| PvxsError::new("Server worker stopped"))?
    }

    pub fn create_pv_string(
        &self,
        name: &str,
        initial: &str,
        metadata: NTScalarMetadataBuilder,
    ) -> Result<()> {
        let (reply_tx, reply_rx) = channel::bounded(1);
        self.tx
            .send(ManagerCommand::CreateString {
                name: name.to_string(),
                initial: initial.to_string(),
                metadata,
                reply: reply_tx,
            })
            .map_err(|_| PvxsError::new("Server worker stopped"))?;
        reply_rx
            .recv()
            .map_err(|_| PvxsError::new("Server worker stopped"))?
    }

    pub fn create_pv_string_array(
        &self,
        name: &str,
        initial: Vec<String>,
        metadata: NTScalarMetadataBuilder,
    ) -> Result<()> {
        let (reply_tx, reply_rx) = channel::bounded(1);
        self.tx
            .send(ManagerCommand::CreateStringArray {
                name: name.to_string(),
                initial,
                metadata,
                reply: reply_tx,
            })
            .map_err(|_| PvxsError::new("Server worker stopped"))?;
        reply_rx
            .recv()
            .map_err(|_| PvxsError::new("Server worker stopped"))?
    }

    pub fn create_pv_enum(
        &self,
        name: &str,
        choices: Vec<&str>,
        selected_index: i16,
        metadata: NTEnumMetadataBuilder,
    ) -> Result<()> {
        let (reply_tx, reply_rx) = channel::bounded(1);
        self.tx
            .send(ManagerCommand::CreateEnum {
                name: name.to_string(),
                choices: choices.iter().map(|s| s.to_string()).collect(),
                selected_index,
                metadata,
                reply: reply_tx,
            })
            .map_err(|_| PvxsError::new("Server worker stopped"))?;
        reply_rx
            .recv()
            .map_err(|_| PvxsError::new("Server worker stopped"))?
    }

    pub fn post_double(&self, name: &str, value: f64) -> Result<()> {
        let (reply_tx, reply_rx) = channel::bounded(1);
        self.tx
            .send(ManagerCommand::PostDouble {
                name: name.to_string(),
                value,
                reply: reply_tx,
            })
            .map_err(|_| PvxsError::new("Server worker stopped"))?;
        reply_rx
            .recv()
            .map_err(|_| PvxsError::new("Server worker stopped"))?
    }

    pub fn post_double_array(&self, name: &str, value: Vec<f64>) -> Result<()> {
        let (reply_tx, reply_rx) = channel::bounded(1);
        self.tx
            .send(ManagerCommand::PostDoubleArray {
                name: name.to_string(),
                value,
                reply: reply_tx,
            })
            .map_err(|_| PvxsError::new("Server worker stopped"))?;
        reply_rx
            .recv()
            .map_err(|_| PvxsError::new("Server worker stopped"))?
    }

    pub fn post_int32(&self, name: &str, value: i32) -> Result<()> {
        let (reply_tx, reply_rx) = channel::bounded(1);
        self.tx
            .send(ManagerCommand::PostInt32 {
                name: name.to_string(),
                value,
                reply: reply_tx,
            })
            .map_err(|_| PvxsError::new("Server worker stopped"))?;
        reply_rx
            .recv()
            .map_err(|_| PvxsError::new("Server worker stopped"))?
    }

    pub fn post_int32_array(&self, name: &str, value: Vec<i32>) -> Result<()> {
        let (reply_tx, reply_rx) = channel::bounded(1);
        self.tx
            .send(ManagerCommand::PostInt32Array {
                name: name.to_string(),
                value,
                reply: reply_tx,
            })
            .map_err(|_| PvxsError::new("Server worker stopped"))?;
        reply_rx
            .recv()
            .map_err(|_| PvxsError::new("Server worker stopped"))?
    }

    pub fn post_string(&self, name: &str, value: &str) -> Result<()> {
        let (reply_tx, reply_rx) = channel::bounded(1);
        self.tx
            .send(ManagerCommand::PostString {
                name: name.to_string(),
                value: value.to_string(),
                reply: reply_tx,
            })
            .map_err(|_| PvxsError::new("Server worker stopped"))?;
        reply_rx
            .recv()
            .map_err(|_| PvxsError::new("Server worker stopped"))?
    }

    pub fn post_string_array(&self, name: &str, value: Vec<String>) -> Result<()> {
        let (reply_tx, reply_rx) = channel::bounded(1);
        self.tx
            .send(ManagerCommand::PostStringArray {
                name: name.to_string(),
                value,
                reply: reply_tx,
            })
            .map_err(|_| PvxsError::new("Server worker stopped"))?;
        reply_rx
            .recv()
            .map_err(|_| PvxsError::new("Server worker stopped"))?
    }

    pub fn post_enum(&self, name: &str, value: i16) -> Result<()> {
        let (reply_tx, reply_rx) = channel::bounded(1);
        self.tx
            .send(ManagerCommand::PostEnum {
                name: name.to_string(),
                value,
                reply: reply_tx,
            })
            .map_err(|_| PvxsError::new("Server worker stopped"))?;
        reply_rx
            .recv()
            .map_err(|_| PvxsError::new("Server worker stopped"))?
    }

    pub fn remove_pv(&self, name: &str) -> Result<()> {
        let (reply_tx, reply_rx) = channel::bounded(1);
        self.tx
            .send(ManagerCommand::Remove {
                name: name.to_string(),
                reply: reply_tx,
            })
            .map_err(|_| PvxsError::new("Server worker stopped"))?;
        reply_rx
            .recv()
            .map_err(|_| PvxsError::new("Server worker stopped"))?
    }

    pub fn fetch_double(&self, name: &str) -> Result<FetchedDouble> {
        let (reply_tx, reply_rx) = channel::bounded(1);
        self.tx
            .send(ManagerCommand::FetchDouble {
                name: name.to_string(),
                reply: reply_tx,
            })
            .map_err(|_| PvxsError::new("Server worker stopped"))?;
        reply_rx
            .recv()
            .map_err(|_| PvxsError::new("Server worker stopped"))?
    }

    pub fn fetch_int32(&self, name: &str) -> Result<FetchedInt32> {
        let (reply_tx, reply_rx) = channel::bounded(1);
        self.tx
            .send(ManagerCommand::FetchInt32 {
                name: name.to_string(),
                reply: reply_tx,
            })
            .map_err(|_| PvxsError::new("Server worker stopped"))?;
        reply_rx
            .recv()
            .map_err(|_| PvxsError::new("Server worker stopped"))?
    }

    pub fn fetch_string(&self, name: &str) -> Result<FetchedString> {
        let (reply_tx, reply_rx) = channel::bounded(1);
        self.tx
            .send(ManagerCommand::FetchString {
                name: name.to_string(),
                reply: reply_tx,
            })
            .map_err(|_| PvxsError::new("Server worker stopped"))?;
        reply_rx
            .recv()
            .map_err(|_| PvxsError::new("Server worker stopped"))?
    }

    pub fn fetch_double_array(&self, name: &str) -> Result<FetchedDoubleArray> {
        let (reply_tx, reply_rx) = channel::bounded(1);
        self.tx
            .send(ManagerCommand::FetchDoubleArray {
                name: name.to_string(),
                reply: reply_tx,
            })
            .map_err(|_| PvxsError::new("Server worker stopped"))?;
        reply_rx
            .recv()
            .map_err(|_| PvxsError::new("Server worker stopped"))?
    }

    pub fn fetch_int32_array(&self, name: &str) -> Result<FetchedInt32Array> {
        let (reply_tx, reply_rx) = channel::bounded(1);
        self.tx
            .send(ManagerCommand::FetchInt32Array {
                name: name.to_string(),
                reply: reply_tx,
            })
            .map_err(|_| PvxsError::new("Server worker stopped"))?;
        reply_rx
            .recv()
            .map_err(|_| PvxsError::new("Server worker stopped"))?
    }

    pub fn fetch_string_array(&self, name: &str) -> Result<FetchedStringArray> {
        let (reply_tx, reply_rx) = channel::bounded(1);
        self.tx
            .send(ManagerCommand::FetchStringArray {
                name: name.to_string(),
                reply: reply_tx,
            })
            .map_err(|_| PvxsError::new("Server worker stopped"))?;
        reply_rx
            .recv()
            .map_err(|_| PvxsError::new("Server worker stopped"))?
    }

    pub fn fetch_enum(&self, name: &str) -> Result<FetchedEnum> {
        let (reply_tx, reply_rx) = channel::bounded(1);
        self.tx
            .send(ManagerCommand::FetchEnum {
                name: name.to_string(),
                reply: reply_tx,
            })
            .map_err(|_| PvxsError::new("Server worker stopped"))?;
        reply_rx
            .recv()
            .map_err(|_| PvxsError::new("Server worker stopped"))?
    }
}

/// A PVXS server for hosting process variables with automatic alarm management
///
/// The Server provides managed PVs with automatic alarm handling, control limit
/// validation, and value alarm checking. This is the recommended way to create
/// EPICS servers in Rust.
///
/// # Features
///
/// - Automatic alarm computation based on control limits and value alarms
/// - Thread-safe PV management with internal worker thread
/// - Support for multiple data types (double, int32, string, enum, arrays)
/// - Isolated or environment-configured operation
///
/// # Example
///
/// ```no_run
/// use pvxs_sys::{Server, NTScalarMetadataBuilder, ControlMetadata};
///
/// let server = Server::start_from_env()?;
///
/// // Create a PV with control limits
/// let metadata = NTScalarMetadataBuilder::new()
///     .control(ControlMetadata {
///         limit_low: 0.0,
///         limit_high: 100.0,
///         min_step: 0.1,
///     });
///
/// server.create_pv_double("test:pv", 50.0, metadata)?;
/// server.post_double("test:pv", 75.0)?;  // Validated and with alarms
///
/// server.stop_drop()?;
/// # Ok::<(), pvxs_sys::PvxsError>(())
/// ```
pub struct Server {
    handle: ServerHandle,
    join: Option<thread::JoinHandle<()>>,
}

impl Server {
    /// Start a server using environment configuration
    ///
    /// Creates and starts a server that reads EPICS network configuration
    /// from environment variables.
    ///
    /// # Errors
    ///
    /// Returns an error if the server cannot be created or started.
    pub fn start_from_env() -> Result<Self> {
        Self::start_inner(false)
    }

    /// Start an isolated server for testing
    ///
    /// Creates and starts a server with system-assigned ports, ideal for
    /// unit tests and parallel test execution.
    ///
    /// # Errors
    ///
    /// Returns an error if the server cannot be created or started.
    pub fn start_isolated() -> Result<Self> {
        Self::start_inner(true)
    }

    /// Get a cloneable handle to this server
    ///
    /// The handle can be used from other threads to interact with the server.
    pub fn handle(&self) -> ServerHandle {
        self.handle.clone()
    }

    pub fn tcp_port(&self) -> u16 {
        self.handle.tcp_port()
    }

    pub fn udp_port(&self) -> u16 {
        self.handle.udp_port()
    }

    pub fn create_pv_double(
        &self,
        name: &str,
        initial: f64,
        metadata: NTScalarMetadataBuilder,
    ) -> Result<()> {
        self.handle.create_pv_double(name, initial, metadata)
    }

    pub fn create_pv_double_array(
        &self,
        name: &str,
        initial: Vec<f64>,
        metadata: NTScalarMetadataBuilder,
    ) -> Result<()> {
        self.handle.create_pv_double_array(name, initial, metadata)
    }

    pub fn create_pv_int32(
        &self,
        name: &str,
        initial: i32,
        metadata: NTScalarMetadataBuilder,
    ) -> Result<()> {
        self.handle.create_pv_int32(name, initial, metadata)
    }

    pub fn create_pv_int32_array(
        &self,
        name: &str,
        initial: Vec<i32>,
        metadata: NTScalarMetadataBuilder,
    ) -> Result<()> {
        self.handle.create_pv_int32_array(name, initial, metadata)
    }

    pub fn create_pv_string(
        &self,
        name: &str,
        initial: &str,
        metadata: NTScalarMetadataBuilder,
    ) -> Result<()> {
        self.handle.create_pv_string(name, initial, metadata)
    }

    pub fn create_pv_string_array(
        &self,
        name: &str,
        initial: Vec<String>,
        metadata: NTScalarMetadataBuilder,
    ) -> Result<()> {
        self.handle.create_pv_string_array(name, initial, metadata)
    }

    pub fn create_pv_enum(
        &self,
        name: &str,
        choices: Vec<&str>,
        selected_index: i16,
        metadata: NTEnumMetadataBuilder,
    ) -> Result<()> {
        self.handle
            .create_pv_enum(name, choices, selected_index, metadata)
    }

    pub fn post_double(&self, name: &str, value: f64) -> Result<()> {
        self.handle.post_double(name, value)
    }

    pub fn post_double_array(&self, name: &str, value: Vec<f64>) -> Result<()> {
        self.handle.post_double_array(name, value)
    }

    pub fn post_int32(&self, name: &str, value: i32) -> Result<()> {
        self.handle.post_int32(name, value)
    }

    pub fn post_int32_array(&self, name: &str, value: Vec<i32>) -> Result<()> {
        self.handle.post_int32_array(name, value)
    }

    pub fn post_string(&self, name: &str, value: &str) -> Result<()> {
        self.handle.post_string(name, value)
    }

    pub fn post_string_array(&self, name: &str, value: Vec<String>) -> Result<()> {
        self.handle.post_string_array(name, value)
    }

    pub fn post_enum(&self, name: &str, value: i16) -> Result<()> {
        self.handle.post_enum(name, value)
    }

    pub fn remove_pv(&self, name: &str) -> Result<()> {
        self.handle.remove_pv(name)
    }

    pub fn fetch_double(&self, name: &str) -> Result<FetchedDouble> {
        self.handle.fetch_double(name)
    }

    pub fn fetch_int32(&self, name: &str) -> Result<FetchedInt32> {
        self.handle.fetch_int32(name)
    }

    pub fn fetch_string(&self, name: &str) -> Result<FetchedString> {
        self.handle.fetch_string(name)
    }

    pub fn fetch_double_array(&self, name: &str) -> Result<FetchedDoubleArray> {
        self.handle.fetch_double_array(name)
    }

    pub fn fetch_int32_array(&self, name: &str) -> Result<FetchedInt32Array> {
        self.handle.fetch_int32_array(name)
    }

    pub fn fetch_string_array(&self, name: &str) -> Result<FetchedStringArray> {
        self.handle.fetch_string_array(name)
    }

    pub fn fetch_enum(&self, name: &str) -> Result<FetchedEnum> {
        self.handle.fetch_enum(name)
    }

    /// Indirectly calls inner stop through the manager thread, ensuring proper shutdown and resource cleanup
    /// Once Stop command is sent the worker thread will exit, however it will destroy the ServerImpl and the
    /// entire pvs hashmap so the all underlying C++ objects are freed correctly.
    ///
    /// Call start_from_env or start_isolated again and create new PVs to start a new server instance if needed after stopping.
    pub fn stop_drop(mut self) -> Result<()> {
        let (reply_tx, reply_rx) = channel::bounded(1);
        self.handle
            .tx
            .send(ManagerCommand::Stop { reply: reply_tx })
            .map_err(|_| PvxsError::new("Server worker stopped"))?;
        let result = reply_rx
            .recv()
            .map_err(|_| PvxsError::new("Server worker stopped"))?;
        if let Some(join) = self.join.take() {
            let _ = join.join();
        }
        result
    }

    fn start_inner(isolated: bool) -> Result<Self> {
        let (tx, rx) = channel::unbounded::<ManagerCommand>();
        let (ready_tx, ready_rx) = channel::bounded::<Result<(u16, u16)>>(1);

        let join = thread::spawn(move || {
            let mut server = if isolated {
                match ServerImpl::create_isolated() {
                    Ok(s) => s,
                    Err(e) => {
                        let _ = ready_tx.send(Err(e));
                        return;
                    }
                }
            } else {
                match ServerImpl::from_env() {
                    Ok(s) => s,
                    Err(e) => {
                        let _ = ready_tx.send(Err(e));
                        return;
                    }
                }
            };

            if let Err(e) = server.start() {
                let _ = ready_tx.send(Err(e));
                return;
            }

            let _ = ready_tx.send(Ok((server.tcp_port(), server.udp_port())));

            let mut pvs: HashMap<String, ManagedPv> = HashMap::new();

            while let Ok(cmd) = rx.recv() {
                match cmd {
                    ManagerCommand::CreateDouble {
                        name,
                        initial,
                        metadata,
                        reply,
                    } => {
                        let result = if pvs.contains_key(&name) {
                            Err(PvxsError::new("PV already exists"))
                        } else {
                            let alarm = AlarmConfig {
                                control: metadata.control.clone(),
                                alarm_metadata: metadata.alarm_metadata.clone(),
                            };
                            // Compute alarm for initial value
                            let alarm_result = compute_alarm_for_scalar(initial, &alarm);
                            // Update metadata with computed alarm
                            let mut metadata_with_alarm = metadata;
                            metadata_with_alarm.alarm_severity = alarm_result.severity;
                            metadata_with_alarm.alarm_status = alarm_result.status;
                            metadata_with_alarm.alarm_message = alarm_result.message.clone();

                            match server.create_pv_double(&name, initial, metadata_with_alarm) {
                                Ok(pv) => {
                                    pvs.insert(
                                        name,
                                        ManagedPv::Double {
                                            pv,
                                            alarm,
                                            last: initial,
                                        },
                                    );
                                    Ok(())
                                }
                                Err(e) => Err(e),
                            }
                        };
                        let _ = reply.send(result);
                    }
                    ManagerCommand::CreateDoubleArray {
                        name,
                        initial,
                        metadata,
                        reply,
                    } => {
                        let result = if pvs.contains_key(&name) {
                            Err(PvxsError::new("PV already exists"))
                        } else {
                            match server.create_pv_double_array(&name, initial, metadata) {
                                Ok(pv) => {
                                    pvs.insert(name, ManagedPv::DoubleArray(pv));
                                    Ok(())
                                }
                                Err(e) => Err(e),
                            }
                        };
                        let _ = reply.send(result);
                    }
                    ManagerCommand::CreateInt32 {
                        name,
                        initial,
                        metadata,
                        reply,
                    } => {
                        let result = if pvs.contains_key(&name) {
                            Err(PvxsError::new("PV already exists"))
                        } else {
                            let alarm = AlarmConfig {
                                control: metadata.control.clone(),
                                alarm_metadata: metadata.alarm_metadata.clone(),
                            };
                            // Compute alarm for initial value
                            let alarm_result = compute_alarm_for_scalar(initial as f64, &alarm);
                            // Update metadata with computed alarm
                            let mut metadata_with_alarm = metadata;
                            metadata_with_alarm.alarm_severity = alarm_result.severity;
                            metadata_with_alarm.alarm_status = alarm_result.status;
                            metadata_with_alarm.alarm_message = alarm_result.message.clone();

                            match server.create_pv_int32(&name, initial, metadata_with_alarm) {
                                Ok(pv) => {
                                    pvs.insert(
                                        name,
                                        ManagedPv::Int32 {
                                            pv,
                                            alarm,
                                            last: initial,
                                        },
                                    );
                                    Ok(())
                                }
                                Err(e) => Err(e),
                            }
                        };
                        let _ = reply.send(result);
                    }
                    ManagerCommand::CreateInt32Array {
                        name,
                        initial,
                        metadata,
                        reply,
                    } => {
                        let result = if pvs.contains_key(&name) {
                            Err(PvxsError::new("PV already exists"))
                        } else {
                            match server.create_pv_int32_array(&name, initial, metadata) {
                                Ok(pv) => {
                                    pvs.insert(name, ManagedPv::Int32Array(pv));
                                    Ok(())
                                }
                                Err(e) => Err(e),
                            }
                        };
                        let _ = reply.send(result);
                    }
                    ManagerCommand::CreateString {
                        name,
                        initial,
                        metadata,
                        reply,
                    } => {
                        let result = if pvs.contains_key(&name) {
                            Err(PvxsError::new("PV already exists"))
                        } else {
                            match server.create_pv_string(&name, &initial, metadata) {
                                Ok(pv) => {
                                    pvs.insert(name, ManagedPv::String(pv));
                                    Ok(())
                                }
                                Err(e) => Err(e),
                            }
                        };
                        let _ = reply.send(result);
                    }
                    ManagerCommand::CreateStringArray {
                        name,
                        initial,
                        metadata,
                        reply,
                    } => {
                        let result = if pvs.contains_key(&name) {
                            Err(PvxsError::new("PV already exists"))
                        } else {
                            match server.create_pv_string_array(&name, initial, metadata) {
                                Ok(pv) => {
                                    pvs.insert(name, ManagedPv::StringArray(pv));
                                    Ok(())
                                }
                                Err(e) => Err(e),
                            }
                        };
                        let _ = reply.send(result);
                    }
                    ManagerCommand::CreateEnum {
                        name,
                        choices,
                        selected_index,
                        metadata,
                        reply,
                    } => {
                        let result = if pvs.contains_key(&name) {
                            Err(PvxsError::new("PV already exists"))
                        } else {
                            let choices_refs: Vec<&str> =
                                choices.iter().map(|s| s.as_str()).collect();
                            match server.create_pv_enum(
                                &name,
                                choices_refs,
                                selected_index,
                                metadata,
                            ) {
                                Ok(pv) => {
                                    pvs.insert(name, ManagedPv::PvEnum(pv));
                                    Ok(())
                                }
                                Err(e) => Err(e),
                            }
                        };
                        let _ = reply.send(result);
                    }
                    ManagerCommand::PostDouble { name, value, reply } => {
                        let result = match pvs.get_mut(&name) {
                            Some(ManagedPv::Double { pv, alarm, last }) => {
                                let alarm_result = compute_alarm_for_scalar(value, alarm);
                                // If not allowed revert to last value
                                let post_value = if alarm_result.allow { value } else { *last };
                                let result = pv.post_double_with_alarm(
                                    post_value,
                                    alarm_result.severity,
                                    alarm_result.status,
                                    alarm_result.message,
                                );
                                if result.is_ok() && alarm_result.allow {
                                    *last = post_value;
                                }
                                result
                            }
                            _ => Err(PvxsError::new("PV not found or type mismatch")),
                        };
                        let _ = reply.send(result);
                    }
                    ManagerCommand::PostDoubleArray { name, value, reply } => {
                        let result = match pvs.get_mut(&name) {
                            Some(ManagedPv::DoubleArray(pv)) => pv.post_double_array(&value),
                            _ => Err(PvxsError::new("PV not found or type mismatch")),
                        };
                        let _ = reply.send(result);
                    }
                    ManagerCommand::PostInt32 { name, value, reply } => {
                        let result = match pvs.get_mut(&name) {
                            Some(ManagedPv::Int32 { pv, alarm, last }) => {
                                let alarm_result = compute_alarm_for_scalar(value as f64, alarm);
                                // If not allowed revert to last value
                                let post_value = if alarm_result.allow { value } else { *last };
                                let result = pv.post_int32_with_alarm(
                                    post_value,
                                    alarm_result.severity,
                                    alarm_result.status,
                                    alarm_result.message,
                                );
                                if result.is_ok() && alarm_result.allow {
                                    *last = post_value;
                                }
                                result
                            }
                            _ => Err(PvxsError::new("PV not found or type mismatch")),
                        };
                        let _ = reply.send(result);
                    }
                    ManagerCommand::PostInt32Array { name, value, reply } => {
                        let result = match pvs.get_mut(&name) {
                            Some(ManagedPv::Int32Array(pv)) => pv.post_int32_array(&value),
                            _ => Err(PvxsError::new("PV not found or type mismatch")),
                        };
                        let _ = reply.send(result);
                    }
                    ManagerCommand::PostString { name, value, reply } => {
                        let result = match pvs.get_mut(&name) {
                            Some(ManagedPv::String(pv)) => pv.post_string(&value),
                            _ => Err(PvxsError::new("PV not found or type mismatch")),
                        };
                        let _ = reply.send(result);
                    }
                    ManagerCommand::PostStringArray { name, value, reply } => {
                        let result = match pvs.get_mut(&name) {
                            Some(ManagedPv::StringArray(pv)) => pv.post_string_array(&value),
                            _ => Err(PvxsError::new("PV not found or type mismatch")),
                        };
                        let _ = reply.send(result);
                    }
                    ManagerCommand::PostEnum { name, value, reply } => {
                        let result = match pvs.get_mut(&name) {
                            Some(ManagedPv::PvEnum(pv)) => pv.post_enum(value),
                            _ => Err(PvxsError::new("PV not found or type mismatch")),
                        };
                        let _ = reply.send(result);
                    }
                    ManagerCommand::Remove { name, reply } => {
                        let result = if pvs.remove(&name).is_some() {
                            server.remove_pv(&name)
                        } else {
                            Err(PvxsError::new("PV not found"))
                        };
                        let _ = reply.send(result);
                    }
                    ManagerCommand::FetchDouble { name, reply } => {
                        let result = match pvs.get(&name) {
                            Some(ManagedPv::Double { pv, .. }) => {
                                pv.fetch().and_then(|v| {
                                    // Extract display metadata if present
                                    let display_metadata = (|| -> Option<DisplayMetadata> {
                                        Some(DisplayMetadata {
                                            limit_low: v.get_field_int32("display.limitLow").ok()?
                                                as i64,
                                            limit_high: v
                                                .get_field_int32("display.limitHigh")
                                                .ok()?
                                                as i64,
                                            description: v
                                                .get_field_string("display.description")
                                                .ok()?,
                                            units: v.get_field_string("display.units").ok()?,
                                            precision: v
                                                .get_field_int32("display.precision")
                                                .ok()?,
                                        })
                                    })();

                                    // Extract control metadata if present
                                    let control_metadata = (|| -> Option<ControlMetadata> {
                                        Some(ControlMetadata {
                                            limit_low: v
                                                .get_field_double("control.limitLow")
                                                .ok()?,
                                            limit_high: v
                                                .get_field_double("control.limitHigh")
                                                .ok()?,
                                            min_step: v.get_field_double("control.minStep").ok()?,
                                        })
                                    })();

                                    // Extract alarm metadata if present
                                    let alarm_metadata = (|| -> Option<AlarmMetadata> {
                                        Some(AlarmMetadata {
                                            active: v.get_field_int32("valueAlarm.active").ok()?
                                                != 0,
                                            low_alarm_limit: v
                                                .get_field_double("valueAlarm.lowAlarmLimit")
                                                .ok()?,
                                            low_warning_limit: v
                                                .get_field_double("valueAlarm.lowWarningLimit")
                                                .ok()?,
                                            high_warning_limit: v
                                                .get_field_double("valueAlarm.highWarningLimit")
                                                .ok()?,
                                            high_alarm_limit: v
                                                .get_field_double("valueAlarm.highAlarmLimit")
                                                .ok()?,
                                            low_alarm_severity: AlarmSeverity::from(
                                                v.get_field_int32("valueAlarm.lowAlarmSeverity")
                                                    .ok()?,
                                            ),
                                            low_warning_severity: AlarmSeverity::from(
                                                v.get_field_int32("valueAlarm.lowWarningSeverity")
                                                    .ok()?,
                                            ),
                                            high_warning_severity: AlarmSeverity::from(
                                                v.get_field_int32("valueAlarm.highWarningSeverity")
                                                    .ok()?,
                                            ),
                                            high_alarm_severity: AlarmSeverity::from(
                                                v.get_field_int32("valueAlarm.highAlarmSeverity")
                                                    .ok()?,
                                            ),
                                            hysteresis: v
                                                .get_field_int32("valueAlarm.hysteresis")
                                                .ok()?
                                                as u8,
                                        })
                                    })();

                                    Ok(FetchedDouble {
                                        value: v.get_field_double("value")?,
                                        alarm_severity: AlarmSeverity::from(
                                            v.get_field_int32("alarm.severity").unwrap_or(0),
                                        ),
                                        alarm_status: AlarmStatus::from(
                                            v.get_field_int32("alarm.status").unwrap_or(0),
                                        ),
                                        alarm_message: v
                                            .get_field_string("alarm.message")
                                            .unwrap_or_default(),
                                        display_metadata,
                                        control_metadata,
                                        alarm_metadata,
                                    })
                                })
                            }
                            _ => Err(PvxsError::new("PV not found or type mismatch")),
                        };
                        let _ = reply.send(result);
                    }
                    ManagerCommand::FetchInt32 { name, reply } => {
                        let result = match pvs.get(&name) {
                            Some(ManagedPv::Int32 { pv, .. }) => {
                                pv.fetch().and_then(|v| {
                                    // Extract display metadata if present
                                    let display_metadata = (|| -> Option<DisplayMetadata> {
                                        Some(DisplayMetadata {
                                            limit_low: v.get_field_int32("display.limitLow").ok()?
                                                as i64,
                                            limit_high: v
                                                .get_field_int32("display.limitHigh")
                                                .ok()?
                                                as i64,
                                            description: v
                                                .get_field_string("display.description")
                                                .ok()?,
                                            units: v.get_field_string("display.units").ok()?,
                                            precision: v
                                                .get_field_int32("display.precision")
                                                .ok()?,
                                        })
                                    })();

                                    // Extract control metadata if present
                                    let control_metadata = (|| -> Option<ControlMetadata> {
                                        Some(ControlMetadata {
                                            limit_low: v
                                                .get_field_double("control.limitLow")
                                                .ok()?,
                                            limit_high: v
                                                .get_field_double("control.limitHigh")
                                                .ok()?,
                                            min_step: v.get_field_double("control.minStep").ok()?,
                                        })
                                    })();

                                    // Extract alarm metadata if present
                                    let alarm_metadata = (|| -> Option<AlarmMetadata> {
                                        Some(AlarmMetadata {
                                            active: v.get_field_int32("valueAlarm.active").ok()?
                                                != 0,
                                            low_alarm_limit: v
                                                .get_field_double("valueAlarm.lowAlarmLimit")
                                                .ok()?,
                                            low_warning_limit: v
                                                .get_field_double("valueAlarm.lowWarningLimit")
                                                .ok()?,
                                            high_warning_limit: v
                                                .get_field_double("valueAlarm.highWarningLimit")
                                                .ok()?,
                                            high_alarm_limit: v
                                                .get_field_double("valueAlarm.highAlarmLimit")
                                                .ok()?,
                                            low_alarm_severity: AlarmSeverity::from(
                                                v.get_field_int32("valueAlarm.lowAlarmSeverity")
                                                    .ok()?,
                                            ),
                                            low_warning_severity: AlarmSeverity::from(
                                                v.get_field_int32("valueAlarm.lowWarningSeverity")
                                                    .ok()?,
                                            ),
                                            high_warning_severity: AlarmSeverity::from(
                                                v.get_field_int32("valueAlarm.highWarningSeverity")
                                                    .ok()?,
                                            ),
                                            high_alarm_severity: AlarmSeverity::from(
                                                v.get_field_int32("valueAlarm.highAlarmSeverity")
                                                    .ok()?,
                                            ),
                                            hysteresis: v
                                                .get_field_int32("valueAlarm.hysteresis")
                                                .ok()?
                                                as u8,
                                        })
                                    })();

                                    Ok(FetchedInt32 {
                                        value: v.get_field_int32("value")?,
                                        alarm_severity: AlarmSeverity::from(
                                            v.get_field_int32("alarm.severity").unwrap_or(0),
                                        ),
                                        alarm_status: AlarmStatus::from(
                                            v.get_field_int32("alarm.status").unwrap_or(0),
                                        ),
                                        alarm_message: v
                                            .get_field_string("alarm.message")
                                            .unwrap_or_default(),
                                        display_metadata,
                                        control_metadata,
                                        alarm_metadata,
                                    })
                                })
                            }
                            _ => Err(PvxsError::new("PV not found or type mismatch")),
                        };
                        let _ = reply.send(result);
                    }
                    ManagerCommand::FetchString { name, reply } => {
                        let result = match pvs.get(&name) {
                            Some(ManagedPv::String(pv)) => pv.fetch().and_then(|v| {
                                Ok(FetchedString {
                                    value: v.get_field_string("value")?,
                                    alarm_severity: AlarmSeverity::from(
                                        v.get_field_int32("alarm.severity").unwrap_or(0),
                                    ),
                                    alarm_status: AlarmStatus::from(
                                        v.get_field_int32("alarm.status").unwrap_or(0),
                                    ),
                                    alarm_message: v
                                        .get_field_string("alarm.message")
                                        .unwrap_or_default(),
                                })
                            }),
                            _ => Err(PvxsError::new("PV not found or type mismatch")),
                        };
                        let _ = reply.send(result);
                    }
                    ManagerCommand::FetchDoubleArray { name, reply } => {
                        let result = match pvs.get(&name) {
                            Some(ManagedPv::DoubleArray(pv)) => pv.fetch().and_then(|v| {
                                let display_metadata = (|| -> Option<DisplayMetadata> {
                                    Some(DisplayMetadata {
                                        limit_low: v.get_field_int32("display.limitLow").ok()?
                                            as i64,
                                        limit_high: v.get_field_int32("display.limitHigh").ok()?
                                            as i64,
                                        description: v
                                            .get_field_string("display.description")
                                            .ok()?,
                                        units: v.get_field_string("display.units").ok()?,
                                        precision: v.get_field_int32("display.precision").ok()?,
                                    })
                                })();
                                let control_metadata = (|| -> Option<ControlMetadata> {
                                    Some(ControlMetadata {
                                        limit_low: v.get_field_double("control.limitLow").ok()?,
                                        limit_high: v.get_field_double("control.limitHigh").ok()?,
                                        min_step: v.get_field_double("control.minStep").ok()?,
                                    })
                                })();
                                let alarm_metadata = (|| -> Option<AlarmMetadata> {
                                    Some(AlarmMetadata {
                                        active: v.get_field_int32("valueAlarm.active").ok()? != 0,
                                        low_alarm_limit: v
                                            .get_field_double("valueAlarm.lowAlarmLimit")
                                            .ok()?,
                                        low_warning_limit: v
                                            .get_field_double("valueAlarm.lowWarningLimit")
                                            .ok()?,
                                        high_warning_limit: v
                                            .get_field_double("valueAlarm.highWarningLimit")
                                            .ok()?,
                                        high_alarm_limit: v
                                            .get_field_double("valueAlarm.highAlarmLimit")
                                            .ok()?,
                                        low_alarm_severity: AlarmSeverity::from(
                                            v.get_field_int32("valueAlarm.lowAlarmSeverity")
                                                .ok()?,
                                        ),
                                        low_warning_severity: AlarmSeverity::from(
                                            v.get_field_int32("valueAlarm.lowWarningSeverity")
                                                .ok()?,
                                        ),
                                        high_warning_severity: AlarmSeverity::from(
                                            v.get_field_int32("valueAlarm.highWarningSeverity")
                                                .ok()?,
                                        ),
                                        high_alarm_severity: AlarmSeverity::from(
                                            v.get_field_int32("valueAlarm.highAlarmSeverity")
                                                .ok()?,
                                        ),
                                        hysteresis: v
                                            .get_field_int32("valueAlarm.hysteresis")
                                            .ok()?
                                            as u8,
                                    })
                                })();
                                Ok(FetchedDoubleArray {
                                    value: v.get_field_double_array("value")?,
                                    alarm_severity: AlarmSeverity::from(
                                        v.get_field_int32("alarm.severity").unwrap_or(0),
                                    ),
                                    alarm_status: AlarmStatus::from(
                                        v.get_field_int32("alarm.status").unwrap_or(0),
                                    ),
                                    alarm_message: v
                                        .get_field_string("alarm.message")
                                        .unwrap_or_default(),
                                    display_metadata,
                                    control_metadata,
                                    alarm_metadata,
                                })
                            }),
                            _ => Err(PvxsError::new("PV not found or type mismatch")),
                        };
                        let _ = reply.send(result);
                    }
                    ManagerCommand::FetchInt32Array { name, reply } => {
                        let result = match pvs.get(&name) {
                            Some(ManagedPv::Int32Array(pv)) => pv.fetch().and_then(|v| {
                                let display_metadata = (|| -> Option<DisplayMetadata> {
                                    Some(DisplayMetadata {
                                        limit_low: v.get_field_int32("display.limitLow").ok()?
                                            as i64,
                                        limit_high: v.get_field_int32("display.limitHigh").ok()?
                                            as i64,
                                        description: v
                                            .get_field_string("display.description")
                                            .ok()?,
                                        units: v.get_field_string("display.units").ok()?,
                                        precision: v.get_field_int32("display.precision").ok()?,
                                    })
                                })();
                                let control_metadata = (|| -> Option<ControlMetadata> {
                                    Some(ControlMetadata {
                                        limit_low: v.get_field_double("control.limitLow").ok()?,
                                        limit_high: v.get_field_double("control.limitHigh").ok()?,
                                        min_step: v.get_field_double("control.minStep").ok()?,
                                    })
                                })();
                                let alarm_metadata = (|| -> Option<AlarmMetadata> {
                                    Some(AlarmMetadata {
                                        active: v.get_field_int32("valueAlarm.active").ok()? != 0,
                                        low_alarm_limit: v
                                            .get_field_double("valueAlarm.lowAlarmLimit")
                                            .ok()?,
                                        low_warning_limit: v
                                            .get_field_double("valueAlarm.lowWarningLimit")
                                            .ok()?,
                                        high_warning_limit: v
                                            .get_field_double("valueAlarm.highWarningLimit")
                                            .ok()?,
                                        high_alarm_limit: v
                                            .get_field_double("valueAlarm.highAlarmLimit")
                                            .ok()?,
                                        low_alarm_severity: AlarmSeverity::from(
                                            v.get_field_int32("valueAlarm.lowAlarmSeverity")
                                                .ok()?,
                                        ),
                                        low_warning_severity: AlarmSeverity::from(
                                            v.get_field_int32("valueAlarm.lowWarningSeverity")
                                                .ok()?,
                                        ),
                                        high_warning_severity: AlarmSeverity::from(
                                            v.get_field_int32("valueAlarm.highWarningSeverity")
                                                .ok()?,
                                        ),
                                        high_alarm_severity: AlarmSeverity::from(
                                            v.get_field_int32("valueAlarm.highAlarmSeverity")
                                                .ok()?,
                                        ),
                                        hysteresis: v
                                            .get_field_int32("valueAlarm.hysteresis")
                                            .ok()?
                                            as u8,
                                    })
                                })();
                                Ok(FetchedInt32Array {
                                    value: v.get_field_int32_array("value")?,
                                    alarm_severity: AlarmSeverity::from(
                                        v.get_field_int32("alarm.severity").unwrap_or(0),
                                    ),
                                    alarm_status: AlarmStatus::from(
                                        v.get_field_int32("alarm.status").unwrap_or(0),
                                    ),
                                    alarm_message: v
                                        .get_field_string("alarm.message")
                                        .unwrap_or_default(),
                                    display_metadata,
                                    control_metadata,
                                    alarm_metadata,
                                })
                            }),
                            _ => Err(PvxsError::new("PV not found or type mismatch")),
                        };
                        let _ = reply.send(result);
                    }
                    ManagerCommand::FetchStringArray { name, reply } => {
                        let result = match pvs.get(&name) {
                            Some(ManagedPv::StringArray(pv)) => pv.fetch().and_then(|v| {
                                Ok(FetchedStringArray {
                                    value: v.get_field_string_array("value")?,
                                    alarm_severity: AlarmSeverity::from(
                                        v.get_field_int32("alarm.severity").unwrap_or(0),
                                    ),
                                    alarm_status: AlarmStatus::from(
                                        v.get_field_int32("alarm.status").unwrap_or(0),
                                    ),
                                    alarm_message: v
                                        .get_field_string("alarm.message")
                                        .unwrap_or_default(),
                                })
                            }),
                            _ => Err(PvxsError::new("PV not found or type mismatch")),
                        };
                        let _ = reply.send(result);
                    }
                    ManagerCommand::FetchEnum { name, reply } => {
                        let result = match pvs.get(&name) {
                            Some(ManagedPv::PvEnum(pv)) => pv.fetch().and_then(|v| {
                                Ok(FetchedEnum {
                                    value: v.get_field_enum("value.index")?,
                                    value_choices: v
                                        .get_field_string_array("value.choices")
                                        .unwrap_or_default(),
                                    alarm_severity: AlarmSeverity::from(
                                        v.get_field_int32("alarm.severity").unwrap_or(0),
                                    ),
                                    alarm_status: AlarmStatus::from(
                                        v.get_field_int32("alarm.status").unwrap_or(0),
                                    ),
                                    alarm_message: v
                                        .get_field_string("alarm.message")
                                        .unwrap_or_default(),
                                })
                            }),
                            _ => Err(PvxsError::new("PV not found or type mismatch")),
                        };
                        let _ = reply.send(result);
                    }
                    ManagerCommand::Stop { reply } => {
                        let result = server.stop();
                        let _ = reply.send(result);
                        break;
                    }
                }
            }
        });

        let (tcp_port, udp_port) = ready_rx
            .recv()
            .map_err(|_| PvxsError::new("Server failed to start"))??;

        Ok(Self {
            handle: ServerHandle {
                tx,
                tcp_port,
                udp_port,
            },
            join: Some(join),
        })
    }
}

/// A shared process variable that can be hosted by a server
///
/// SharedPVs represent individual process variables with typed values
/// that can be accessed by EPICS clients.
///
/// # Example
///
/// ```ignore
/// use pvxs_sys::SharedPV;
///
/// let mut pv = SharedPV::create_mailbox()?;
/// // Note: open_double is internal API, use Server::create_pv_* methods instead
///
/// // Update the value
/// pv.post_double(99.9)?;
///
/// // Get current value
/// let value = pv.fetch()?;
/// println!("Current value: {}", value);
/// # Ok::<(), pvxs_sys::PvxsError>(())
/// ```
pub struct SharedPV {
    inner: UniquePtr<bridge::SharedPVWrapper>,
}

impl SharedPV {
    /// Create a mailbox SharedPV
    ///
    /// Mailbox PVs support both read and write operations by clients.
    pub fn create_mailbox() -> Result<Self> {
        let inner = bridge::shared_pv_create_mailbox()?;
        Ok(Self { inner })
    }

    /// Create a readonly SharedPV
    ///
    /// Readonly PVs only support read operations by clients.
    pub fn create_readonly() -> Result<Self> {
        let inner = bridge::shared_pv_create_readonly()?;
        Ok(Self { inner })
    }

    /// Open the PV with a double value and metadata
    ///
    /// # Arguments
    ///
    /// * `initial_value` - The initial value for the PV
    /// * `metadata` - Metadata builder for the scalar PV
    ///
    /// # Example
    ///
    /// ```ignore
    /// # use pvxs_sys::{SharedPV, NTScalarMetadataBuilder, DisplayMetadata};
    /// // Note: open_double is internal API
    /// // Use Server::create_pv_double instead for public API
    /// let mut pv = SharedPV::create_mailbox()?;
    ///
    /// let metadata = NTScalarMetadataBuilder::new()
    ///     .alarm(0, 0, "OK")
    ///     .display(DisplayMetadata {
    ///         limit_low: 0,
    ///         limit_high: 100,
    ///         description: "Temperature".to_string(),
    ///         units: "°C".to_string(),
    ///         precision: 2,
    ///     })
    ///
    /// pv.open_double(25.5, metadata)?;
    /// # Ok::<(), pvxs_sys::PvxsError>(())
    /// ```
    pub(crate) fn open_double(
        &mut self,
        initial_value: f64,
        metadata: NTScalarMetadataBuilder,
    ) -> Result<()> {
        let meta = metadata.build()?;
        bridge::shared_pv_open_double(self.inner.pin_mut(), initial_value, &meta)?;
        Ok(())
    }

    /// Open the PV with a double array value and metadata
    ///
    /// # Arguments
    ///
    /// * `initial_value` - The initial array value for the PV
    /// * `metadata` - Metadata builder for the scalar array PV
    pub(crate) fn open_double_array(
        &mut self,
        initial_value: Vec<f64>,
        metadata: NTScalarMetadataBuilder,
    ) -> Result<()> {
        let meta = metadata.build()?;
        bridge::shared_pv_open_double_array(self.inner.pin_mut(), initial_value, &meta)?;
        Ok(())
    }

    /// Open the PV with an enum value and metadata
    ///
    /// # Arguments
    ///
    /// * `choices` - List of string choices for the enum
    /// * `selected_index` - Initial selected index (0-based)
    /// * `metadata` - Metadata builder for the enum PV
    pub(crate) fn open_enum(
        &mut self,
        choices: Vec<&str>,
        selected_index: i16,
        metadata: NTEnumMetadataBuilder,
    ) -> Result<()> {
        let meta = metadata.build()?;
        let choices_vec: Vec<String> = choices.iter().map(|s| s.to_string()).collect();
        bridge::shared_pv_open_enum(self.inner.pin_mut(), choices_vec, selected_index, &meta)?;
        Ok(())
    }

    /// Open the PV with an int32 value and metadata
    ///
    /// # Arguments
    ///
    /// * `initial_value` - The initial value for the PV
    /// * `metadata` - Metadata builder for the int32 PV
    pub(crate) fn open_int32(
        &mut self,
        initial_value: i32,
        metadata: NTScalarMetadataBuilder,
    ) -> Result<()> {
        let meta = metadata.build()?;
        bridge::shared_pv_open_int32(self.inner.pin_mut(), initial_value, &meta)?;
        Ok(())
    }

    /// Open the PV with an int32 array value and metadata
    ///
    /// # Arguments
    ///
    /// * `initial_value` - The initial array value for the PV
    /// * `metadata` - Metadata builder for the int32 array PV
    pub(crate) fn open_int32_array(
        &mut self,
        initial_value: Vec<i32>,
        metadata: NTScalarMetadataBuilder,
    ) -> Result<()> {
        let meta = metadata.build()?;
        bridge::shared_pv_open_int32_array(self.inner.pin_mut(), initial_value, &meta)?;
        Ok(())
    }

    /// Open the PV with a string value and metadata
    ///
    /// # Arguments
    ///
    /// * `initial_value` - The initial value for the PV
    /// * `metadata` - Metadata builder for the string PV
    pub(crate) fn open_string(
        &mut self,
        initial_value: &str,
        metadata: NTScalarMetadataBuilder,
    ) -> Result<()> {
        let meta = metadata.build()?;
        bridge::shared_pv_open_string(self.inner.pin_mut(), initial_value.to_string(), &meta)?;
        Ok(())
    }

    /// Open the PV with a string array value and metadata
    ///
    /// # Arguments
    ///
    /// * `initial_value` - The initial array value for the PV
    /// * `metadata` - Metadata builder for the string array PV
    pub(crate) fn open_string_array(
        &mut self,
        initial_value: Vec<String>,
        metadata: NTScalarMetadataBuilder,
    ) -> Result<()> {
        let meta = metadata.build()?;
        bridge::shared_pv_open_string_array(self.inner.pin_mut(), initial_value, &meta)?;
        Ok(())
    }

    /// Check if the PV is open
    pub fn is_open(&self) -> bool {
        bridge::shared_pv_is_open(&self.inner)
    }

    /// Close the PV
    pub fn close(&mut self) -> Result<()> {
        bridge::shared_pv_close(self.inner.pin_mut())?;
        Ok(())
    }

    /// Post a new double value to the PV
    ///
    /// This updates the PV value and notifies connected clients.
    /// If the PV is a double array, this will just replace the value at position 0.
    ///
    /// # Arguments
    ///
    /// * `value` - The new value to post
    pub fn post_double(&mut self, value: f64) -> Result<()> {
        bridge::shared_pv_post_double(self.inner.pin_mut(), value)?;
        Ok(())
    }

    /// Post a new int32 value to the PV
    ///
    /// This updates the PV value and notifies connected clients.
    /// If the PV is an int32 array, this will just replace the value at position 0.
    ///
    /// # Arguments
    ///
    /// * `value` - The new value to post
    pub fn post_int32(&mut self, value: i32) -> Result<()> {
        bridge::shared_pv_post_int32(self.inner.pin_mut(), value)?;
        Ok(())
    }

    pub(crate) fn post_double_with_alarm(
        &mut self,
        value: f64,
        severity: AlarmSeverity,
        status: AlarmStatus,
        message: String,
    ) -> Result<()> {
        bridge::shared_pv_post_double_with_alarm(
            self.inner.pin_mut(),
            value,
            severity as i32,
            status as i32,
            message,
        )?;
        Ok(())
    }

    pub(crate) fn post_int32_with_alarm(
        &mut self,
        value: i32,
        severity: AlarmSeverity,
        status: AlarmStatus,
        message: String,
    ) -> Result<()> {
        bridge::shared_pv_post_int32_with_alarm(
            self.inner.pin_mut(),
            value,
            severity as i32,
            status as i32,
            message,
        )?;
        Ok(())
    }

    // TODO: TZ - Review later if needed
    /*pub(crate) fn post_enum_with_alarm(&mut self, value: i16, severity: AlarmSeverity, status: AlarmStatus, message: String) -> Result<()> {
        bridge::shared_pv_post_enum_with_alarm(self.inner.pin_mut(), value, severity as i32, status as i32, message)?;
        Ok(())
    }*/

    /// Post a new string value to the PV
    ///
    /// # Arguments
    ///
    /// * `value` - The new value to post
    pub fn post_string(&mut self, value: &str) -> Result<()> {
        bridge::shared_pv_post_string(self.inner.pin_mut(), value.to_string())?;
        Ok(())
    }

    /// Post a new enum value to the PV
    ///
    /// Updates the enum index (value.index field) and notifies connected clients.
    ///
    /// # Arguments
    ///
    /// * `value` - The enum index to post (should be valid for the choices array)
    pub fn post_enum(&mut self, value: i16) -> Result<()> {
        bridge::shared_pv_post_enum(self.inner.pin_mut(), value)?;
        Ok(())
    }

    /// Post a new double array to the PV
    ///
    /// Updates the array value and notifies connected clients.
    ///
    /// # Arguments
    ///
    /// * `value` - The new array to post
    pub fn post_double_array(&mut self, value: &[f64]) -> Result<()> {
        if value.is_empty() {
            return Err(PvxsError::new("Cannot post empty double array"));
        }
        bridge::shared_pv_post_double_array(self.inner.pin_mut(), value.to_vec())?;
        Ok(())
    }

    /// Post a new int32 array to the PV
    ///
    /// Updates the array value and notifies connected clients.
    ///
    /// # Arguments
    ///
    /// * `value` - The new array to post
    pub fn post_int32_array(&mut self, value: &[i32]) -> Result<()> {
        if value.is_empty() {
            return Err(PvxsError::new("Cannot post empty int32 array"));
        }
        bridge::shared_pv_post_int32_array(self.inner.pin_mut(), value.to_vec())?;
        Ok(())
    }

    /// Post a new string array to the PV
    ///
    /// Updates the array value and notifies connected clients.
    ///
    /// # Arguments
    ///
    /// * `value` - The new array to post
    pub fn post_string_array(&mut self, value: &[String]) -> Result<()> {
        if value.is_empty() {
            return Err(PvxsError::new("Cannot post empty string array"));
        }
        bridge::shared_pv_post_string_array(self.inner.pin_mut(), value.to_vec())?;
        Ok(())
    }

    /// Fetch the current value of the PV
    ///
    /// Returns the current value as a Value that can be inspected.
    pub fn fetch(&self) -> Result<Value> {
        let inner = bridge::shared_pv_fetch(&self.inner)?;
        Ok(Value { inner })
    }
}

/// A static source for organising collections of PVs
///
/// StaticSource allows grouping related PVs together with common
/// configuration and management.
///
/// # Example
///
/// ```ignore
/// use pvxs_sys::{StaticSource, SharedPV};
///
/// // Note: This example uses internal APIs
/// // Use Server::create_pv_* methods for public API
/// let mut source = StaticSource::create()?;
///
/// let mut temp_pv = SharedPV::create_readonly()?;
/// // temp_pv.open_double(23.5)?; // Internal API
///
/// source.add_pv("temperature", &mut temp_pv)?;
///
/// // Add source to server with priority 0
/// // server.add_source("sensors", &mut source, 0)?;
/// # Ok::<(), pvxs_sys::PvxsError>(())
/// ```
pub struct StaticSource {
    inner: UniquePtr<bridge::StaticSourceWrapper>,
}

impl StaticSource {
    /// Create a new StaticSource
    pub fn create() -> Result<Self> {
        let inner = bridge::static_source_create()?;
        Ok(Self { inner })
    }

    /// Add a PV to this source
    ///
    /// # Arguments
    ///
    /// * `name` - The PV name within this source
    /// * `pv` - The SharedPV to add
    pub fn add_pv(&mut self, name: &str, pv: &mut SharedPV) -> Result<()> {
        bridge::static_source_add_pv(self.inner.pin_mut(), name.to_string(), pv.inner.pin_mut())?;
        Ok(())
    }

    /// Remove a PV from this source
    ///
    /// # Arguments
    ///
    /// * `name` - The name of the PV to remove
    pub fn remove_pv(&mut self, name: &str) -> Result<()> {
        bridge::static_source_remove_pv(self.inner.pin_mut(), name.to_string())?;
        Ok(())
    }

    /// Close all PVs in this source
    pub fn close_all(&mut self) -> Result<()> {
        bridge::static_source_close_all(self.inner.pin_mut())?;
        Ok(())
    }
}

// ============================================================================
// NTScalar Metadata Support with C++ std::optional
// ============================================================================

/// Builder for creating NTScalar metadata with optional fields
///
/// This provides a clean, type-safe API for configuring PV metadata.
/// The metadata is constructed using C++ builder functions that support std::optional.
///
/// ```text
/// epics:nt/NTScalar:1.0
/// double value
/// alarm_t alarm
///     int severity
///     int status
///     string message
/// structure timeStamp
///     long secondsPastEpoch
///     int nanoseconds
///     int userTag
/// structure display
///     double limitLow
///     double limitHigh
///     string description
///     string units
///     int precision
/// control_t control
///     double limitLow
///     double limitHigh
///     double minStep
/// valueAlarm_t valueAlarm
///     boolean active
///     double lowAlarmLimit
///     double lowWarningLimit
///     double highWarningLimit
///     double highAlarmLimit
///     int lowAlarmSeverity
///     int lowWarningSeverity
///     int highWarningSeverity
///     int highAlarmSeverity
///     byte hysteresis
/// ```
#[derive(Debug, Clone)]
pub struct NTScalarMetadataBuilder {
    alarm_severity: AlarmSeverity,
    alarm_status: AlarmStatus,
    alarm_message: String,
    timestamp_seconds: i64,
    timestamp_nanos: i32,
    timestamp_user_tag: i32,
    display: Option<DisplayMetadata>,
    control: Option<ControlMetadata>,
    alarm_metadata: Option<AlarmMetadata>,
}

impl NTScalarMetadataBuilder {
    /// Create a new metadata builder with default values
    pub fn new() -> Self {
        use std::time::{SystemTime, UNIX_EPOCH};
        let now = SystemTime::now().duration_since(UNIX_EPOCH).unwrap();

        Self {
            alarm_severity: AlarmSeverity::Invalid,
            alarm_status: AlarmStatus::UndefinedStatus,
            alarm_message: String::new(),
            timestamp_seconds: now.as_secs() as i64,
            timestamp_nanos: now.subsec_nanos() as i32,
            timestamp_user_tag: 0,
            display: None,
            control: None,
            alarm_metadata: None,
        }
    }

    /// Set alarm information
    pub fn alarm(
        mut self,
        severity: AlarmSeverity,
        status: AlarmStatus,
        message: impl Into<String>,
    ) -> Self {
        self.alarm_severity = severity;
        self.alarm_status = status;
        self.alarm_message = message.into();
        self
    }

    /// Set timestamp (defaults to current time)
    pub fn timestamp(mut self, seconds: i64, nanos: i32, user_tag: i32) -> Self {
        self.timestamp_seconds = seconds;
        self.timestamp_nanos = nanos;
        self.timestamp_user_tag = user_tag;
        self
    }

    /// Add display metadata
    pub fn display(mut self, meta: DisplayMetadata) -> Self {
        self.display = Some(meta);
        self
    }

    /// Add control metadata
    pub fn control(mut self, meta: ControlMetadata) -> Self {
        self.control = Some(meta);
        self
    }

    /// Add value alarm metadata
    pub fn alarm_metadata(mut self, meta: AlarmMetadata) -> Self {
        self.alarm_metadata = Some(meta);
        self
    }

    /// Build the metadata using C++ builder functions with std::optional support
    fn build(self) -> Result<cxx::UniquePtr<bridge::NTScalarMetadata>> {
        // Create alarm and timestamp (always required)
        let alarm = bridge::create_alarm(
            self.alarm_severity as i32,
            self.alarm_status as i32,
            self.alarm_message,
        );
        let time_stamp = bridge::create_time(
            self.timestamp_seconds,
            self.timestamp_nanos,
            self.timestamp_user_tag,
        );

        let make_display = |d: &DisplayMetadata| {
            bridge::create_display(
                d.limit_low,
                d.limit_high,
                d.description.clone(),
                d.units.clone(),
                d.precision,
            )
        };

        // Build metadata based on which optional fields are present
        let metadata = match (&self.display, &self.control, &self.alarm_metadata) {
            (None, None, None) => bridge::create_metadata_no_optional(&alarm, &time_stamp),
            (Some(d), None, None) => {
                let display = make_display(d);
                bridge::create_metadata_with_display(&alarm, &time_stamp, &display)
            }
            (None, Some(c), None) => {
                let control = bridge::create_control(c.limit_low, c.limit_high, c.min_step);
                bridge::create_metadata_with_control(&alarm, &time_stamp, &control)
            }
            (None, None, Some(v)) => {
                let value_alarm = bridge::create_value_alarm(
                    v.active,
                    v.low_alarm_limit,
                    v.low_warning_limit,
                    v.high_warning_limit,
                    v.high_alarm_limit,
                    v.low_alarm_severity as i32,
                    v.low_warning_severity as i32,
                    v.high_warning_severity as i32,
                    v.high_alarm_severity as i32,
                    v.hysteresis,
                );
                bridge::create_metadata_with_value_alarm(&alarm, &time_stamp, &value_alarm)
            }
            (Some(d), Some(c), None) => {
                let display = make_display(d);
                let control = bridge::create_control(c.limit_low, c.limit_high, c.min_step);
                bridge::create_metadata_with_display_control(
                    &alarm,
                    &time_stamp,
                    &display,
                    &control,
                )
            }
            (Some(d), None, Some(v)) => {
                let display = make_display(d);
                let value_alarm = bridge::create_value_alarm(
                    v.active,
                    v.low_alarm_limit,
                    v.low_warning_limit,
                    v.high_warning_limit,
                    v.high_alarm_limit,
                    v.low_alarm_severity as i32,
                    v.low_warning_severity as i32,
                    v.high_warning_severity as i32,
                    v.high_alarm_severity as i32,
                    v.hysteresis,
                );
                bridge::create_metadata_with_display_value_alarm(
                    &alarm,
                    &time_stamp,
                    &display,
                    &value_alarm,
                )
            }
            (None, Some(c), Some(v)) => {
                let control = bridge::create_control(c.limit_low, c.limit_high, c.min_step);
                let value_alarm = bridge::create_value_alarm(
                    v.active,
                    v.low_alarm_limit,
                    v.low_warning_limit,
                    v.high_warning_limit,
                    v.high_alarm_limit,
                    v.low_alarm_severity as i32,
                    v.low_warning_severity as i32,
                    v.high_warning_severity as i32,
                    v.high_alarm_severity as i32,
                    v.hysteresis,
                );
                bridge::create_metadata_with_control_value_alarm(
                    &alarm,
                    &time_stamp,
                    &control,
                    &value_alarm,
                )
            }
            (Some(d), Some(c), Some(v)) => {
                let display = make_display(d);
                let control = bridge::create_control(c.limit_low, c.limit_high, c.min_step);
                let value_alarm = bridge::create_value_alarm(
                    v.active,
                    v.low_alarm_limit,
                    v.low_warning_limit,
                    v.high_warning_limit,
                    v.high_alarm_limit,
                    v.low_alarm_severity as i32,
                    v.low_warning_severity as i32,
                    v.high_warning_severity as i32,
                    v.high_alarm_severity as i32,
                    v.hysteresis,
                );
                bridge::create_metadata_full(&alarm, &time_stamp, &display, &control, &value_alarm)
            }
        };

        Ok(metadata)
    }
}

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

// ============================================================================
// NTEnum Metadata support
// ============================================================================
/// Builder for creating NTEnum metadata
///
/// This provides a clean, type-safe API for configuring enum PV metadata.
/// The metadata is constructed using C++ builder functions.
///
/// ```text
/// epics:nt/NTEnum:1.0
/// enum_t value
///     int index
///     string[] choices
/// alarm_t alarm
///     int severity
///     int status
///     string message
/// structure timeStamp
///     long secondsPastEpoch
///     int nanoseconds
///     int userTag
/// ```
pub struct NTEnumMetadataBuilder {
    alarm_severity: i32,
    alarm_status: i32,
    alarm_message: String,
    timestamp_seconds: i64,
    timestamp_nanos: i32,
    timestamp_user_tag: i32,
}

impl NTEnumMetadataBuilder {
    /// Create a new metadata builder with default values
    pub fn new() -> Self {
        use std::time::{SystemTime, UNIX_EPOCH};
        let now = SystemTime::now().duration_since(UNIX_EPOCH).unwrap();

        Self {
            alarm_severity: 0,
            alarm_status: 0,
            alarm_message: String::new(),
            timestamp_seconds: now.as_secs() as i64,
            timestamp_nanos: now.subsec_nanos() as i32,
            timestamp_user_tag: 0,
        }
    }

    /// Set alarm information
    pub fn alarm(mut self, severity: i32, status: i32, message: impl Into<String>) -> Self {
        self.alarm_severity = severity;
        self.alarm_status = status;
        self.alarm_message = message.into();
        self
    }

    /// Set timestamp (defaults to current time)
    pub fn timestamp(mut self, seconds: i64, nanos: i32, user_tag: i32) -> Self {
        self.timestamp_seconds = seconds;
        self.timestamp_nanos = nanos;
        self.timestamp_user_tag = user_tag;
        self
    }

    fn build(self) -> Result<cxx::UniquePtr<bridge::NTEnumMetadata>> {
        let alarm =
            bridge::create_alarm(self.alarm_severity, self.alarm_status, self.alarm_message);
        let time_stamp = bridge::create_time(
            self.timestamp_seconds,
            self.timestamp_nanos,
            self.timestamp_user_tag,
        );
        let metadata = bridge::create_enum_metadata(&alarm, &time_stamp);
        Ok(metadata)
    }
}

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