rvoip-sip 0.2.1

SIP umbrella for RVoIP: api/* (UnifiedCoordinator, StreamPeer, CallbackPeer, Endpoint), server/* (B2BUA helpers), adapter/* (rvoip-core::ConnectionAdapter impl)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
//! Simplified endpoint API for softphones, PBX accounts, demos, and IVR legs.
//!
//! [`Endpoint`] is the easiest rvoip-sip surface to start with. It wraps
//! [`StreamPeer`], keeps the existing [`SessionHandle`] and [`IncomingCall`]
//! types, and adds only the account/profile conveniences that SIP applications
//! usually need first.
//!
//! For PBX or SBC integrations that require non-standard or vendor INVITE
//! headers, call `endpoint.invite(to).with_extra_headers(...).send()` to
//! attach a caller-supplied `Vec<TypedHeader>` to the first INVITE.

#![deny(missing_docs)]

use std::fmt;
use std::fs;
use std::net::{IpAddr, Ipv4Addr, SocketAddr};
use std::path::{Path, PathBuf};
use std::str::FromStr;
use std::sync::Arc;
use std::time::Duration;

use serde::Deserialize;
use tokio::sync::Mutex;

use rvoip_sip_core::types::uri::{Scheme, Uri};

use crate::api::audio::{AudioReceiver, AudioSender, AudioStream};
use crate::api::events::Event;
use crate::api::handle::{CallId, SessionHandle};
use crate::api::incoming::{IncomingCall, IncomingCallGuard};
use crate::api::performance::PerformanceConfig;
use crate::api::stream_peer::{EventReceiver, PeerControl, StreamPeer};
use crate::api::unified::{
    Config, MediaMode, Registration, RegistrationHandle, RegistrationInfo, RegistrationStatus,
    SipTlsMode,
};
use crate::errors::{Result, SessionError};
use crate::types::Credentials;

/// A simplified SIP endpoint built on top of [`StreamPeer`].
///
/// Use `Endpoint` when an application wants a compact softphone/PBX-account
/// style API without losing access to the underlying stream/control objects.
/// Advanced applications can call [`control`](Self::control) or
/// [`into_stream_peer`](Self::into_stream_peer) and continue with the lower
/// level APIs.
pub struct Endpoint {
    peer: StreamPeer,
    registration: Option<Registration>,
    registration_handle: SharedRegistrationHandle,
    registrar: Option<String>,
    transport: EndpointTransport,
}

impl Endpoint {
    /// Start a new [`EndpointBuilder`].
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// # async fn example() -> rvoip_sip::Result<()> {
    /// let endpoint = rvoip_sip::Endpoint::builder()
    ///     .name("alice")
    ///     .build()
    ///     .await?;
    /// endpoint.shutdown().await?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn builder() -> EndpointBuilder {
        EndpointBuilder::new()
    }

    /// Build and start an endpoint from a serde-friendly configuration object.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// # async fn example(config: rvoip_sip::EndpointConfig) -> rvoip_sip::Result<()> {
    /// let endpoint = rvoip_sip::Endpoint::from_config(config).await?;
    /// endpoint.shutdown().await?;
    /// # Ok(())
    /// # }
    /// ```
    pub async fn from_config(config: EndpointConfig) -> Result<Self> {
        EndpointBuilder::from_config(config)?.build().await
    }

    /// Load endpoint configuration from a JSON file and start the endpoint.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// # async fn example() -> rvoip_sip::Result<()> {
    /// let endpoint = rvoip_sip::Endpoint::from_json_file("alice.json").await?;
    /// endpoint.shutdown().await?;
    /// # Ok(())
    /// # }
    /// ```
    pub async fn from_json_file(path: impl AsRef<Path>) -> Result<Self> {
        let text = fs::read_to_string(path.as_ref()).map_err(|err| {
            SessionError::ConfigError(format!(
                "failed to read endpoint JSON config '{}': {err}",
                path.as_ref().display()
            ))
        })?;
        let config = serde_json::from_str::<EndpointConfig>(&text).map_err(|err| {
            SessionError::ConfigError(format!(
                "failed to parse endpoint JSON config '{}': {err}",
                path.as_ref().display()
            ))
        })?;
        Self::from_config(config).await
    }

    /// Register the configured account with its registrar.
    ///
    /// Repeated calls return the existing registration handle. Build the
    /// endpoint with [`EndpointBuilder::account`],
    /// [`EndpointBuilder::password`], and [`EndpointBuilder::registrar`] or
    /// with [`EndpointBuilder::endpoint_account`] before calling this method.
    pub async fn register(&mut self) -> Result<RegistrationHandle> {
        let mut stored = self.registration_handle.lock().await;
        if let Some(handle) = stored.as_ref() {
            return Ok(handle.clone());
        }

        let registration = self.registration.clone().ok_or_else(|| {
            SessionError::ConfigError(
                "Endpoint has no complete registration account; set account, password, and registrar"
                    .to_string(),
            )
        })?;
        let mut b = self
            .peer
            .register(
                registration.registrar.clone(),
                registration.username.clone(),
                registration.password.clone(),
            )
            .with_expires(registration.expires);
        if let Some(from) = registration.from_uri.clone() {
            b = b.with_from_uri(from);
        }
        if let Some(contact) = registration.contact_uri.clone() {
            b = b.with_contact_uri(contact);
        }
        let handle = b.send().await?;
        *stored = Some(handle.clone());
        Ok(handle)
    }

    /// Register the configured account and wait for registrar confirmation.
    pub async fn register_and_wait(
        &mut self,
        timeout: Option<Duration>,
    ) -> Result<EndpointRegistrationInfo> {
        let mut events = self.events().await?;
        let handle = self.register().await?;
        wait_for_registration_result(&mut events, &handle, timeout).await
    }

    /// Unregister the current account if it has been registered.
    ///
    /// Calling this on an endpoint that has not registered is a no-op.
    pub async fn unregister(&mut self) -> Result<()> {
        let mut stored = self.registration_handle.lock().await;
        if let Some(handle) = stored.take() {
            self.peer.unregister(&handle).await?;
        }
        Ok(())
    }

    /// Initiate an outgoing call and wait for it to answer.
    pub async fn call_and_wait(
        &self,
        target: &str,
        timeout: Option<Duration>,
    ) -> Result<EndpointCall> {
        let call_id = self.invite(target)?.send().await?;
        let call = self.wrap_call(call_id);
        call.wait_for_answered(timeout).await
    }

    /// Wait for the next incoming call.
    pub async fn wait_for_incoming(&mut self) -> Result<EndpointIncomingCall> {
        let incoming = self.peer.wait_for_incoming().await?;
        Ok(EndpointIncomingCall::new(
            incoming,
            self.registrar.clone(),
            self.transport,
        ))
    }

    /// Subscribe to endpoint-level events without consuming the endpoint.
    pub async fn events(&self) -> Result<EndpointEvents> {
        let events = self.peer.control().subscribe_events().await?;
        Ok(EndpointEvents::new(
            events,
            self.peer.control().clone(),
            self.registrar.clone(),
            self.transport,
        ))
    }

    /// Split the endpoint into cloneable controls and an endpoint event stream.
    pub fn split(self) -> (EndpointControl, EndpointEvents) {
        let registration = self.registration;
        let registration_handle = self.registration_handle;
        let registrar = self.registrar;
        let transport = self.transport;
        let (control, events) = self.peer.split();
        let endpoint_control = EndpointControl::new(
            control.clone(),
            registration,
            registration_handle,
            registrar.clone(),
            transport,
        );
        let endpoint_events = EndpointEvents::new(events, control, registrar, transport);
        (endpoint_control, endpoint_events)
    }

    /// Access the command half of the wrapped [`StreamPeer`].
    pub fn control(&self) -> &PeerControl {
        self.peer.control()
    }

    /// Resolve a dial target the same way [`invite`](Self::invite) does.
    ///
    /// This is useful for logging or for handing the resolved URI to a lower
    /// level API.
    pub fn resolve_target(&self, target: &str) -> Result<String> {
        normalize_target(self.registrar.as_deref(), target, self.transport)
    }

    /// Begin building an outbound INVITE from this endpoint's
    /// registered AOR (or `local_uri`). Resolves bare extensions
    /// through the configured registrar. Returns an
    /// [`OutboundCallBuilder`](crate::api::send::OutboundCallBuilder).
    ///
    /// Returns `Err` only if the target can't be normalized into a SIP
    /// URI (e.g. a bare extension without a configured registrar).
    pub fn invite(&self, target: &str) -> Result<crate::api::send::OutboundCallBuilder> {
        let resolved = self.resolve_target(target)?;
        Ok(self.peer.control().invite(resolved))
    }

    /// Materialize an [`EndpointCall`] for a `CallId` returned by
    /// [`invite(...).send()`](Self::invite). Pairs with `invite()` the
    /// same way the unified coordinator's `session(...)` pairs with its
    /// bare builder — gives back the rich call wrapper around the raw
    /// [`SessionHandle`].
    pub fn wrap_call(&self, call_id: crate::api::handle::CallId) -> EndpointCall {
        let coord = self.peer.control().coordinator().clone();
        EndpointCall::new(
            crate::api::handle::SessionHandle::new(call_id, coord),
            self.registrar.clone(),
            self.transport,
        )
    }

    /// Consume this endpoint and return the wrapped [`StreamPeer`].
    pub fn into_stream_peer(self) -> StreamPeer {
        self.peer
    }

    /// Gracefully unregister and shut down the endpoint.
    pub async fn shutdown(self) -> Result<()> {
        self.peer.shutdown().await
    }
}

type SharedRegistrationHandle = Arc<Mutex<Option<RegistrationHandle>>>;

/// Cloneable command half returned by [`Endpoint::split`].
#[derive(Clone)]
pub struct EndpointControl {
    control: PeerControl,
    registration: Option<Registration>,
    registration_handle: SharedRegistrationHandle,
    registrar: Option<String>,
    transport: EndpointTransport,
}

impl EndpointControl {
    fn new(
        control: PeerControl,
        registration: Option<Registration>,
        registration_handle: SharedRegistrationHandle,
        registrar: Option<String>,
        transport: EndpointTransport,
    ) -> Self {
        Self {
            control,
            registration,
            registration_handle,
            registrar,
            transport,
        }
    }

    /// Register the configured account.
    pub async fn register(&self) -> Result<()> {
        let mut stored = self.registration_handle.lock().await;
        if stored.is_some() {
            return Ok(());
        }
        let registration = self.registration.clone().ok_or_else(|| {
            SessionError::ConfigError(
                "Endpoint has no complete registration account; set account, password, and registrar"
                    .to_string(),
            )
        })?;
        let mut b = self
            .control
            .coordinator()
            .register(
                registration.registrar,
                registration.username,
                registration.password,
            )
            .with_expires(registration.expires);
        if let Some(from) = registration.from_uri {
            b = b.with_from_uri(from);
        }
        if let Some(contact) = registration.contact_uri {
            b = b.with_contact_uri(contact);
        }
        let handle = b.send().await?;
        *stored = Some(handle);
        Ok(())
    }

    /// Register and wait for a registrar success or failure event.
    pub async fn register_and_wait(
        &self,
        timeout: Option<Duration>,
    ) -> Result<EndpointRegistrationInfo> {
        let mut events = self.events().await?;
        self.register().await?;
        let handle = self
            .registration_handle
            .lock()
            .await
            .clone()
            .ok_or_else(|| SessionError::Other("registration handle missing".to_string()))?;
        wait_for_registration_result(&mut events, &handle, timeout).await
    }

    /// Return the current registration information, if this endpoint registered.
    pub async fn registration_info(&self) -> Result<Option<EndpointRegistrationInfo>> {
        let handle = self.registration_handle.lock().await.clone();
        match handle {
            Some(handle) => self
                .control
                .coordinator()
                .registration_info(&handle)
                .await
                .map(EndpointRegistrationInfo::from)
                .map(Some),
            None => Ok(None),
        }
    }

    /// Unregister the current account, if registered.
    pub async fn unregister(&self) -> Result<()> {
        if let Some(handle) = self.registration_handle.lock().await.take() {
            self.control.coordinator().unregister(&handle).await?;
        }
        Ok(())
    }

    /// Unregister and wait for registrar confirmation.
    pub async fn unregister_and_wait(&self, timeout: Option<Duration>) -> Result<()> {
        if let Some(handle) = self.registration_handle.lock().await.take() {
            self.control
                .coordinator()
                .unregister_and_wait(&handle, timeout)
                .await?;
        }
        Ok(())
    }

    /// Subscribe to Endpoint-level events.
    pub async fn events(&self) -> Result<EndpointEvents> {
        let events = self.control.subscribe_events().await?;
        Ok(EndpointEvents::new(
            events,
            self.control.clone(),
            self.registrar.clone(),
            self.transport,
        ))
    }

    /// Resolve a dial target using this endpoint's account context.
    pub fn resolve_target(&self, target: &str) -> Result<String> {
        normalize_target(self.registrar.as_deref(), target, self.transport)
    }

    /// Begin building an outbound INVITE from this endpoint's
    /// account context. Resolves bare extensions through the configured
    /// registrar.
    pub fn invite(&self, target: &str) -> Result<crate::api::send::OutboundCallBuilder> {
        let resolved = self.resolve_target(target)?;
        Ok(self.control.invite(resolved))
    }

    /// Materialize an [`EndpointCall`] for a `CallId` returned by
    /// [`invite(...).send()`](Self::invite).
    pub fn wrap_call(&self, call_id: crate::api::handle::CallId) -> EndpointCall {
        let coord = self.control.coordinator().clone();
        EndpointCall::new(
            crate::api::handle::SessionHandle::new(call_id, coord),
            self.registrar.clone(),
            self.transport,
        )
    }

    /// Gracefully shut down the endpoint runtime.
    pub async fn shutdown(&self) -> Result<()> {
        self.control.coordinator().shutdown_gracefully(None).await
    }
}

/// Endpoint-level event stream returned by [`Endpoint::split`] and [`Endpoint::events`].
pub struct EndpointEvents {
    events: EventReceiver,
    control: PeerControl,
    registrar: Option<String>,
    transport: EndpointTransport,
}

impl EndpointEvents {
    fn new(
        events: EventReceiver,
        control: PeerControl,
        registrar: Option<String>,
        transport: EndpointTransport,
    ) -> Self {
        Self {
            events,
            control,
            registrar,
            transport,
        }
    }

    /// Wait for the next endpoint event.
    pub async fn next(&mut self) -> Result<Option<EndpointEvent>> {
        Ok(self.events.next().await.map(|event| self.map_event(event)))
    }

    /// Return the next endpoint event if one is ready immediately.
    pub fn try_next(&mut self) -> Option<EndpointEvent> {
        self.events.try_next().map(|event| self.map_event(event))
    }

    fn map_event(&self, event: Event) -> EndpointEvent {
        match event {
            Event::IncomingCall {
                call_id,
                from,
                to,
                sdp,
            } => {
                let incoming =
                    IncomingCall::new(call_id, from, to, sdp, self.control.coordinator().clone());
                EndpointEvent::IncomingCall(EndpointIncomingCall::new(
                    incoming,
                    self.registrar.clone(),
                    self.transport,
                ))
            }
            Event::CallProgress {
                call_id,
                status_code,
                reason,
                sdp,
            } => EndpointEvent::CallProgress {
                call_id: EndpointCallId(call_id),
                status_code,
                reason,
                has_sdp: sdp.is_some(),
            },
            Event::CallAnswered { call_id, sdp } => EndpointEvent::CallAnswered {
                call: EndpointCall::new(
                    SessionHandle::new(call_id, self.control.coordinator().clone()),
                    self.registrar.clone(),
                    self.transport,
                ),
                has_sdp: sdp.is_some(),
            },
            Event::CallEnded { call_id, reason } => EndpointEvent::CallEnded {
                call_id: EndpointCallId(call_id),
                reason,
            },
            Event::CallFailed {
                call_id,
                status_code,
                reason,
            } => EndpointEvent::CallFailed {
                call_id: EndpointCallId(call_id),
                status_code,
                reason,
            },
            Event::CallCancelled { call_id } => EndpointEvent::CallCancelled {
                call_id: EndpointCallId(call_id),
            },
            Event::CallOnHold { call_id } => EndpointEvent::LocalHold {
                call_id: EndpointCallId(call_id),
            },
            Event::CallResumed { call_id } => EndpointEvent::LocalResume {
                call_id: EndpointCallId(call_id),
            },
            Event::RemoteCallOnHold { call_id } => EndpointEvent::RemoteHold {
                call_id: EndpointCallId(call_id),
            },
            Event::RemoteCallResumed { call_id } => EndpointEvent::RemoteResume {
                call_id: EndpointCallId(call_id),
            },
            Event::DtmfReceived { call_id, digit } => EndpointEvent::DtmfReceived {
                call_id: EndpointCallId(call_id),
                digit,
            },
            Event::RegistrationSuccess {
                registrar,
                expires,
                contact,
            } => EndpointEvent::RegistrationChanged(EndpointRegistrationInfo {
                status: EndpointRegistrationStatus::Registered,
                registrar: Some(registrar),
                contact: Some(contact),
                expires_secs: Some(expires),
                accepted_expires_secs: Some(expires),
                next_refresh_in: None,
                retry_count: 0,
                last_failure: None,
            }),
            Event::RegistrationFailed {
                registrar,
                status_code,
                reason,
            } => EndpointEvent::RegistrationChanged(EndpointRegistrationInfo {
                status: EndpointRegistrationStatus::Failed,
                registrar: Some(registrar),
                contact: None,
                expires_secs: None,
                accepted_expires_secs: None,
                next_refresh_in: None,
                retry_count: 0,
                last_failure: Some(format!("{status_code} {reason}")),
            }),
            Event::UnregistrationSuccess { registrar } => {
                EndpointEvent::RegistrationChanged(EndpointRegistrationInfo {
                    status: EndpointRegistrationStatus::Unregistered,
                    registrar: Some(registrar),
                    contact: None,
                    expires_secs: None,
                    accepted_expires_secs: None,
                    next_refresh_in: None,
                    retry_count: 0,
                    last_failure: None,
                })
            }
            Event::UnregistrationFailed { registrar, reason } => {
                EndpointEvent::RegistrationChanged(EndpointRegistrationInfo {
                    status: EndpointRegistrationStatus::Failed,
                    registrar: Some(registrar),
                    contact: None,
                    expires_secs: None,
                    accepted_expires_secs: None,
                    next_refresh_in: None,
                    retry_count: 0,
                    last_failure: Some(reason),
                })
            }
            Event::NetworkError { call_id, error } => EndpointEvent::NetworkError {
                call_id: call_id.map(EndpointCallId),
                error,
            },
            Event::SipTrace(trace) => EndpointEvent::SipTrace(EndpointSipTrace {
                direction: trace.direction,
                transport: trace.transport,
                local_addr: trace.local_addr,
                remote_addr: trace.remote_addr,
                timestamp_unix_millis: trace.timestamp_unix_millis,
                start_line: trace.start_line,
                sip_call_id: trace.sip_call_id,
                session_id: trace.session_id.map(EndpointCallId),
                raw_message: trace.raw_message,
                original_len: trace.original_len,
                truncated: trace.truncated,
                redacted: trace.redacted,
            }),
            other => EndpointEvent::Info {
                call_id: other.call_id().cloned().map(EndpointCallId),
                message: format!("{other:?}"),
            },
        }
    }
}

/// Endpoint-level event type for softphone applications.
pub enum EndpointEvent {
    /// A new inbound call is ringing.
    IncomingCall(EndpointIncomingCall),
    /// An outgoing call received provisional progress.
    CallProgress {
        /// Call identifier.
        call_id: EndpointCallId,
        /// SIP status code.
        status_code: u16,
        /// SIP reason phrase.
        reason: String,
        /// Whether the event included SDP.
        has_sdp: bool,
    },
    /// A call was answered and is now controllable.
    CallAnswered {
        /// Active call handle.
        call: EndpointCall,
        /// Whether the event included SDP.
        has_sdp: bool,
    },
    /// A call ended.
    CallEnded {
        /// Call identifier.
        call_id: EndpointCallId,
        /// End reason.
        reason: String,
    },
    /// A call failed.
    CallFailed {
        /// Call identifier.
        call_id: EndpointCallId,
        /// SIP status code.
        status_code: u16,
        /// Failure reason.
        reason: String,
    },
    /// A ringing incoming call was cancelled by the caller.
    CallCancelled {
        /// Call identifier.
        call_id: EndpointCallId,
    },
    /// Local hold completed.
    LocalHold {
        /// Call identifier.
        call_id: EndpointCallId,
    },
    /// Local resume completed.
    LocalResume {
        /// Call identifier.
        call_id: EndpointCallId,
    },
    /// Remote hold was observed.
    RemoteHold {
        /// Call identifier.
        call_id: EndpointCallId,
    },
    /// Remote resume was observed.
    RemoteResume {
        /// Call identifier.
        call_id: EndpointCallId,
    },
    /// DTMF was received.
    DtmfReceived {
        /// Call identifier.
        call_id: EndpointCallId,
        /// Received digit.
        digit: char,
    },
    /// Registration state changed.
    RegistrationChanged(EndpointRegistrationInfo),
    /// SIP message observed at the transport boundary.
    SipTrace(EndpointSipTrace),
    /// A network error occurred.
    NetworkError {
        /// Call identifier, when known.
        call_id: Option<EndpointCallId>,
        /// Error text.
        error: String,
    },
    /// Informational event not otherwise modeled by the endpoint facade.
    Info {
        /// Call identifier, when known.
        call_id: Option<EndpointCallId>,
        /// Human-readable event summary.
        message: String,
    },
}

/// Endpoint-level SIP trace event.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct EndpointSipTrace {
    /// Inbound or outbound at the local transport boundary.
    pub direction: crate::api::events::SipTraceDirection,
    /// Transport flavour, for example `UDP`, `TCP`, or `TLS`.
    pub transport: String,
    /// Local socket address.
    pub local_addr: String,
    /// Remote socket address.
    pub remote_addr: String,
    /// Milliseconds since Unix epoch when the trace event was created.
    pub timestamp_unix_millis: u64,
    /// SIP start line.
    pub start_line: String,
    /// Wire-level SIP `Call-ID` header value when present.
    pub sip_call_id: Option<String>,
    /// Endpoint call/session id after mapping, when known.
    pub session_id: Option<EndpointCallId>,
    /// Redacted, optionally body-stripped SIP message text.
    pub raw_message: String,
    /// Original rendered message byte length before redaction/body stripping/truncation.
    pub original_len: usize,
    /// Whether `raw_message` was truncated for bounded diagnostics.
    pub truncated: bool,
    /// Whether sensitive headers were redacted.
    pub redacted: bool,
}

/// Opaque call identifier for Endpoint applications.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct EndpointCallId(CallId);

impl fmt::Display for EndpointCallId {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.0.fmt(f)
    }
}

/// Active call handle returned by Endpoint APIs.
#[derive(Clone)]
pub struct EndpointCall {
    handle: SessionHandle,
    registrar: Option<String>,
    transport: EndpointTransport,
}

impl EndpointCall {
    fn new(handle: SessionHandle, registrar: Option<String>, transport: EndpointTransport) -> Self {
        Self {
            handle,
            registrar,
            transport,
        }
    }

    /// Return this call's opaque identifier.
    pub fn id(&self) -> EndpointCallId {
        EndpointCallId(self.handle.id().clone())
    }

    /// Return the underlying session handle for advanced operations that are
    /// not yet modeled directly on the endpoint facade.
    pub fn as_session_handle(&self) -> &SessionHandle {
        &self.handle
    }

    /// Wait for this outgoing call to be answered.
    pub async fn wait_for_answered(&self, timeout: Option<Duration>) -> Result<Self> {
        let handle = self.handle.wait_for_answered(timeout).await?;
        Ok(Self::new(handle, self.registrar.clone(), self.transport))
    }

    /// Wait for this call to end.
    pub async fn wait_for_end(&self, timeout: Option<Duration>) -> Result<String> {
        self.handle.wait_for_end(timeout).await
    }

    /// Hang up the call.
    pub async fn hangup(&self) -> Result<()> {
        self.handle.hangup().await
    }

    /// Hang up the call and wait for teardown.
    pub async fn hangup_and_wait(&self, timeout: Option<Duration>) -> Result<String> {
        self.handle.hangup_and_wait(timeout).await
    }

    /// Put the call on local hold.
    pub async fn hold(&self) -> Result<()> {
        self.handle.hold().await
    }

    /// Resume a locally held call.
    pub async fn resume(&self) -> Result<()> {
        self.handle.resume().await
    }

    /// Mute local microphone media for the call.
    pub async fn mute(&self) -> Result<()> {
        self.handle.mute().await
    }

    /// Unmute local microphone media for the call.
    pub async fn unmute(&self) -> Result<()> {
        self.handle.unmute().await
    }

    /// Send an RFC 4733 DTMF digit.
    pub async fn send_dtmf(&self, digit: char) -> Result<()> {
        self.handle.send_dtmf(digit).await
    }

    /// Blind-transfer the call using Endpoint target resolution.
    pub async fn transfer(&self, target: &str) -> Result<()> {
        let target = normalize_target(self.registrar.as_deref(), target, self.transport)?;
        self.handle.transfer_blind(&target).await
    }

    /// Open the call's bidirectional audio stream.
    pub async fn audio(&self) -> Result<EndpointAudio> {
        self.handle.audio().await.map(EndpointAudio::new)
    }
}

impl fmt::Debug for EndpointCall {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("EndpointCall")
            .field("id", &self.id().to_string())
            .finish()
    }
}

/// Inbound call presented by [`EndpointEvent::IncomingCall`].
pub struct EndpointIncomingCall {
    incoming: IncomingCall,
    registrar: Option<String>,
    transport: EndpointTransport,
}

impl EndpointIncomingCall {
    fn new(
        incoming: IncomingCall,
        registrar: Option<String>,
        transport: EndpointTransport,
    ) -> Self {
        Self {
            incoming,
            registrar,
            transport,
        }
    }

    /// Return the inbound call identifier.
    pub fn id(&self) -> EndpointCallId {
        EndpointCallId(self.incoming.call_id.clone())
    }

    /// Return the caller URI.
    pub fn from(&self) -> &str {
        &self.incoming.from
    }

    /// Return the called URI.
    pub fn to(&self) -> &str {
        &self.incoming.to
    }

    /// Answer the incoming call.
    pub async fn answer(self) -> Result<EndpointCall> {
        let handle = self.incoming.accept().await?;
        Ok(EndpointCall::new(handle, self.registrar, self.transport))
    }

    /// Alias for [`answer`](Self::answer).
    pub async fn accept(self) -> Result<EndpointCall> {
        self.answer().await
    }

    /// Defer the incoming call decision and return a guard.
    pub fn defer(self, watchdog: Duration) -> IncomingCallGuard {
        self.incoming.defer(watchdog)
    }

    /// Reject the call with 603 Decline.
    pub async fn decline(self) -> Result<()> {
        self.reject(603, "Decline").await
    }

    /// Reject the call with 486 Busy Here.
    pub async fn busy(self) -> Result<()> {
        self.reject(486, "Busy Here").await
    }

    /// Reject the call with an explicit SIP status and reason phrase.
    pub async fn reject(self, status: u16, reason: &str) -> Result<()> {
        self.incoming.reject(status, reason);
        Ok(())
    }

    /// Redirect the caller to another SIP URI with `302 Moved Temporarily`.
    pub async fn redirect_to(self, target: impl Into<String>) -> Result<()> {
        self.incoming.redirect_to(target).await
    }

    /// Redirect the caller with an explicit 3xx status and Contact list.
    pub async fn redirect_with_contacts<I, S>(self, status: u16, contacts: I) -> Result<()>
    where
        I: IntoIterator<Item = S>,
        S: Into<String>,
    {
        self.incoming.redirect_with_contacts(status, contacts).await
    }
}

impl fmt::Debug for EndpointIncomingCall {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("EndpointIncomingCall")
            .field("id", &self.id().to_string())
            .field("from", &self.from())
            .field("to", &self.to())
            .finish()
    }
}

/// Bidirectional endpoint audio stream for a call.
pub struct EndpointAudio {
    stream: AudioStream,
}

impl EndpointAudio {
    fn new(stream: AudioStream) -> Self {
        Self { stream }
    }

    /// Split the audio stream into sender and receiver halves.
    pub fn split(self) -> (EndpointAudioSender, EndpointAudioReceiver) {
        let (sender, receiver) = self.stream.split();
        (
            EndpointAudioSender { sender },
            EndpointAudioReceiver { receiver },
        )
    }
}

/// Send half of endpoint call audio.
#[derive(Clone)]
pub struct EndpointAudioSender {
    sender: AudioSender,
}

impl EndpointAudioSender {
    /// Send one audio frame to the remote party.
    pub async fn send(&self, frame: EndpointAudioFrame) -> Result<()> {
        self.sender.send(frame.into()).await
    }

    /// Return whether the underlying audio channel is open.
    pub fn is_open(&self) -> bool {
        self.sender.is_open()
    }
}

/// Receive half of endpoint call audio.
pub struct EndpointAudioReceiver {
    receiver: AudioReceiver,
}

impl EndpointAudioReceiver {
    /// Wait for the next audio frame from the remote party.
    pub async fn recv(&mut self) -> Option<EndpointAudioFrame> {
        self.receiver.recv().await.map(EndpointAudioFrame::from)
    }

    /// Try to receive an audio frame without blocking.
    pub fn try_recv(&mut self) -> Option<EndpointAudioFrame> {
        self.receiver.try_recv().map(EndpointAudioFrame::from)
    }
}

/// Mono or interleaved PCM16 audio frame used by Endpoint audio.
#[derive(Debug, Clone, Deserialize)]
pub struct EndpointAudioFrame {
    /// PCM16 samples, interleaved when channels is greater than one.
    pub samples: Vec<i16>,
    /// Sample rate in Hz.
    pub sample_rate: u32,
    /// Number of channels.
    pub channels: u8,
    /// RTP-style timestamp.
    pub timestamp: u32,
}

impl EndpointAudioFrame {
    /// Create a new endpoint audio frame.
    pub fn new(samples: Vec<i16>, sample_rate: u32, channels: u8, timestamp: u32) -> Self {
        Self {
            samples,
            sample_rate,
            channels,
            timestamp,
        }
    }

    /// Create a 20 ms, 8 kHz mono PCM16 frame.
    pub fn pcmu_sized_mono_8khz(samples: Vec<i16>, timestamp: u32) -> Self {
        Self::new(samples, 8_000, 1, timestamp)
    }

    /// Return samples per channel.
    pub fn samples_per_channel(&self) -> usize {
        self.samples.len() / self.channels.max(1) as usize
    }
}

impl From<EndpointAudioFrame> for rvoip_media_core::types::AudioFrame {
    fn from(frame: EndpointAudioFrame) -> Self {
        rvoip_media_core::types::AudioFrame::new(
            frame.samples,
            frame.sample_rate,
            frame.channels,
            frame.timestamp,
        )
    }
}

impl From<rvoip_media_core::types::AudioFrame> for EndpointAudioFrame {
    fn from(frame: rvoip_media_core::types::AudioFrame) -> Self {
        Self {
            samples: frame.samples,
            sample_rate: frame.sample_rate,
            channels: frame.channels,
            timestamp: frame.timestamp,
        }
    }
}

/// Registration state exposed by Endpoint.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum EndpointRegistrationStatus {
    /// REGISTER is in progress.
    Registering,
    /// The registrar accepted the binding.
    Registered,
    /// Unregister is in progress.
    Unregistering,
    /// No active binding is known.
    Unregistered,
    /// The most recent registration operation failed.
    Failed,
}

/// Registration lifecycle snapshot exposed by Endpoint.
#[derive(Debug, Clone)]
pub struct EndpointRegistrationInfo {
    /// Coarse registration status.
    pub status: EndpointRegistrationStatus,
    /// Registrar URI.
    pub registrar: Option<String>,
    /// Contact URI currently registered.
    pub contact: Option<String>,
    /// Requested expiry.
    pub expires_secs: Option<u32>,
    /// Registrar-accepted expiry.
    pub accepted_expires_secs: Option<u32>,
    /// Duration until the next automatic refresh.
    pub next_refresh_in: Option<Duration>,
    /// Retry count for the current or last registration flow.
    pub retry_count: u32,
    /// Last failure, if any.
    pub last_failure: Option<String>,
}

impl From<RegistrationInfo> for EndpointRegistrationInfo {
    fn from(info: RegistrationInfo) -> Self {
        Self {
            status: match info.status {
                RegistrationStatus::Registering => EndpointRegistrationStatus::Registering,
                RegistrationStatus::Registered => EndpointRegistrationStatus::Registered,
                RegistrationStatus::Unregistering => EndpointRegistrationStatus::Unregistering,
                RegistrationStatus::Unregistered => EndpointRegistrationStatus::Unregistered,
                RegistrationStatus::Failed => EndpointRegistrationStatus::Failed,
            },
            registrar: info.registrar,
            contact: info.contact,
            expires_secs: info.expires_secs,
            accepted_expires_secs: info.accepted_expires_secs,
            next_refresh_in: info.next_refresh_in,
            retry_count: info.retry_count,
            last_failure: info.last_failure,
        }
    }
}

/// Account information used by [`EndpointBuilder`].
///
/// `EndpointAccount` describes the SIP registrar credentials and optional
/// identity overrides. It maps directly to [`Registration`] plus the default
/// INVITE digest credentials stored on [`Config`].
#[derive(Debug, Clone)]
pub struct EndpointAccount {
    /// SIP URI of the registrar, for example `sip:pbx.example.com` or
    /// `sips:pbx.example.com:5061`.
    pub registrar: String,
    /// Address-of-record user, usually the extension or SIP username.
    pub username: String,
    /// Optional digest-auth username when it differs from [`username`](Self::username).
    pub auth_username: Option<String>,
    /// Digest-auth password.
    pub password: String,
    /// Registration expiry in seconds.
    pub expires: u32,
    /// Optional From/AoR URI override.
    pub from_uri: Option<String>,
    /// Optional Contact URI override.
    pub contact_uri: Option<String>,
}

impl EndpointAccount {
    /// Create a complete endpoint account.
    ///
    /// # Examples
    ///
    /// ```
    /// let account = rvoip_sip::EndpointAccount::new(
    ///     "sip:pbx.example.com",
    ///     "1001",
    ///     "secret",
    /// );
    /// assert_eq!(account.expires, 3600);
    /// ```
    pub fn new(
        registrar: impl Into<String>,
        username: impl Into<String>,
        password: impl Into<String>,
    ) -> Self {
        Self {
            registrar: registrar.into(),
            username: username.into(),
            auth_username: None,
            password: password.into(),
            expires: 3600,
            from_uri: None,
            contact_uri: None,
        }
    }

    /// Set the digest-auth username.
    pub fn auth_username(mut self, username: impl Into<String>) -> Self {
        self.auth_username = Some(username.into());
        self
    }

    /// Set the registration expiry in seconds.
    pub fn expires(mut self, seconds: u32) -> Self {
        self.expires = seconds;
        self
    }

    /// Override the SIP From/AoR URI.
    pub fn from_uri(mut self, uri: impl Into<String>) -> Self {
        self.from_uri = Some(uri.into());
        self
    }

    /// Override the SIP Contact URI.
    pub fn contact_uri(mut self, uri: impl Into<String>) -> Self {
        self.contact_uri = Some(uri.into());
        self
    }
}

/// Serde-friendly endpoint configuration for CLI tools and simple apps.
#[derive(Debug, Clone, Default, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct EndpointConfig {
    /// Display/configuration name.
    pub name: Option<String>,
    /// Deployment profile shortcut.
    pub profile: Option<EndpointProfileName>,
    /// Top-level bind shortcut.
    pub bind: Option<SocketAddr>,
    /// Top-level advertised SIP address shortcut.
    pub advertise: Option<SocketAddr>,
    /// SIP account configuration.
    pub account: Option<EndpointAccountConfig>,
    /// Network and signalling settings.
    pub network: Option<EndpointNetworkConfig>,
    /// Media settings.
    pub media: Option<EndpointMediaConfig>,
    /// Performance profile settings.
    pub performance: Option<PerformanceConfig>,
    /// Whether automatic `180 Ringing` is sent for inbound INVITEs.
    pub auto_180_ringing: Option<bool>,
    /// Whether automatic `100 Trying` timer tasks are armed for inbound INVITEs.
    pub auto_100_trying: Option<bool>,
    /// Whether inbound INVITEs are immediately accepted before app callbacks.
    pub fast_auto_accept_incoming_calls: Option<bool>,
    /// Cleanup-stage timing diagnostics.
    pub cleanup_diagnostics: Option<bool>,
    /// Per-operation cleanup diagnostic event logs.
    pub cleanup_diagnostic_events: Option<bool>,
    /// App-facing event buffer capacity.
    pub app_event_channel_capacity: Option<usize>,
    /// Per-transaction command channel capacity.
    pub sip_transaction_command_channel_capacity: Option<usize>,
    /// Server-side inbound call admission limit.
    pub server_call_admission_limit: Option<usize>,
    /// Soft threshold where server-side admission starts pacing.
    pub server_call_admission_soft_limit: Option<usize>,
    /// Delay in milliseconds while above the soft admission threshold.
    pub server_call_admission_pacing_delay_ms: Option<u64>,
    /// Retry-After seconds for server overload rejections.
    pub server_overload_retry_after_secs: Option<u32>,
    /// RSS growth threshold used by perf soak release gates.
    #[cfg(feature = "perf-tests")]
    pub perf_max_rss_growth_mb_per_hr: Option<f64>,
    /// SRTP negotiation diagnostic log lines.
    pub srtp_diagnostics: Option<bool>,
    /// RTP packet diagnostic log lines.
    pub rtp_diagnostics: Option<bool>,
    /// SDP media diagnostic log lines.
    pub media_sdp_diagnostics: Option<bool>,
    /// SIP trace diagnostics.
    pub sip_trace: Option<crate::api::events::SipTraceConfig>,
    /// Whether an application should register immediately after startup.
    pub register_on_start: Option<bool>,
}

/// Serde-friendly SIP account settings.
#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct EndpointAccountConfig {
    /// SIP registrar URI.
    pub registrar: String,
    /// SIP username or extension.
    pub username: String,
    /// Optional digest username when it differs from username.
    pub auth_username: Option<String>,
    /// Digest password.
    pub password: String,
    /// Registration expiry in seconds.
    pub expires: Option<u32>,
    /// Optional From/AoR URI override.
    pub from_uri: Option<String>,
    /// Optional Contact URI override.
    pub contact_uri: Option<String>,
}

impl TryFrom<EndpointAccountConfig> for EndpointAccount {
    type Error = SessionError;

    fn try_from(config: EndpointAccountConfig) -> Result<Self> {
        let mut account = EndpointAccount::new(config.registrar, config.username, config.password);
        if let Some(auth_username) = config.auth_username {
            account = account.auth_username(auth_username);
        }
        if let Some(expires) = config.expires {
            account = account.expires(expires);
        }
        if let Some(from_uri) = config.from_uri {
            account = account.from_uri(from_uri);
        }
        if let Some(contact_uri) = config.contact_uri {
            account = account.contact_uri(contact_uri);
        }
        Ok(account)
    }
}

/// Serde-friendly network and signalling settings.
#[derive(Debug, Clone, Default, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct EndpointNetworkConfig {
    /// SIP bind address.
    pub bind: Option<SocketAddr>,
    /// Advertised SIP address.
    pub advertise: Option<SocketAddr>,
    /// Preferred signalling transport.
    pub transport: Option<EndpointTransport>,
    /// STUN server for media public-address discovery.
    pub stun: Option<String>,
    /// Outbound proxy URI.
    pub outbound_proxy: Option<String>,
    /// SIP instance URN for registered-flow profiles.
    pub sip_instance: Option<String>,
    /// TLS listener bind address.
    pub tls_bind: Option<SocketAddr>,
    /// TLS certificate path.
    pub tls_cert_path: Option<PathBuf>,
    /// TLS private key path.
    pub tls_key_path: Option<PathBuf>,
    /// Optional UDP parse worker count.
    pub udp_parse_workers: Option<usize>,
    /// Optional per-worker UDP parse queue capacity.
    pub udp_parse_queue_capacity: Option<usize>,
}

/// Serde-friendly media settings.
#[derive(Debug, Clone, Default, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct EndpointMediaConfig {
    /// Public media address as an IP address or socket address string.
    pub public_address: Option<String>,
    /// RTP media port range start.
    pub port_start: Option<u16>,
    /// RTP media port range end.
    pub port_end: Option<u16>,
    /// Whether real media-core RTP allocation is enabled.
    pub enabled: Option<bool>,
    /// SDP RTP port to advertise when media is disabled.
    pub signaling_only_rtp_port: Option<u16>,
    /// SRTP negotiation policy.
    pub srtp: Option<EndpointSrtpMode>,
}

/// Serde-friendly deployment profile names.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum EndpointProfileName {
    /// Local loopback development.
    Local,
    /// Directly reachable LAN/PBX endpoint.
    LanPbx,
    /// UDP Asterisk/PBX endpoint.
    AsteriskUdp,
    /// Asterisk TLS and mandatory SRTP registered flow.
    AsteriskTlsSrtp,
    /// FreeSWITCH internal profile.
    FreeswitchInternal,
    /// FreeSWITCH TLS and SRTP reachable-contact profile.
    FreeswitchTlsSrtp,
    /// Carrier/SBC profile.
    CarrierSbc,
}

impl From<EndpointProfileName> for EndpointProfile {
    fn from(profile: EndpointProfileName) -> Self {
        match profile {
            EndpointProfileName::Local => EndpointProfile::Local,
            EndpointProfileName::LanPbx => EndpointProfile::LanPbx,
            EndpointProfileName::AsteriskUdp => EndpointProfile::AsteriskUdp,
            EndpointProfileName::AsteriskTlsSrtp => EndpointProfile::AsteriskTlsSrtpRegisteredFlow,
            EndpointProfileName::FreeswitchInternal => EndpointProfile::FreeSwitchInternal,
            EndpointProfileName::FreeswitchTlsSrtp => {
                EndpointProfile::FreeSwitchTlsSrtpReachableContact
            }
            EndpointProfileName::CarrierSbc => EndpointProfile::CarrierSbc,
        }
    }
}

/// Preferred signalling transport for endpoint-generated SIP URIs.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum EndpointTransport {
    /// UDP signalling.
    Udp,
    /// TCP signalling.
    Tcp,
    /// TLS signalling with `sips:` targets.
    Tls,
}

/// SRTP policy for endpoint media negotiation.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum EndpointSrtpMode {
    /// Do not offer SRTP.
    Off,
    /// Offer SRTP but allow RTP fallback.
    Offer,
    /// Require SRTP.
    Required,
}

/// Deployment profile used by [`EndpointBuilder`].
///
/// These variants intentionally mirror the existing [`Config`] profile
/// constructors so `Endpoint` remains a convenience layer, not a second SIP
/// configuration system.
#[derive(Debug, Clone)]
pub enum EndpointProfile {
    /// Local loopback development profile.
    Local,
    /// Directly reachable LAN PBX endpoint.
    LanPbx,
    /// UDP Asterisk/PBX endpoint profile.
    AsteriskUdp,
    /// Asterisk TLS + mandatory SDES-SRTP with symmetric registered-flow reuse.
    AsteriskTlsSrtpRegisteredFlow,
    /// FreeSWITCH/Sofia internal LAN profile.
    FreeSwitchInternal,
    /// FreeSWITCH TLS + mandatory SDES-SRTP with a directly reachable TLS Contact.
    FreeSwitchTlsSrtpReachableContact,
    /// Carrier/SBC style TLS registered-flow operation with outbound proxy.
    CarrierSbc,
    /// Fully custom config; builder account and registration conveniences still apply.
    Custom(Config),
}

impl Default for EndpointProfile {
    fn default() -> Self {
        Self::Local
    }
}

/// Builder for [`Endpoint`].
///
/// The builder first selects a deployment profile, then applies account,
/// registration, media-port, and custom configuration overrides before
/// starting the wrapped [`StreamPeer`].
pub struct EndpointBuilder {
    name: Option<String>,
    profile: EndpointProfile,
    bind_addr: Option<SocketAddr>,
    advertised_addr: Option<SocketAddr>,
    tls_bind_addr: Option<SocketAddr>,
    tls_cert_path: Option<std::path::PathBuf>,
    tls_key_path: Option<std::path::PathBuf>,
    media_port_start: Option<u16>,
    media_port_end: Option<u16>,
    media_public_addr: Option<SocketAddr>,
    media_mode: Option<MediaMode>,
    stun_server: Option<String>,
    outbound_proxy_uri: Option<String>,
    sip_instance: Option<String>,
    transport: EndpointTransport,
    sip_udp_parse_workers: Option<usize>,
    sip_udp_parse_queue_capacity: Option<usize>,
    performance: Option<PerformanceConfig>,
    srtp_mode: Option<EndpointSrtpMode>,
    auto_180_ringing: Option<bool>,
    auto_100_trying: Option<bool>,
    fast_auto_accept_incoming_calls: Option<bool>,
    cleanup_diagnostics: Option<bool>,
    cleanup_diagnostic_events: Option<bool>,
    app_event_channel_capacity: Option<usize>,
    sip_transaction_command_channel_capacity: Option<usize>,
    server_call_admission_limit: Option<usize>,
    server_call_admission_soft_limit: Option<usize>,
    server_call_admission_pacing_delay_ms: Option<u64>,
    server_overload_retry_after_secs: Option<u32>,
    #[cfg(feature = "perf-tests")]
    perf_max_rss_growth_mb_per_hr: Option<f64>,
    srtp_diagnostics: Option<bool>,
    rtp_diagnostics: Option<bool>,
    media_sdp_diagnostics: Option<bool>,
    account_username: Option<String>,
    auth_username: Option<String>,
    password: Option<String>,
    registrar: Option<String>,
    expires: u32,
    sip_trace: Option<crate::api::events::SipTraceConfig>,
    from_uri: Option<String>,
    contact_uri: Option<String>,
    configurators: Vec<Box<dyn FnOnce(&mut Config) + Send>>,
}

impl EndpointBuilder {
    /// Create a builder with the local profile.
    pub fn new() -> Self {
        Self {
            name: None,
            profile: EndpointProfile::Local,
            bind_addr: None,
            advertised_addr: None,
            tls_bind_addr: None,
            tls_cert_path: None,
            tls_key_path: None,
            media_port_start: None,
            media_port_end: None,
            media_public_addr: None,
            media_mode: None,
            stun_server: None,
            outbound_proxy_uri: None,
            sip_instance: None,
            transport: EndpointTransport::Udp,
            sip_udp_parse_workers: None,
            sip_udp_parse_queue_capacity: None,
            performance: None,
            srtp_mode: None,
            auto_180_ringing: None,
            auto_100_trying: None,
            fast_auto_accept_incoming_calls: None,
            cleanup_diagnostics: None,
            cleanup_diagnostic_events: None,
            app_event_channel_capacity: None,
            sip_transaction_command_channel_capacity: None,
            server_call_admission_limit: None,
            server_call_admission_soft_limit: None,
            server_call_admission_pacing_delay_ms: None,
            server_overload_retry_after_secs: None,
            #[cfg(feature = "perf-tests")]
            perf_max_rss_growth_mb_per_hr: None,
            srtp_diagnostics: None,
            rtp_diagnostics: None,
            media_sdp_diagnostics: None,
            account_username: None,
            auth_username: None,
            password: None,
            registrar: None,
            expires: 3600,
            sip_trace: None,
            from_uri: None,
            contact_uri: None,
            configurators: Vec::new(),
        }
    }

    /// Create a builder from a serde-friendly endpoint configuration object.
    pub fn from_config(config: EndpointConfig) -> Result<Self> {
        let mut builder = EndpointBuilder::new();

        if let Some(name) = config.name {
            builder = builder.name(name);
        }
        if let Some(profile) = config.profile {
            builder = builder.profile(profile.into());
        }
        if let Some(performance) = config.performance {
            builder = builder.performance_config(performance);
        }
        if let Some(bind) = config.bind.or(config.network.as_ref().and_then(|n| n.bind)) {
            builder = builder.bind_addr(bind);
        }
        if let Some(advertise) = config
            .advertise
            .or(config.network.as_ref().and_then(|n| n.advertise))
        {
            builder = builder.advertised_addr(advertise);
        }

        if let Some(account) = config.account {
            builder = builder.endpoint_account(account.try_into()?);
        }
        if let Some(auto_180_ringing) = config.auto_180_ringing {
            builder = builder.auto_180_ringing(auto_180_ringing);
        }
        if let Some(auto_100_trying) = config.auto_100_trying {
            builder = builder.auto_100_trying(auto_100_trying);
        }
        if let Some(fast_auto_accept) = config.fast_auto_accept_incoming_calls {
            builder = builder.fast_auto_accept_incoming_calls(fast_auto_accept);
        }
        if let Some(cleanup_diagnostics) = config.cleanup_diagnostics {
            builder = builder.cleanup_diagnostics(cleanup_diagnostics);
        }
        if let Some(cleanup_diagnostic_events) = config.cleanup_diagnostic_events {
            builder = builder.cleanup_diagnostic_events(cleanup_diagnostic_events);
        }
        if let Some(capacity) = config.app_event_channel_capacity {
            builder = builder.app_event_channel_capacity(capacity);
        }
        if let Some(capacity) = config.sip_transaction_command_channel_capacity {
            builder = builder.sip_transaction_command_channel_capacity(capacity);
        }
        if let Some(limit) = config.server_call_admission_limit {
            builder = builder.server_call_admission_limit(limit);
        }
        if let Some(limit) = config.server_call_admission_soft_limit {
            builder = builder.server_call_admission_soft_limit(limit);
        }
        if let Some(delay_ms) = config.server_call_admission_pacing_delay_ms {
            builder = builder.server_call_admission_pacing_delay_ms(delay_ms);
        }
        if let Some(seconds) = config.server_overload_retry_after_secs {
            builder = builder.server_overload_retry_after_secs(seconds);
        }
        #[cfg(feature = "perf-tests")]
        if let Some(limit) = config.perf_max_rss_growth_mb_per_hr {
            builder = builder.perf_max_rss_growth_mb_per_hr(limit);
        }
        if let Some(srtp_diagnostics) = config.srtp_diagnostics {
            builder = builder.srtp_diagnostics(srtp_diagnostics);
        }
        if let Some(rtp_diagnostics) = config.rtp_diagnostics {
            builder = builder.rtp_diagnostics(rtp_diagnostics);
        }
        if let Some(media_sdp_diagnostics) = config.media_sdp_diagnostics {
            builder = builder.media_sdp_diagnostics(media_sdp_diagnostics);
        }

        if let Some(network) = config.network {
            if let Some(transport) = network.transport {
                builder = builder.transport(transport);
            }
            if let Some(stun) = network.stun {
                builder = builder.stun_server(stun);
            }
            if let Some(proxy) = network.outbound_proxy {
                builder = builder.outbound_proxy(proxy);
            }
            if let Some(instance) = network.sip_instance {
                builder = builder.sip_instance(instance);
            }
            if let Some(tls_bind) = network.tls_bind {
                builder = builder.tls_bind_addr(tls_bind);
            }
            if let Some(path) = network.tls_cert_path {
                builder = builder.tls_cert_path(path);
            }
            if let Some(path) = network.tls_key_path {
                builder = builder.tls_key_path(path);
            }
            if let Some(workers) = network.udp_parse_workers {
                builder = builder.sip_udp_parse_workers(workers);
            }
            if let Some(capacity) = network.udp_parse_queue_capacity {
                builder = builder.sip_udp_parse_queue_capacity(capacity);
            }
        }

        if let Some(media) = config.media {
            if let Some(public) = media.public_address {
                builder = builder.media_public_addr(parse_media_public_address(&public)?);
            }
            if let Some(start) = media.port_start {
                let end = media.port_end.unwrap_or(start);
                builder = builder.media_ports(start, end);
            } else if let Some(end) = media.port_end {
                builder = builder.media_ports(Config::DEFAULT_MEDIA_PORT_START, end);
            }
            if let Some(srtp) = media.srtp {
                builder = builder.srtp(srtp);
            }
            if media.enabled == Some(false) || media.signaling_only_rtp_port.is_some() {
                builder = builder.signaling_only_media(media.signaling_only_rtp_port.unwrap_or(9));
            } else if media.enabled == Some(true) {
                builder = builder.media_enabled(true);
            }
        }

        if let Some(sip_trace) = config.sip_trace {
            builder = builder.sip_trace(sip_trace);
        }

        Ok(builder)
    }

    /// Set the display/configuration name.
    pub fn name(mut self, name: impl Into<String>) -> Self {
        self.name = Some(name.into());
        self
    }

    /// Set the SIP account username or extension.
    pub fn account(mut self, username: impl Into<String>) -> Self {
        self.account_username = Some(username.into());
        self
    }

    /// Set all account fields at once.
    pub fn endpoint_account(mut self, account: EndpointAccount) -> Self {
        self.registrar = Some(account.registrar);
        self.account_username = Some(account.username);
        self.auth_username = account.auth_username;
        self.password = Some(account.password);
        self.expires = account.expires;
        self.from_uri = account.from_uri;
        self.contact_uri = account.contact_uri;
        self
    }

    /// Set the digest-auth username when it differs from the account username.
    pub fn auth_username(mut self, username: impl Into<String>) -> Self {
        self.auth_username = Some(username.into());
        self
    }

    /// Set the digest-auth password.
    pub fn password(mut self, password: impl Into<String>) -> Self {
        self.password = Some(password.into());
        self
    }

    /// Set the SIP registrar URI.
    pub fn registrar(mut self, registrar: impl Into<String>) -> Self {
        self.registrar = Some(registrar.into());
        self
    }

    /// Set the registration expiry in seconds.
    pub fn expires(mut self, seconds: u32) -> Self {
        self.expires = seconds;
        self
    }

    /// Select a deployment profile.
    pub fn profile(mut self, profile: EndpointProfile) -> Self {
        self.profile = profile;
        self
    }

    /// Apply a serde-friendly configuration object to this builder.
    pub fn config(self, config: EndpointConfig) -> Result<Self> {
        let mut configured = EndpointBuilder::from_config(config)?;
        if self.name.is_some() {
            configured.name = self.name;
        }
        if self.sip_trace.is_some() {
            configured.sip_trace = self.sip_trace;
        }
        Ok(configured)
    }

    /// Set the SIP bind address.
    pub fn bind_addr(mut self, addr: SocketAddr) -> Self {
        self.bind_addr = Some(addr);
        self
    }

    /// Set the SIP advertised/public address.
    pub fn advertised_addr(mut self, addr: SocketAddr) -> Self {
        self.advertised_addr = Some(addr);
        self
    }

    /// Set the SIP TLS listener bind address.
    pub fn tls_bind_addr(mut self, addr: SocketAddr) -> Self {
        self.tls_bind_addr = Some(addr);
        self
    }

    /// Set the TLS listener certificate path.
    pub fn tls_cert_path(mut self, path: impl Into<std::path::PathBuf>) -> Self {
        self.tls_cert_path = Some(path.into());
        self
    }

    /// Set the TLS listener private-key path.
    pub fn tls_key_path(mut self, path: impl Into<std::path::PathBuf>) -> Self {
        self.tls_key_path = Some(path.into());
        self
    }

    /// Set the RTP media port range.
    pub fn media_ports(mut self, start: u16, end: u16) -> Self {
        self.media_port_start = Some(start);
        self.media_port_end = Some(end);
        self
    }

    /// Enable or disable real media-core RTP allocation.
    pub fn media_enabled(mut self, enabled: bool) -> Self {
        self.media_mode = Some(if enabled {
            MediaMode::Enabled
        } else {
            MediaMode::SignalingOnly { sdp_rtp_port: 9 }
        });
        self
    }

    /// Skip media-core RTP allocation while still generating SDP.
    pub fn signaling_only_media(mut self, sdp_rtp_port: u16) -> Self {
        self.media_mode = Some(MediaMode::SignalingOnly { sdp_rtp_port });
        self
    }

    /// Set the public RTP media address advertised in SDP.
    pub fn media_public_addr(mut self, addr: SocketAddr) -> Self {
        self.media_public_addr = Some(addr);
        self
    }

    /// Set a public RTP media IP address, leaving the negotiated media port dynamic.
    pub fn media_public_ip(mut self, addr: IpAddr) -> Self {
        self.media_public_addr = Some(SocketAddr::new(addr, 0));
        self
    }

    /// Set a STUN server for best-effort media public-address discovery.
    pub fn stun_server(mut self, server: impl Into<String>) -> Self {
        self.stun_server = Some(server.into());
        self
    }

    /// Set an outbound proxy URI for carrier/SBC-style operation.
    pub fn outbound_proxy(mut self, uri: impl Into<String>) -> Self {
        self.outbound_proxy_uri = Some(uri.into());
        self
    }

    /// Set the RFC 5626 SIP instance URN used by registered-flow profiles.
    pub fn sip_instance(mut self, urn: impl Into<String>) -> Self {
        self.sip_instance = Some(urn.into());
        self
    }

    /// Set the preferred signalling transport for generated SIP URIs.
    pub fn transport(mut self, transport: EndpointTransport) -> Self {
        self.transport = transport;
        self
    }

    /// Set the UDP parse worker count.
    pub fn sip_udp_parse_workers(mut self, workers: usize) -> Self {
        self.sip_udp_parse_workers = Some(workers);
        self
    }

    /// Set the per-worker UDP parse queue capacity.
    pub fn sip_udp_parse_queue_capacity(mut self, capacity: usize) -> Self {
        self.sip_udp_parse_queue_capacity = Some(capacity);
        self
    }

    /// Apply a YAML-backed performance recipe.
    pub fn performance_config(mut self, performance: PerformanceConfig) -> Self {
        self.performance = Some(performance);
        self
    }

    /// Apply the PBX media server performance recipe.
    pub fn pbx_media_server_performance(mut self, capacity: usize) -> Self {
        self.performance = Some(PerformanceConfig::pbx_media_server(capacity));
        self
    }

    /// Apply the signaling-only high-performance server recipe.
    pub fn signaling_only_server_high_performance(mut self, capacity: usize) -> Self {
        self.performance = Some(PerformanceConfig::signaling_only_server_high_performance(
            capacity,
        ));
        self
    }

    /// Apply the signaling-only high-performance server recipe with an explicit SDP RTP port.
    pub fn signaling_only_server_high_performance_with_port(
        mut self,
        capacity: usize,
        sdp_rtp_port: u16,
    ) -> Self {
        self.performance = Some(
            PerformanceConfig::signaling_only_server_high_performance(capacity)
                .with_signaling_only_rtp_port(sdp_rtp_port),
        );
        self
    }

    /// Enable or disable automatic `180 Ringing` on inbound INVITEs.
    pub fn auto_180_ringing(mut self, enabled: bool) -> Self {
        self.auto_180_ringing = Some(enabled);
        self
    }

    /// Enable or disable automatic `100 Trying` timer tasks on inbound INVITEs.
    pub fn auto_100_trying(mut self, enabled: bool) -> Self {
        self.auto_100_trying = Some(enabled);
        self
    }

    /// Enable or disable immediate session-path accept for inbound INVITEs.
    pub fn fast_auto_accept_incoming_calls(mut self, enabled: bool) -> Self {
        self.fast_auto_accept_incoming_calls = Some(enabled);
        self
    }

    /// Enable or disable cleanup-stage timing diagnostics.
    pub fn cleanup_diagnostics(mut self, enabled: bool) -> Self {
        self.cleanup_diagnostics = Some(enabled);
        self
    }

    /// Enable or disable per-operation cleanup diagnostic event logs.
    pub fn cleanup_diagnostic_events(mut self, enabled: bool) -> Self {
        self.cleanup_diagnostic_events = Some(enabled);
        self
    }

    /// Set app-facing event buffer capacity.
    pub fn app_event_channel_capacity(mut self, capacity: usize) -> Self {
        self.app_event_channel_capacity = Some(capacity);
        self
    }

    /// Set the per-transaction command channel capacity.
    pub fn sip_transaction_command_channel_capacity(mut self, capacity: usize) -> Self {
        self.sip_transaction_command_channel_capacity = Some(capacity);
        self
    }

    /// Set the server-side inbound call admission limit.
    pub fn server_call_admission_limit(mut self, limit: usize) -> Self {
        self.server_call_admission_limit = Some(limit);
        self
    }

    /// Set the soft threshold where server-side admission starts pacing.
    pub fn server_call_admission_soft_limit(mut self, limit: usize) -> Self {
        self.server_call_admission_soft_limit = Some(limit);
        self
    }

    /// Set the delay in milliseconds while above the soft admission threshold.
    pub fn server_call_admission_pacing_delay_ms(mut self, delay_ms: u64) -> Self {
        self.server_call_admission_pacing_delay_ms = Some(delay_ms);
        self
    }

    /// Set the `Retry-After` value used for server overload rejections.
    pub fn server_overload_retry_after_secs(mut self, seconds: u32) -> Self {
        self.server_overload_retry_after_secs = Some(seconds);
        self
    }

    /// Set the RSS growth threshold used by perf soak release gates.
    #[cfg(feature = "perf-tests")]
    pub fn perf_max_rss_growth_mb_per_hr(mut self, limit: f64) -> Self {
        self.perf_max_rss_growth_mb_per_hr = Some(limit);
        self
    }

    /// Enable or disable SRTP negotiation diagnostic log lines.
    pub fn srtp_diagnostics(mut self, enabled: bool) -> Self {
        self.srtp_diagnostics = Some(enabled);
        self
    }

    /// Enable or disable RTP packet diagnostic log lines.
    pub fn rtp_diagnostics(mut self, enabled: bool) -> Self {
        self.rtp_diagnostics = Some(enabled);
        self
    }

    /// Enable or disable SDP media diagnostic log lines.
    pub fn media_sdp_diagnostics(mut self, enabled: bool) -> Self {
        self.media_sdp_diagnostics = Some(enabled);
        self
    }

    /// Set the SRTP offer policy.
    pub fn srtp(mut self, mode: EndpointSrtpMode) -> Self {
        self.srtp_mode = Some(mode);
        self
    }

    /// Enable SIP transport-boundary tracing with default redaction.
    pub fn enable_sip_trace(mut self) -> Self {
        self.sip_trace = Some(crate::api::events::SipTraceConfig::enabled());
        self
    }

    /// Set SIP transport-boundary trace policy.
    pub fn sip_trace(mut self, config: crate::api::events::SipTraceConfig) -> Self {
        self.sip_trace = Some(config);
        self
    }

    /// Override the From/AoR URI used for registration and outgoing calls.
    pub fn from_uri(mut self, uri: impl Into<String>) -> Self {
        self.from_uri = Some(uri.into());
        self
    }

    /// Override the Contact URI used for registration and dialog Contact generation.
    pub fn contact_uri(mut self, uri: impl Into<String>) -> Self {
        self.contact_uri = Some(uri.into());
        self
    }

    /// Mutate the generated [`Config`] immediately before the endpoint starts.
    pub fn configure(mut self, f: impl FnOnce(&mut Config) + Send + 'static) -> Self {
        self.configurators.push(Box::new(f));
        self
    }

    /// Build and start the endpoint.
    pub async fn build(self) -> Result<Endpoint> {
        let parts = self.build_parts()?;
        let peer = StreamPeer::with_config(parts.config).await?;
        Ok(Endpoint {
            peer,
            registration: parts.registration,
            registration_handle: Arc::new(Mutex::new(None)),
            registrar: parts.registrar,
            transport: parts.transport,
        })
    }

    fn build_parts(self) -> Result<EndpointParts> {
        let mut config = self.profile_config()?;
        let registrar = self
            .registrar
            .clone()
            .map(|uri| apply_transport_to_uri(&uri, self.transport, true));
        let account_username = self.account_username.clone();

        if let (Some(username), Some(password)) = (&account_username, &self.password) {
            let auth_username = self.auth_username.as_deref().unwrap_or(username);
            config.credentials = Some(Credentials::new(auth_username, password));
        }

        if let Some(performance) = self.performance {
            config = config.try_with_performance_config(performance)?;
        }

        if self.media_port_start.is_some() || self.media_port_end.is_some() {
            let media_port_start = self.media_port_start.unwrap_or(config.media_port_start);
            let media_port_end = self.media_port_end.unwrap_or(config.media_port_end);
            config = config.with_media_ports(media_port_start, media_port_end);
        }
        if let Some(addr) = self.media_public_addr {
            config.media_public_addr = Some(addr);
        }
        if let Some(mode) = self.media_mode {
            config.media_mode = mode;
        }
        if let Some(stun) = self.stun_server {
            config.stun_server = Some(stun);
        }
        if let Some(outbound_proxy) = self.outbound_proxy_uri.as_ref() {
            config.outbound_proxy_uri =
                Some(apply_transport_to_uri(outbound_proxy, self.transport, true));
        }
        if let Some(srtp_mode) = self.srtp_mode {
            match srtp_mode {
                EndpointSrtpMode::Off => {
                    config.offer_srtp = false;
                    config.srtp_required = false;
                }
                EndpointSrtpMode::Offer => {
                    config.offer_srtp = true;
                    config.srtp_required = false;
                }
                EndpointSrtpMode::Required => {
                    config.offer_srtp = true;
                    config.srtp_required = true;
                }
            }
        }
        if let Some(sip_trace) = self.sip_trace {
            config.sip_trace = sip_trace;
        }
        if let Some(workers) = self.sip_udp_parse_workers {
            config.sip_udp_parse_workers = Some(workers);
        }
        if let Some(capacity) = self.sip_udp_parse_queue_capacity {
            config.sip_udp_parse_queue_capacity = Some(capacity);
        }
        if let Some(auto_180_ringing) = self.auto_180_ringing {
            config.auto_180_ringing = auto_180_ringing;
        }
        if let Some(auto_100_trying) = self.auto_100_trying {
            config.auto_100_trying = auto_100_trying;
        }
        if let Some(fast_auto_accept) = self.fast_auto_accept_incoming_calls {
            config.fast_auto_accept_incoming_calls = fast_auto_accept;
        }
        if let Some(cleanup_diagnostics) = self.cleanup_diagnostics {
            config.cleanup_diagnostics = cleanup_diagnostics;
        }
        if let Some(cleanup_diagnostic_events) = self.cleanup_diagnostic_events {
            config.cleanup_diagnostic_events = cleanup_diagnostic_events;
        }
        if let Some(capacity) = self.app_event_channel_capacity {
            config = config.with_app_event_channel_capacity(capacity);
        }
        if let Some(capacity) = self.sip_transaction_command_channel_capacity {
            config = config.with_sip_transaction_command_channel_capacity(capacity);
        }
        if let Some(limit) = self.server_call_admission_limit {
            config = config.with_server_call_admission_limit(limit);
        }
        if let Some(limit) = self.server_call_admission_soft_limit {
            config = config.with_server_call_admission_soft_limit(limit);
        }
        if let Some(delay_ms) = self.server_call_admission_pacing_delay_ms {
            config = config.with_server_call_admission_pacing_delay_ms(delay_ms);
        }
        if let Some(seconds) = self.server_overload_retry_after_secs {
            config = config.with_server_overload_retry_after_secs(seconds);
        }
        #[cfg(feature = "perf-tests")]
        if let Some(limit) = self.perf_max_rss_growth_mb_per_hr {
            config.perf_max_rss_growth_mb_per_hr = Some(limit);
        }
        if let Some(srtp_diagnostics) = self.srtp_diagnostics {
            config.srtp_diagnostics = srtp_diagnostics;
        }
        if let Some(rtp_diagnostics) = self.rtp_diagnostics {
            config.rtp_diagnostics = rtp_diagnostics;
        }
        if let Some(media_sdp_diagnostics) = self.media_sdp_diagnostics {
            config.media_sdp_diagnostics = media_sdp_diagnostics;
        }
        if self.transport == EndpointTransport::Tls && config.sip_tls_mode == SipTlsMode::Disabled {
            config.sip_tls_mode = SipTlsMode::ClientOnly;
        }

        let derived_from_uri = match (&self.from_uri, &account_username, &registrar) {
            (Some(uri), _, _) => Some(uri.clone()),
            (None, Some(username), Some(registrar)) => Some(account_aor_uri(registrar, username)?),
            _ => None,
        };
        if let Some(from_uri) = &derived_from_uri {
            config.local_uri = from_uri.clone();
        }

        if let Some(contact_uri) = &self.contact_uri {
            config.contact_uri = Some(contact_uri.clone());
        }

        for configure in self.configurators {
            configure(&mut config);
        }

        let registration = match (
            registrar.as_ref(),
            account_username.as_ref(),
            self.password.as_ref(),
        ) {
            (Some(registrar), Some(username), Some(password)) => {
                let auth_username = self.auth_username.as_deref().unwrap_or(username);
                let mut registration = Registration::new(
                    registrar.clone(),
                    auth_username.to_string(),
                    password.clone(),
                )
                .expires(self.expires);
                if let Some(from_uri) = derived_from_uri {
                    registration = registration.from_uri(from_uri);
                }
                if let Some(contact_uri) = self.contact_uri {
                    registration = registration.contact_uri(contact_uri);
                }
                Some(registration)
            }
            _ => None,
        };

        Ok(EndpointParts {
            config,
            registration,
            registrar,
            transport: self.transport,
        })
    }

    fn profile_config(&self) -> Result<Config> {
        let name = self
            .name
            .as_deref()
            .or(self.account_username.as_deref())
            .unwrap_or("endpoint");

        match &self.profile {
            EndpointProfile::Local => {
                let bind = self
                    .bind_addr
                    .unwrap_or_else(|| SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), 5060));
                if bind.ip().is_loopback() {
                    Ok(Config::local(name, bind.port()))
                } else {
                    let mut config = Config::on(name, bind.ip(), bind.port());
                    config.bind_addr = bind;
                    Ok(config)
                }
            }
            EndpointProfile::LanPbx => {
                let bind = self.bind_addr.unwrap_or_else(default_udp_bind);
                let advertised = self.advertised_addr.ok_or_else(|| {
                    SessionError::ConfigError(
                        "EndpointProfile::LanPbx requires advertised_addr".to_string(),
                    )
                })?;
                Ok(Config::lan_pbx(name, bind, advertised))
            }
            EndpointProfile::AsteriskUdp => {
                let bind = self.bind_addr.unwrap_or_else(default_udp_bind);
                if let Some(advertised) = self.advertised_addr {
                    Ok(Config::lan_pbx(name, bind, advertised))
                } else if bind.ip().is_loopback() {
                    let mut config = Config::local(name, bind.port());
                    config.bind_addr = bind;
                    Ok(config)
                } else if bind.ip().is_unspecified() {
                    Err(SessionError::ConfigError(
                        "EndpointProfile::AsteriskUdp with an unspecified bind address requires advertised_addr"
                            .to_string(),
                    ))
                } else {
                    let mut config = Config::on(name, bind.ip(), bind.port());
                    config.bind_addr = bind;
                    Ok(config)
                }
            }
            EndpointProfile::AsteriskTlsSrtpRegisteredFlow => {
                let bind = self.bind_addr.unwrap_or_else(default_tls_bind);
                Ok(Config::asterisk_tls_registered_flow(
                    name,
                    bind,
                    self.sip_instance
                        .clone()
                        .unwrap_or_else(generate_sip_instance),
                ))
            }
            EndpointProfile::FreeSwitchInternal => {
                let bind = self.bind_addr.unwrap_or_else(default_udp_bind);
                Ok(Config::freeswitch_internal(name, bind))
            }
            EndpointProfile::FreeSwitchTlsSrtpReachableContact => {
                let bind = self.bind_addr.unwrap_or_else(default_udp_bind);
                let tls_bind = self.tls_bind_addr.unwrap_or_else(default_tls_bind);
                let cert = self.tls_cert_path.clone().ok_or_else(|| {
                    SessionError::ConfigError(
                        "EndpointProfile::FreeSwitchTlsSrtpReachableContact requires tls_cert_path"
                            .to_string(),
                    )
                })?;
                let key = self.tls_key_path.clone().ok_or_else(|| {
                    SessionError::ConfigError(
                        "EndpointProfile::FreeSwitchTlsSrtpReachableContact requires tls_key_path"
                            .to_string(),
                    )
                })?;
                Ok(Config::freeswitch_tls_srtp_reachable_contact(
                    name, bind, tls_bind, cert, key,
                ))
            }
            EndpointProfile::CarrierSbc => {
                let bind = self.bind_addr.unwrap_or_else(default_tls_bind);
                let public = self.advertised_addr.ok_or_else(|| {
                    SessionError::ConfigError(
                        "EndpointProfile::CarrierSbc requires advertised_addr".to_string(),
                    )
                })?;
                let outbound_proxy = self.outbound_proxy_uri.clone().ok_or_else(|| {
                    SessionError::ConfigError(
                        "EndpointProfile::CarrierSbc requires outbound_proxy".to_string(),
                    )
                })?;
                Ok(Config::carrier_sbc(
                    name,
                    bind,
                    public,
                    outbound_proxy,
                    self.sip_instance
                        .clone()
                        .unwrap_or_else(generate_sip_instance),
                ))
            }
            EndpointProfile::Custom(config) => Ok(config.clone()),
        }
    }
}

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

struct EndpointParts {
    config: Config,
    registration: Option<Registration>,
    registrar: Option<String>,
    transport: EndpointTransport,
}

fn default_udp_bind() -> SocketAddr {
    SocketAddr::new(IpAddr::V4(Ipv4Addr::UNSPECIFIED), 5060)
}

fn default_tls_bind() -> SocketAddr {
    SocketAddr::new(IpAddr::V4(Ipv4Addr::UNSPECIFIED), 5061)
}

fn generate_sip_instance() -> String {
    format!("urn:uuid:{}", uuid::Uuid::new_v4())
}

async fn wait_for_registration_result(
    events: &mut EndpointEvents,
    handle: &RegistrationHandle,
    timeout: Option<Duration>,
) -> Result<EndpointRegistrationInfo> {
    let coordinator = events.control.coordinator().clone();
    let registrar = coordinator
        .registration_info(handle)
        .await?
        .registrar
        .unwrap_or_default();
    let fut = async {
        loop {
            match events.next().await? {
                Some(EndpointEvent::RegistrationChanged(info))
                    if registrar.is_empty()
                        || info.registrar.as_deref() == Some(registrar.as_str()) =>
                {
                    if info.status == EndpointRegistrationStatus::Registered {
                        return coordinator
                            .registration_info(handle)
                            .await
                            .map(EndpointRegistrationInfo::from);
                    }
                    if info.status == EndpointRegistrationStatus::Failed {
                        return Err(SessionError::Other(format!(
                            "registration failed for {}: {}",
                            info.registrar.unwrap_or_default(),
                            info.last_failure
                                .unwrap_or_else(|| "unknown error".to_string())
                        )));
                    }
                }
                Some(_) => {}
                None => {
                    return Err(SessionError::Other(
                        "event stream closed while waiting for registration".to_string(),
                    ))
                }
            }
        }
    };

    match timeout {
        Some(duration) => tokio::time::timeout(duration, fut)
            .await
            .map_err(|_| SessionError::Timeout("register_and_wait timed out".to_string()))?,
        None => fut.await,
    }
}

fn normalize_target(
    registrar: Option<&str>,
    target: &str,
    transport: EndpointTransport,
) -> Result<String> {
    let target = target.trim();
    if target.is_empty() {
        return Err(SessionError::InvalidInput(
            "call target must not be empty".to_string(),
        ));
    }

    let lower = target.to_ascii_lowercase();
    if lower.starts_with("sip:") || lower.starts_with("sips:") || lower.starts_with("tel:") {
        return Ok(apply_transport_to_uri(target, transport, false));
    }

    let registrar = registrar.ok_or_else(|| {
        SessionError::ConfigError(
            "bare call targets require EndpointBuilder::registrar".to_string(),
        )
    })?;
    let registrar = apply_transport_to_uri(registrar, transport, true);
    let mut registrar_uri = parse_uri(&registrar, "registrar")?;

    if target.contains('@') {
        return Ok(format!("{}:{}", registrar_uri.scheme, target));
    }

    registrar_uri.user = Some(target.to_string());
    registrar_uri.password = None;
    registrar_uri.headers.clear();
    Ok(registrar_uri.to_string())
}

fn apply_transport_to_uri(
    uri: &str,
    transport: EndpointTransport,
    registrar_or_proxy: bool,
) -> String {
    match transport {
        EndpointTransport::Udp => uri.to_string(),
        EndpointTransport::Tcp => {
            if uri.contains(";transport=") {
                uri.to_string()
            } else {
                format!("{uri};transport=tcp")
            }
        }
        EndpointTransport::Tls => {
            let tls_uri = if uri.to_ascii_lowercase().starts_with("sip:") {
                format!("sips:{}", &uri[4..])
            } else {
                uri.to_string()
            };
            if registrar_or_proxy || tls_uri.contains(";transport=") {
                tls_uri
            } else {
                format!("{tls_uri};transport=tls")
            }
        }
    }
}

fn parse_media_public_address(value: &str) -> Result<SocketAddr> {
    if let Ok(addr) = value.parse::<SocketAddr>() {
        return Ok(addr);
    }
    let ip = value.parse::<IpAddr>().map_err(|err| {
        SessionError::InvalidInput(format!("invalid media public address '{value}': {err}"))
    })?;
    Ok(SocketAddr::new(ip, 0))
}

fn account_aor_uri(registrar: &str, username: &str) -> Result<String> {
    let mut uri = parse_uri(registrar, "registrar")?;
    uri.user = Some(username.to_string());
    uri.password = None;
    uri.port = None;
    uri.parameters.clear();
    uri.headers.clear();
    Ok(uri.to_string())
}

fn parse_uri(value: &str, label: &str) -> Result<Uri> {
    let uri = Uri::from_str(value).map_err(|err| {
        SessionError::InvalidInput(format!("invalid {label} URI '{value}': {err}"))
    })?;
    match uri.scheme {
        Scheme::Sip | Scheme::Sips => Ok(uri),
        _ => Err(SessionError::InvalidInput(format!(
            "{label} URI must use sip: or sips:"
        ))),
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::api::unified::{SipContactMode, SipTlsMode};

    #[test]
    fn endpoint_builder_maps_asterisk_tls_profile() {
        let parts = Endpoint::builder()
            .name("alice")
            .account("1001")
            .password("secret")
            .registrar("sips:pbx.example.test:5061;transport=tls")
            .profile(EndpointProfile::AsteriskTlsSrtpRegisteredFlow)
            .sip_instance("urn:uuid:00000000-0000-0000-0000-000000000001")
            .build_parts()
            .unwrap();

        assert_eq!(parts.config.sip_tls_mode, SipTlsMode::ClientOnly);
        assert_eq!(
            parts.config.sip_contact_mode,
            SipContactMode::RegisteredFlowSymmetric
        );
        assert!(parts.config.offer_srtp);
        assert!(parts.config.srtp_required);
        assert_eq!(parts.config.local_uri, "sips:1001@pbx.example.test");
        assert!(parts.registration.is_some());
    }

    #[test]
    fn endpoint_builder_creates_registration_defaults() {
        let parts = Endpoint::builder()
            .account("1001")
            .auth_username("auth1001")
            .password("secret")
            .registrar("sip:pbx.example.test")
            .contact_uri("sip:1001@192.0.2.10:5060")
            .expires(600)
            .build_parts()
            .unwrap();

        let registration = parts.registration.unwrap();
        assert_eq!(registration.registrar, "sip:pbx.example.test");
        assert_eq!(registration.username, "auth1001");
        assert_eq!(registration.password, "secret");
        assert_eq!(registration.expires, 600);
        assert_eq!(
            registration.from_uri.as_deref(),
            Some("sip:1001@pbx.example.test")
        );
        assert_eq!(
            registration.contact_uri.as_deref(),
            Some("sip:1001@192.0.2.10:5060")
        );
    }

    #[test]
    fn endpoint_normalizes_bare_extension_through_registrar() {
        let target = normalize_target(
            Some("sips:pbx.example.test:5061;transport=tls"),
            "1002",
            EndpointTransport::Udp,
        )
        .unwrap();
        assert_eq!(target, "sips:1002@pbx.example.test:5061;transport=tls");
    }

    #[test]
    fn endpoint_leaves_full_sip_uri_unchanged() {
        let target = normalize_target(
            Some("sips:pbx.example.test:5061"),
            "sip:bob@example.test",
            EndpointTransport::Udp,
        )
        .unwrap();
        assert_eq!(target, "sip:bob@example.test");
    }

    #[test]
    fn endpoint_requires_registrar_for_bare_target() {
        let err = normalize_target(None, "1002", EndpointTransport::Udp).unwrap_err();
        assert!(err.to_string().contains("registrar"));
    }

    #[test]
    fn endpoint_transport_rewrites_tls_target() {
        let target = normalize_target(
            Some("sip:pbx.example.test:5060"),
            "1002",
            EndpointTransport::Tls,
        )
        .unwrap();
        assert_eq!(target, "sips:1002@pbx.example.test:5060");
    }

    #[test]
    fn endpoint_json_config_maps_builder_fields() {
        let config = serde_json::from_str::<EndpointConfig>(
            r#"{
                "name": "alice",
                "profile": "asterisk-udp",
                "auto180Ringing": false,
                "auto100Trying": false,
                "fastAutoAcceptIncomingCalls": true,
                "cleanupDiagnostics": true,
                "cleanupDiagnosticEvents": true,
                "appEventChannelCapacity": 512,
                "srtpDiagnostics": true,
                "rtpDiagnostics": true,
                "mediaSdpDiagnostics": true,
                "account": {
                    "username": "1001",
                    "password": "secret",
                    "registrar": "sip:pbx.example.test"
                },
                "network": {
                    "bind": "127.0.0.1:5060",
                    "transport": "tcp",
                    "stun": "stun.example.test:3478",
                    "udpParseWorkers": 4,
                    "udpParseQueueCapacity": 8192
                },
                "media": {
                    "publicAddress": "192.0.2.10",
                    "enabled": false,
                    "signalingOnlyRtpPort": 9,
                    "srtp": "offer"
                }
            }"#,
        )
        .unwrap();

        let parts = EndpointBuilder::from_config(config)
            .unwrap()
            .build_parts()
            .unwrap();
        assert_eq!(parts.transport, EndpointTransport::Tcp);
        assert_eq!(
            parts.config.stun_server.as_deref(),
            Some("stun.example.test:3478")
        );
        assert!(parts.config.offer_srtp);
        assert!(!parts.config.srtp_required);
        assert!(!parts.config.auto_180_ringing);
        assert!(!parts.config.auto_100_trying);
        assert!(parts.config.fast_auto_accept_incoming_calls);
        assert!(parts.config.cleanup_diagnostics);
        assert!(parts.config.cleanup_diagnostic_events);
        assert_eq!(parts.config.global_event_channel_capacity, 512);
        assert_eq!(parts.config.session_event_dispatcher_channel_capacity, 512);
        assert!(parts.config.srtp_diagnostics);
        assert!(parts.config.rtp_diagnostics);
        assert!(parts.config.media_sdp_diagnostics);
        assert_eq!(parts.config.sip_udp_parse_workers, Some(4));
        assert_eq!(parts.config.sip_udp_parse_queue_capacity, Some(8192));
        assert_eq!(
            parts.config.media_mode,
            MediaMode::SignalingOnly { sdp_rtp_port: 9 }
        );
        assert_eq!(
            parts.config.media_public_addr,
            Some("192.0.2.10:0".parse().unwrap())
        );
        assert_eq!(
            parts.registrar.as_deref(),
            Some("sip:pbx.example.test;transport=tcp")
        );
    }

    #[test]
    fn endpoint_json_performance_profile_maps_into_config() {
        let config = serde_json::from_str::<EndpointConfig>(
            r#"{
                "name": "perf",
                "performance": {
                    "profile": "pbx-media-server",
                    "capacity": 2000
                },
                "network": {
                    "udpParseWorkers": 2
                },
                "sipTransactionCommandChannelCapacity": 256,
                "serverCallAdmissionLimit": 3000,
                "serverCallAdmissionSoftLimit": 2500,
                "serverCallAdmissionPacingDelayMs": 3,
                "serverOverloadRetryAfterSecs": 2
            }"#,
        )
        .unwrap();

        let parts = EndpointBuilder::from_config(config)
            .unwrap()
            .build_parts()
            .unwrap();
        assert!(parts.config.fast_auto_accept_incoming_calls);
        assert_eq!(parts.config.media_mode, MediaMode::Enabled);
        assert_eq!(parts.config.media_port_start, 16_384);
        assert_eq!(parts.config.media_port_capacity, Some(49_152));
        assert_eq!(parts.config.media_session_capacity, Some(2_000));
        assert_eq!(parts.config.sip_udp_parse_workers, Some(2));
        assert_eq!(
            parts.config.sip_udp_parse_dispatch,
            Some(rvoip_sip_transport::UdpParseDispatch::RoundRobin)
        );
        assert_eq!(
            parts.config.sip_transaction_command_channel_capacity,
            Some(256)
        );
        assert_eq!(parts.config.server_call_capacity, Some(2_000));
        assert_eq!(parts.config.server_call_admission_limit, Some(3_000));
        assert_eq!(parts.config.server_call_admission_soft_limit, Some(2_500));
        assert_eq!(parts.config.server_call_admission_pacing_delay_ms, Some(3));
        assert_eq!(parts.config.server_overload_retry_after_secs, Some(2));
    }

    #[test]
    fn endpoint_json_endpoint_performance_recipe_is_default_shape() {
        let config = serde_json::from_str::<EndpointConfig>(
            r#"{
                "name": "softphone",
                "performance": {
                    "profile": "endpoint"
                }
            }"#,
        )
        .unwrap();

        let parts = EndpointBuilder::from_config(config)
            .unwrap()
            .build_parts()
            .unwrap();
        assert!(parts.config.auto_180_ringing);
        assert!(parts.config.auto_100_trying);
        assert!(!parts.config.fast_auto_accept_incoming_calls);
        assert_eq!(parts.config.media_mode, MediaMode::Enabled);
        assert_eq!(parts.config.sip_udp_parse_workers, None);
        assert_eq!(parts.config.sip_transaction_command_channel_capacity, None);
    }

    #[test]
    fn endpoint_json_signaling_only_performance_profile_maps_into_config() {
        let config = serde_json::from_str::<EndpointConfig>(
            r#"{
                "name": "perf",
                "performance": {
                    "profile": "signaling-only-server-high-performance",
                    "capacity": 2000,
                    "signalingOnlyRtpPort": 4000
                }
            }"#,
        )
        .unwrap();

        let parts = EndpointBuilder::from_config(config)
            .unwrap()
            .build_parts()
            .unwrap();
        assert_eq!(
            parts.config.media_mode,
            MediaMode::SignalingOnly { sdp_rtp_port: 4000 }
        );
        assert_eq!(parts.config.sip_udp_parse_workers, Some(4));
        assert_eq!(
            parts.config.sip_transaction_command_channel_capacity,
            Some(128)
        );
        assert_eq!(parts.config.server_call_capacity, Some(2_000));
        assert_eq!(parts.config.server_call_admission_limit, Some(2_000));
        assert_eq!(parts.config.server_call_admission_soft_limit, Some(1_800));
        assert_eq!(parts.config.server_call_admission_pacing_delay_ms, Some(1));
    }

    #[test]
    fn endpoint_json_config_accepts_partial_sip_trace_config() {
        let config = serde_json::from_str::<EndpointConfig>(
            r#"{
                "sipTrace": {
                    "enabled": true,
                    "redactSensitiveHeaders": false
                }
            }"#,
        )
        .unwrap();

        let trace = config.sip_trace.unwrap();
        assert!(trace.enabled);
        assert_eq!(
            trace.capacity,
            crate::api::events::SipTraceConfig::DEFAULT_CAPACITY
        );
        assert!(!trace.redact_sensitive_headers);
        assert!(trace.include_body);
    }

    #[test]
    fn sip_client_example_stays_on_endpoint_surface() {
        let source = [
            include_str!("../../examples/sip_client/main.rs"),
            include_str!("../../examples/sip_client/audio.rs"),
            include_str!("../../examples/sip_client/config.rs"),
            include_str!("../../examples/sip_client/runtime.rs"),
            include_str!("../../examples/sip_client/smoke.rs"),
            include_str!("../../examples/sip_client/ui.rs"),
        ]
        .join("\n");
        for banned in [
            "StreamPeer",
            "PeerControl",
            "UnifiedCoordinator",
            "RegistrationHandle",
            "SessionHandle",
            "SipTlsMode",
            "rvoip_media_core",
        ] {
            assert!(
                !source.contains(banned),
                "sip_client example must not reference lower-level API {banned}"
            );
        }
    }

    #[test]
    fn endpoint_audio_roundtrip_stays_on_endpoint_surface() {
        let source = include_str!("../../examples/endpoint/04_audio_roundtrip/main.rs");
        for banned in [
            "StreamPeer",
            "PeerControl",
            "UnifiedCoordinator",
            "RegistrationHandle",
            "SessionHandle",
            "as_session_handle",
            "rvoip_media_core",
        ] {
            assert!(
                !source.contains(banned),
                "endpoint audio roundtrip example must not reference lower-level API {banned}"
            );
        }
    }
}