xphone 0.4.5

SIP telephony library with event-driven API — handles SIP signaling, RTP media, codecs, and call state
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
use std::collections::HashMap;
use std::sync::Arc;

use parking_lot::Mutex;
use tracing::{debug, info, warn};

use crate::call::Call;
use crate::config::{Config, DialOptions};
use crate::dialog::Dialog;
use crate::dialog_info::parse_dialog_info;
use crate::error::{Error, Result};
use crate::mock::dialog::MockDialog;
use crate::mwi::MwiSubscriber;
use crate::registry::Registry;
use crate::subscription::{SubId, SubscriptionManager};
use crate::transport::SipTransport;
#[cfg(test)]
use crate::types::{CallState, EndReason};
use crate::types::{
    ExtensionState, ExtensionStatus, NotifyEvent, PhoneState, SipMessage, VoicemailStatus,
};

type CallStateCb = Arc<dyn Fn(Arc<Call>, crate::types::CallState) + Send + Sync>;
type CallEndedCb = Arc<dyn Fn(Arc<Call>, crate::types::EndReason) + Send + Sync>;
type CallDtmfCb = Arc<dyn Fn(Arc<Call>, String) + Send + Sync>;

struct Inner {
    state: PhoneState,
    tr: Option<Arc<dyn SipTransport>>,
    reg: Option<Arc<Registry>>,
    mwi: Option<Arc<MwiSubscriber>>,
    incoming: Vec<Arc<dyn Fn(Arc<Call>) + Send + Sync>>,
    calls: HashMap<String, Arc<Call>>,

    on_registered_fn: Vec<Arc<dyn Fn() + Send + Sync>>,
    on_unregistered_fn: Vec<Arc<dyn Fn() + Send + Sync>>,
    on_error_fn: Vec<Arc<dyn Fn(Error) + Send + Sync>>,
    on_voicemail_fn: Vec<Arc<dyn Fn(VoicemailStatus) + Send + Sync>>,
    on_message_fn: Vec<Arc<dyn Fn(SipMessage) + Send + Sync>>,
    on_subscription_error_fn: Vec<Arc<dyn Fn(String, Error) + Send + Sync>>,

    // Phone-level call callbacks — auto-wired to every new call.
    on_call_state_fn: Vec<CallStateCb>,
    on_call_ended_fn: Vec<CallEndedCb>,
    on_call_dtmf_fn: Vec<CallDtmfCb>,

    /// DTMF mode from config, applied to every new call.
    dtmf_mode: crate::config::DtmfMode,

    /// Subscription manager for BLF and generic event subscriptions.
    subscription_mgr: Option<Arc<SubscriptionManager>>,
    /// BLF watchers: extension -> (SubId, last known state).
    blf_watchers: HashMap<String, (SubId, ExtensionState)>,
}

/// Phone orchestrates SIP registration, call tracking, and incoming/outgoing calls.
#[derive(Clone)]
pub struct Phone {
    cfg: Config,
    inner: Arc<Mutex<Inner>>,
}

impl Phone {
    /// Creates a new `Phone` with the given configuration, initially in the `Disconnected` state.
    pub fn new(mut cfg: Config) -> Self {
        cfg.normalize_host();
        let dtmf_mode = cfg.dtmf_mode;
        Self {
            cfg,
            inner: Arc::new(Mutex::new(Inner {
                state: PhoneState::Disconnected,
                tr: None,
                reg: None,
                mwi: None,
                incoming: Vec::new(),
                calls: HashMap::new(),
                on_registered_fn: Vec::new(),
                on_unregistered_fn: Vec::new(),
                on_error_fn: Vec::new(),
                on_voicemail_fn: Vec::new(),
                on_message_fn: Vec::new(),
                on_subscription_error_fn: Vec::new(),
                on_call_state_fn: Vec::new(),
                on_call_ended_fn: Vec::new(),
                on_call_dtmf_fn: Vec::new(),
                dtmf_mode,
                subscription_mgr: None,
                blf_watchers: HashMap::new(),
            })),
        }
    }

    /// Connects to the SIP server using the configured transport.
    /// Creates a real SipUA, performs registration, and wires up incoming INVITE handling.
    pub fn connect(&self) -> crate::error::Result<()> {
        info!(host = %self.cfg.host, port = self.cfg.port, user = %self.cfg.username, "Phone connecting");
        let tr = Arc::new(crate::sip::ua::SipUA::new(&self.cfg)?);
        self.connect_with_transport(tr);
        let state = self.state();
        if state == PhoneState::Registered {
            info!("Phone connected and registered");
            Ok(())
        } else {
            warn!("Phone registration failed");
            Err(crate::error::Error::RegistrationFailed)
        }
    }

    /// Connects with a provided transport (test hook).
    /// Performs registration and wires up incoming INVITE handling.
    pub fn connect_with_transport(&self, tr: Arc<dyn SipTransport>) {
        let reg = Arc::new(Registry::new(Arc::clone(&tr), self.cfg.clone()));

        // Apply buffered callbacks to the registry.
        // Clone the Vecs before iterating to avoid holding the Phone lock
        // during Registry method calls (prevents lock-ordering issues).
        let (reg_cbs, unreg_cbs, err_cbs) = {
            let inner = self.inner.lock();
            (
                inner.on_registered_fn.clone(),
                inner.on_unregistered_fn.clone(),
                inner.on_error_fn.clone(),
            )
        };
        for f in reg_cbs {
            reg.on_registered(move || f());
        }
        for f in unreg_cbs {
            reg.on_unregistered(move || f());
        }
        for f in err_cbs {
            reg.on_error(move |e| f(e));
        }

        // Perform registration.
        let reg_result = reg.start();

        // Determine the local IP for SDP media address.
        // Priority: explicit config override > STUN-mapped IP > UDP heuristic.
        let effective_ip = if !self.cfg.local_ip.is_empty() {
            self.cfg.local_ip.clone()
        } else if let Some(addr) = tr.advertised_addr() {
            addr.ip().to_string()
        } else {
            local_ip_for(&self.cfg.host)
        };

        // Wire up incoming INVITE handling (dialog-based for production, simple for mock).
        let inner_clone = Arc::clone(&self.inner);
        let incoming_ip = effective_ip.clone();
        let rtp_port_min = self.cfg.rtp_port_min;
        let rtp_port_max = self.cfg.rtp_port_max;
        tr.on_dialog_invite(Box::new(move |dlg, from, to, remote_sdp| {
            handle_dialog_incoming(
                &inner_clone,
                dlg,
                &from,
                &to,
                &remote_sdp,
                &incoming_ip,
                rtp_port_min,
                rtp_port_max,
            );
        }));

        let inner_clone = Arc::clone(&self.inner);
        tr.on_incoming(Box::new(move |from, to| {
            handle_incoming(&inner_clone, &from, &to);
        }));

        // Wire up BYE handling.
        let inner_clone = Arc::clone(&self.inner);
        tr.on_bye(Box::new(move |call_id| {
            handle_bye(&inner_clone, &call_id);
        }));

        // Wire up NOTIFY handling (REFER progress).
        let inner_clone = Arc::clone(&self.inner);
        tr.on_notify(Box::new(move |call_id, code| {
            handle_notify(&inner_clone, &call_id, code);
        }));

        // Wire up SIP INFO DTMF handling.
        let inner_clone = Arc::clone(&self.inner);
        tr.on_info_dtmf(Box::new(move |call_id, digit| {
            handle_info_dtmf(&inner_clone, &call_id, &digit);
        }));

        // Wire up SIP MESSAGE handling.
        let inner_clone = Arc::clone(&self.inner);
        tr.on_message(Box::new(move |from, content_type, body| {
            handle_message(&inner_clone, &from, &content_type, &body);
        }));

        // Create subscription manager and wire NOTIFY handler.
        let sub_mgr = Arc::new(SubscriptionManager::new(Arc::clone(&tr)));
        let sub_mgr_clone = Arc::clone(&sub_mgr);
        tr.on_subscription_notify(Box::new(move |event, ct, body, sub_state, from_uri| {
            sub_mgr_clone.handle_notify(event, ct, body, sub_state, from_uri);
        }));
        // Apply buffered on_subscription_error callbacks.
        let sub_err_cbs = self.inner.lock().on_subscription_error_fn.clone();
        for f in sub_err_cbs {
            sub_mgr.on_error(move |uri, err| f(uri, err));
        }

        // Start MWI subscriber if voicemail URI is configured and registration succeeded.
        let mwi = if reg_result.is_ok() {
            if let Some(ref vm_uri) = self.cfg.voicemail_uri {
                let sub = Arc::new(MwiSubscriber::new(Arc::clone(&tr), vm_uri.clone()));
                // Apply buffered on_voicemail callbacks.
                let vm_cbs = self.inner.lock().on_voicemail_fn.clone();
                for f in vm_cbs {
                    sub.on_voicemail(move |s| f(s));
                }
                sub.start();
                Some(sub)
            } else {
                None
            }
        } else {
            None
        };

        let mut inner = self.inner.lock();
        inner.tr = Some(tr);
        inner.reg = Some(reg);
        inner.mwi = mwi;
        inner.subscription_mgr = Some(sub_mgr);
        if reg_result.is_ok() {
            inner.state = PhoneState::Registered;
        } else {
            inner.state = PhoneState::RegistrationFailed;
        }
    }

    /// Disconnects the phone: ends all active calls, stops registry, and closes transport.
    pub fn disconnect(&self) -> Result<()> {
        info!("Phone disconnecting");
        let (reg, tr, unreg_fns, active_calls, mwi, sub_mgr) = {
            let mut inner = self.inner.lock();
            if inner.state == PhoneState::Disconnected {
                return Err(Error::NotConnected);
            }
            let reg = inner.reg.take();
            let tr = inner.tr.take();
            let unreg_fns = inner.on_unregistered_fn.clone();
            let active_calls: Vec<Arc<Call>> = inner.calls.drain().map(|(_, c)| c).collect();
            let mwi = inner.mwi.take();
            let sub_mgr = inner.subscription_mgr.take();
            inner.blf_watchers.clear();
            inner.state = PhoneState::Disconnected;
            (reg, tr, unreg_fns, active_calls, mwi, sub_mgr)
        };

        // End all active calls so their resources (media, sockets, SRTP) are released.
        for call in active_calls {
            let _ = call.end();
        }

        if let Some(sub_mgr) = sub_mgr {
            sub_mgr.stop();
        }
        if let Some(mwi) = mwi {
            mwi.stop();
        }
        if let Some(reg) = reg {
            reg.stop();
        }
        if let Some(tr) = tr {
            let _ = tr.close();
        }
        for f in unreg_fns {
            crate::callback_pool::spawn_callback(move || f());
        }

        Ok(())
    }

    /// Initiates an outbound call.
    pub fn dial(&self, target: &str, opts: DialOptions) -> Result<Arc<Call>> {
        info!(target = %target, "Phone dialing");
        let tr = {
            let inner = self.inner.lock();
            if inner.state != PhoneState::Registered {
                return Err(Error::NotRegistered);
            }
            inner.tr.as_ref().cloned().ok_or(Error::NotConnected)?
        };

        // Allocate RTP port and build SDP offer.
        // Use STUN-mapped IP from transport if available.
        let local_ip = if !self.cfg.local_ip.is_empty() {
            self.cfg.local_ip.clone()
        } else if let Some(addr) = tr.advertised_addr() {
            addr.ip().to_string()
        } else {
            local_ip_for(&self.cfg.host)
        };
        let (rtp_socket, rtp_port) = {
            let (sock, port) =
                crate::media::listen_rtp_port(self.cfg.rtp_port_min, self.cfg.rtp_port_max)?;
            (Some(sock), port as i32)
        };
        // Allocate video RTP socket if video is requested.
        let (video_rtp_socket, video_rtp_port) = if opts.video {
            match crate::media::listen_rtp_port(self.cfg.rtp_port_min, self.cfg.rtp_port_max) {
                Ok((sock, port)) => (Some(sock), port as i32),
                Err(_) => (None, 0),
            }
        } else {
            (None, 0)
        };

        // Generate SRTP keying material if enabled.
        let srtp_inline_key = if self.cfg.srtp {
            let (_material, encoded) = crate::srtp::generate_keying_material()?;
            Some(encoded)
        } else {
            None
        };
        let video_srtp_inline_key = if self.cfg.srtp && opts.video {
            let (_material, encoded) = crate::srtp::generate_keying_material()?;
            Some(encoded)
        } else {
            None
        };

        let video_codecs = if opts.video_codecs.is_empty() {
            vec![
                crate::types::VideoCodec::H264,
                crate::types::VideoCodec::VP8,
            ]
        } else {
            opts.video_codecs.clone()
        };

        let local_sdp = if opts.video {
            match (&srtp_inline_key, &video_srtp_inline_key) {
                (Some(audio_key), Some(video_key)) => crate::sdp::build_offer_video_srtp(
                    &local_ip,
                    rtp_port,
                    &[8, 0, 9, 101],
                    video_rtp_port,
                    &video_codecs,
                    crate::sdp::DIR_SEND_RECV,
                    audio_key,
                    video_key,
                ),
                _ => crate::sdp::build_offer_video(
                    &local_ip,
                    rtp_port,
                    &[8, 0, 9, 101],
                    video_rtp_port,
                    &video_codecs,
                    crate::sdp::DIR_SEND_RECV,
                ),
            }
        } else if let Some(ref key) = srtp_inline_key {
            crate::sdp::build_offer_srtp(
                &local_ip,
                rtp_port,
                &[8, 0, 9, 101],
                crate::sdp::DIR_SEND_RECV,
                key,
            )
        } else {
            crate::sdp::build_offer(
                &local_ip,
                rtp_port,
                &[8, 0, 9, 101],
                crate::sdp::DIR_SEND_RECV,
            )
        };

        // Try dialog-based dial (production SipUA path).
        let dial_result = tr.dial(target, local_sdp.as_bytes(), opts.timeout, &opts);

        let (call, responses) = match dial_result {
            Ok(result) => {
                // Production path: got a real dialog from SipUA.
                // tr.dial() already consumed the 200 OK, so transition to Active.
                let call = Call::new_outbound(result.dialog, opts);
                call.set_local_media(&local_ip, rtp_port);
                call.set_local_sdp(&local_sdp);
                if let Some(ref key) = srtp_inline_key {
                    call.set_srtp(key);
                }
                if let Some(sock) = rtp_socket {
                    call.set_rtp_socket(sock);
                }
                // Wire video socket if allocated.
                if let Some(vsock) = video_rtp_socket {
                    call.set_video_rtp_port(video_rtp_port);
                    call.set_video_rtp_socket(vsock);
                }

                // Wire phone-level callbacks (incl. dtmf_mode) BEFORE simulate_response fires on_state.
                wire_phone_call_callbacks(&self.inner, &call);

                // Handle early media: if we got a 183 with SDP, set up media before
                // the final 200 OK so the caller hears ringback/IVR prompts.
                if let Some(ref early_sdp) = result.early_sdp {
                    call.set_remote_sdp(early_sdp);
                    call.simulate_response(183, "Session Progress");
                }

                if !result.remote_sdp.is_empty() {
                    call.set_remote_sdp(&result.remote_sdp);
                }
                call.simulate_response(200, "OK");
                (call, Vec::new())
            }
            Err(e) if e.to_string().contains("not supported") => {
                // Fallback path (MockTransport): use send_request + MockDialog.
                let resp = tr.send_request("INVITE", None, opts.timeout)?;
                let mut code = resp.status_code;
                let mut responses = vec![(code, resp.reason.clone())];

                while (100..200).contains(&code) {
                    let next = tr.read_response(opts.timeout)?;
                    code = next.status_code;
                    responses.push((code, next.reason.clone()));
                }

                let dlg = Arc::new(MockDialog::new());
                let call = Call::new_outbound(dlg as Arc<dyn Dialog>, opts);
                // Wire phone-level callbacks (incl. dtmf_mode) BEFORE replay.
                wire_phone_call_callbacks(&self.inner, &call);
                (call, responses)
            }
            Err(e) => return Err(e),
        };

        // Replay provisional responses (mock path only).
        for (c, r) in &responses {
            call.simulate_response(*c, r);
        }

        // Track the call.
        self.inner
            .lock()
            .calls
            .insert(call.call_id(), Arc::clone(&call));

        Ok(call)
    }

    /// Sets the callback for incoming calls.
    /// The callback fires for every incoming INVITE, even during an active call (call waiting).
    /// The application decides whether to accept, reject (486 Busy), or ignore the new call.
    pub fn on_incoming<F: Fn(Arc<Call>) + Send + Sync + 'static>(&self, f: F) {
        self.inner.lock().incoming.push(Arc::new(f));
    }

    /// Registers a callback for successful registration.
    /// Multiple callbacks can be registered; all will fire.
    pub fn on_registered<F: Fn() + Send + Sync + 'static>(&self, f: F) {
        let cb: Arc<dyn Fn() + Send + Sync> = Arc::new(f);
        let reg = {
            let mut inner = self.inner.lock();
            inner.on_registered_fn.push(Arc::clone(&cb));
            inner.reg.clone()
        };
        if let Some(reg) = reg {
            let cb = Arc::clone(&cb);
            reg.on_registered(move || cb());
        }
    }

    /// Registers a callback for loss of registration.
    /// Multiple callbacks can be registered; all will fire.
    pub fn on_unregistered<F: Fn() + Send + Sync + 'static>(&self, f: F) {
        let cb: Arc<dyn Fn() + Send + Sync> = Arc::new(f);
        let reg = {
            let mut inner = self.inner.lock();
            inner.on_unregistered_fn.push(Arc::clone(&cb));
            inner.reg.clone()
        };
        if let Some(reg) = reg {
            let cb = Arc::clone(&cb);
            reg.on_unregistered(move || cb());
        }
    }

    /// Registers a callback for registration errors.
    /// Multiple callbacks can be registered; all will fire.
    pub fn on_error<F: Fn(Error) + Send + Sync + 'static>(&self, f: F) {
        let cb: Arc<dyn Fn(Error) + Send + Sync> = Arc::new(f);
        let reg = {
            let mut inner = self.inner.lock();
            inner.on_error_fn.push(Arc::clone(&cb));
            inner.reg.clone()
        };
        if let Some(reg) = reg {
            let cb = Arc::clone(&cb);
            reg.on_error(move |e| cb(e));
        }
    }

    /// Registers a callback for voicemail (MWI) status updates.
    /// Multiple callbacks can be registered; all will fire.
    pub fn on_voicemail<F: Fn(VoicemailStatus) + Send + Sync + 'static>(&self, f: F) {
        let cb: Arc<dyn Fn(VoicemailStatus) + Send + Sync> = Arc::new(f);
        let mwi = {
            let mut inner = self.inner.lock();
            inner.on_voicemail_fn.push(Arc::clone(&cb));
            inner.mwi.clone()
        };
        if let Some(mwi) = mwi {
            let cb = Arc::clone(&cb);
            mwi.on_voicemail(move |s| cb(s));
        }
    }

    /// Registers a callback for incoming SIP MESSAGE (instant messages, RFC 3428).
    /// Multiple callbacks can be registered; all will fire.
    pub fn on_message<F: Fn(SipMessage) + Send + Sync + 'static>(&self, f: F) {
        self.inner.lock().on_message_fn.push(Arc::new(f));
    }

    /// Sends a SIP MESSAGE with `text/plain` content type.
    pub fn send_message(&self, target: &str, body: &str) -> Result<()> {
        let tr = {
            let inner = self.inner.lock();
            if inner.state != PhoneState::Registered {
                return Err(Error::NotRegistered);
            }
            inner.tr.as_ref().cloned().ok_or(Error::NotConnected)?
        };
        tr.send_message(
            target,
            "text/plain",
            body.as_bytes(),
            std::time::Duration::from_secs(10),
        )
    }

    /// Sends a SIP MESSAGE with a custom content type.
    pub fn send_message_with_type(
        &self,
        target: &str,
        content_type: &str,
        body: &str,
    ) -> Result<()> {
        let tr = {
            let inner = self.inner.lock();
            if inner.state != PhoneState::Registered {
                return Err(Error::NotRegistered);
            }
            inner.tr.as_ref().cloned().ok_or(Error::NotConnected)?
        };
        tr.send_message(
            target,
            content_type,
            body.as_bytes(),
            std::time::Duration::from_secs(10),
        )
    }

    /// Returns the subscription manager, or `NotConnected` if not connected.
    fn get_sub_mgr(&self) -> Result<Arc<SubscriptionManager>> {
        let inner = self.inner.lock();
        inner
            .subscription_mgr
            .as_ref()
            .ok_or(Error::NotConnected)
            .cloned()
    }

    /// Watch an extension's state via BLF (dialog event package, RFC 4235).
    ///
    /// The callback fires with the new `ExtensionStatus` and the previous state
    /// (`None` on the first update). Duplicate states are suppressed.
    pub fn watch<F>(&self, extension: &str, f: F) -> Result<()>
    where
        F: Fn(ExtensionStatus, Option<ExtensionState>) + Send + Sync + 'static,
    {
        if self.inner.lock().state != PhoneState::Registered {
            return Err(Error::NotRegistered);
        }
        let sub_mgr = self.get_sub_mgr()?;

        let uri = format!("sip:{}@{}", extension, self.cfg.host);
        let ext = extension.to_string();
        let phone_inner = Arc::clone(&self.inner);
        let f = Arc::new(f);

        let sub_id = sub_mgr.subscribe(
            &uri,
            "dialog",
            "application/dialog-info+xml",
            Arc::new(move |notify: NotifyEvent| {
                let new_state = if notify.body.is_empty() {
                    ExtensionState::Unknown
                } else {
                    parse_dialog_info(&notify.body)
                };

                // Duplicate suppression + track previous state.
                // Only update the ExtensionState; preserve the SubId.
                let (prev, should_fire) = {
                    let mut inner = phone_inner.lock();
                    if let Some((_sub_id, last)) = inner.blf_watchers.get_mut(&ext) {
                        if *last == new_state {
                            return; // No change — suppress.
                        }
                        let prev = Some(*last);
                        *last = new_state; // Only update state; SubId is preserved.
                        (prev, true)
                    } else {
                        // First NOTIFY before post-subscribe storage — use 0 as placeholder.
                        inner.blf_watchers.insert(ext.clone(), (0, new_state));
                        (None, true)
                    }
                };

                if should_fire {
                    let status = ExtensionStatus {
                        extension: ext.clone(),
                        state: new_state,
                    };
                    f(status, prev);
                }
            }),
        );

        // Store the SubId for unwatch.
        self.inner
            .lock()
            .blf_watchers
            .entry(extension.to_string())
            .and_modify(|(id, _)| *id = sub_id)
            .or_insert((sub_id, ExtensionState::Unknown));

        Ok(())
    }

    /// Stop watching an extension.
    pub fn unwatch(&self, extension: &str) -> Result<()> {
        let sub_mgr = self.get_sub_mgr()?;
        let sub_id = {
            let inner = self.inner.lock();
            let (sub_id, _) = inner
                .blf_watchers
                .get(extension)
                .ok_or_else(|| Error::Other(format!("not watching {}", extension)))?;
            *sub_id
        };

        sub_mgr.unsubscribe(sub_id);
        self.inner.lock().blf_watchers.remove(extension);
        Ok(())
    }

    /// Subscribe to a generic event package (power user API).
    /// Returns a subscription ID for later unsubscribe.
    pub fn subscribe_event<F>(&self, uri: &str, event: &str, accept: &str, f: F) -> Result<SubId>
    where
        F: Fn(NotifyEvent) + Send + Sync + 'static,
    {
        if self.inner.lock().state != PhoneState::Registered {
            return Err(Error::NotRegistered);
        }
        let sub_mgr = self.get_sub_mgr()?;
        Ok(sub_mgr.subscribe(uri, event, accept, Arc::new(f)))
    }

    /// Unsubscribe from a previously subscribed event.
    pub fn unsubscribe_event(&self, sub_id: SubId) -> Result<()> {
        let sub_mgr = self.get_sub_mgr()?;
        sub_mgr.unsubscribe(sub_id);
        Ok(())
    }

    /// Register a callback for subscription errors (permanent failures).
    pub fn on_subscription_error<F>(&self, f: F)
    where
        F: Fn(String, Error) + Send + Sync + 'static,
    {
        let mut inner = self.inner.lock();
        let f: Arc<dyn Fn(String, Error) + Send + Sync> = Arc::new(f);
        inner.on_subscription_error_fn.push(Arc::clone(&f));
        // If subscription manager already exists, wire it.
        if let Some(ref mgr) = inner.subscription_mgr {
            let f = Arc::clone(&f);
            mgr.on_error(move |uri, err| f(uri, err));
        }
    }

    /// Returns the current phone state.
    pub fn state(&self) -> PhoneState {
        self.inner.lock().state
    }

    /// Returns the configured SIP server host.
    pub fn host(&self) -> &str {
        &self.cfg.host
    }

    /// Registers a callback that fires for every call state change (all calls).
    /// Multiple callbacks can be registered; all will fire.
    pub fn on_call_state<F: Fn(Arc<Call>, crate::types::CallState) + Send + Sync + 'static>(
        &self,
        f: F,
    ) {
        self.inner.lock().on_call_state_fn.push(Arc::new(f));
    }

    /// Registers a callback that fires when any call ends.
    /// Multiple callbacks can be registered; all will fire.
    pub fn on_call_ended<F: Fn(Arc<Call>, crate::types::EndReason) + Send + Sync + 'static>(
        &self,
        f: F,
    ) {
        self.inner.lock().on_call_ended_fn.push(Arc::new(f));
    }

    /// Registers a callback that fires for DTMF digits received on any call.
    /// Multiple callbacks can be registered; all will fire.
    pub fn on_call_dtmf<F: Fn(Arc<Call>, String) + Send + Sync + 'static>(&self, f: F) {
        self.inner.lock().on_call_dtmf_fn.push(Arc::new(f));
    }

    /// Looks up an active call by dialog ID.
    pub fn find_call(&self, call_id: &str) -> Option<Arc<Call>> {
        self.inner.lock().calls.get(call_id).cloned()
    }

    /// Returns all active calls.
    /// Useful for call waiting UIs that need to display concurrent calls.
    pub fn calls(&self) -> Vec<Arc<Call>> {
        self.inner.lock().calls.values().cloned().collect()
    }

    /// Performs an attended transfer. Delegates to [`Call::attended_transfer`].
    pub fn attended_transfer(&self, call_a: &Arc<Call>, call_b: &Arc<Call>) -> Result<()> {
        call_a.attended_transfer(call_b)
    }
}

impl Drop for Phone {
    fn drop(&mut self) {
        // Only disconnect if this is the last clone — dropping a clone must not
        // tear down the shared registration/transport.
        if Arc::strong_count(&self.inner) == 1 {
            let _ = self.disconnect();
        }
    }
}

/// Discovers the local IP address used to reach the given host.
/// Uses a connectionless UDP dial (no packets sent).
fn local_ip_for(host: &str) -> String {
    use std::net::UdpSocket;
    let target = format!("{}:5060", host);
    match UdpSocket::bind("0.0.0.0:0") {
        Ok(sock) => match sock.connect(&target) {
            Ok(()) => match sock.local_addr() {
                Ok(addr) if !addr.ip().is_unspecified() => addr.ip().to_string(),
                _ => "127.0.0.1".into(),
            },
            Err(_) => "127.0.0.1".into(),
        },
        Err(_) => "127.0.0.1".into(),
    }
}

/// Handles an incoming INVITE from the transport.
fn handle_incoming(inner: &Arc<Mutex<Inner>>, from: &str, to: &str) {
    let (tr, incoming_fns) = {
        let guard = inner.lock();
        (guard.tr.clone(), guard.incoming.clone())
    };

    // Send 100 Trying.
    if let Some(ref tr) = tr {
        tr.respond(100, "Trying");
    }

    // Create an inbound call with a stub dialog.
    let dlg = Arc::new(MockDialog::new());
    let call = Call::new_inbound(dlg as Arc<dyn Dialog>);

    // Wire phone-level callbacks + call-tracking cleanup.
    wire_phone_call_callbacks(inner, &call);

    // Track the call.
    inner.lock().calls.insert(call.call_id(), Arc::clone(&call));

    // Log incoming call details (suppress unused warnings).
    let _ = (from, to);

    // Fire OnIncoming callbacks.
    for f in &incoming_fns {
        f(Arc::clone(&call));
    }

    // Send 180 Ringing.
    if let Some(ref tr) = tr {
        tr.respond(180, "Ringing");
    }
}

/// Wire phone-level call callbacks onto an individual call.
fn wire_phone_call_callbacks(inner: &Arc<Mutex<Inner>>, call: &Arc<Call>) {
    // Copy callbacks and config out of Phone lock, then drop it before acquiring Call lock.
    let (state_fns, ended_fns, dtmf_fns, dtmf_mode) = {
        let locked = inner.lock();
        (
            locked.on_call_state_fn.clone(),
            locked.on_call_ended_fn.clone(),
            locked.on_call_dtmf_fn.clone(),
            locked.dtmf_mode,
        )
    };

    call.set_dtmf_mode(dtmf_mode);

    if !state_fns.is_empty() {
        let c = Arc::clone(call);
        call.on_state_internal(move |s| {
            for f in &state_fns {
                f(Arc::clone(&c), s);
            }
        });
    }

    // Combine phone-level on_ended callbacks with call-tracking cleanup
    // into a single on_ended_internal closure so neither overwrites the other.
    {
        let inner_clone = Arc::clone(inner);
        let call_id = call.call_id();
        let c = Arc::clone(call);
        call.on_ended_internal(move |r| {
            // Call-tracking cleanup.
            inner_clone.lock().calls.remove(&call_id);
            // Phone-level on_call_ended callbacks.
            for f in &ended_fns {
                f(Arc::clone(&c), r);
            }
        });
    }

    if !dtmf_fns.is_empty() {
        let c = Arc::clone(call);
        call.on_dtmf_internal(move |d| {
            for f in &dtmf_fns {
                f(Arc::clone(&c), d.clone());
            }
        });
    }
}

#[allow(clippy::too_many_arguments)]
fn handle_dialog_incoming(
    inner: &Arc<Mutex<Inner>>,
    dlg: Arc<dyn Dialog>,
    _from: &str,
    _to: &str,
    remote_sdp: &str,
    local_ip: &str,
    rtp_port_min: u16,
    rtp_port_max: u16,
) {
    // Check if this is a re-INVITE for an existing call (same Call-ID).
    let call_id = dlg.call_id();
    let existing_call = inner.lock().calls.get(&call_id).cloned();
    if let Some(call) = existing_call {
        info!(call_id = %call_id, "Phone handling re-INVITE for existing call");
        handle_reinvite(&call, dlg, remote_sdp, rtp_port_min, rtp_port_max);
        return;
    }

    info!(from = _from, to = _to, "Phone handling incoming INVITE");
    let incoming_fns = inner.lock().incoming.clone();

    // Allocate an RTP socket for this call (ephemeral port if range is 0,0).
    let (rtp_socket, actual_port) = match crate::media::listen_rtp_port(rtp_port_min, rtp_port_max)
    {
        Ok((sock, port)) => (Some(sock), port as i32),
        Err(e) => {
            warn!("RTP port allocation failed for incoming call, rejecting: {e}");
            let _ = dlg.respond(503, "Service Unavailable", &[]);
            return;
        }
    };

    // Parse remote SDP once for SRTP detection and video detection.
    let parsed_sdp = crate::sdp::parse(remote_sdp).ok();

    // Only use SRTP if the remote actually offers RTP/SAVP with a supported suite.
    let use_srtp = parsed_sdp.as_ref().is_some_and(|sess| {
        sess.is_srtp()
            && sess
                .first_crypto()
                .is_some_and(|c| c.suite == crate::srtp::SUPPORTED_SUITE)
    });

    // Create an inbound call with the real dialog.
    let call = Call::new_inbound(dlg);
    call.set_local_media(local_ip, actual_port);
    if use_srtp {
        match crate::srtp::generate_keying_material() {
            Ok((_material, encoded)) => call.set_srtp(&encoded),
            Err(e) => {
                tracing::error!("failed to generate SRTP keying material: {}", e);
                return;
            }
        }
    }
    if let Some(sock) = rtp_socket {
        call.set_rtp_socket(sock);
    }

    // Allocate video RTP socket if remote SDP offers video.
    if let Some(ref sess) = parsed_sdp {
        if sess.has_video() {
            if let Ok((vsock, vport)) = crate::media::listen_rtp_port(rtp_port_min, rtp_port_max) {
                call.set_video_rtp_port(vport as i32);
                call.set_video_rtp_socket(vsock);
            }
        }
    }

    if !remote_sdp.is_empty() {
        call.set_remote_sdp(remote_sdp);
    }

    // Wire phone-level callbacks + call-tracking cleanup before anything fires.
    wire_phone_call_callbacks(inner, &call);

    // Track the call.
    inner.lock().calls.insert(call.call_id(), Arc::clone(&call));

    // Send 180 Ringing via dialog.
    let _ = call.dlg_respond(180, "Ringing");

    // Fire OnIncoming callbacks.
    for f in &incoming_fns {
        f(Arc::clone(&call));
    }
}

/// Handles a mid-dialog re-INVITE for an existing call (e.g., video upgrade, hold/resume).
fn handle_reinvite(
    call: &Arc<Call>,
    dlg: Arc<dyn Dialog>,
    remote_sdp: &str,
    rtp_port_min: u16,
    rtp_port_max: u16,
) {
    call.handle_reinvite(&dlg, remote_sdp, rtp_port_min, rtp_port_max);
}

/// Handles an incoming BYE — looks up the call by Call-ID and simulates BYE.
fn handle_bye(inner: &Arc<Mutex<Inner>>, call_id: &str) {
    info!(call_id = %call_id, "Phone handling BYE");
    let call = inner.lock().calls.get(call_id).cloned();
    if let Some(call) = call {
        call.simulate_bye();
    } else {
        debug!(call_id = %call_id, "Phone BYE for unknown call (already ended)");
    }
}

/// Handles an incoming SIP INFO DTMF — looks up the call by Call-ID and fires its DTMF callback.
fn handle_info_dtmf(inner: &Arc<Mutex<Inner>>, call_id: &str, digit: &str) {
    info!(call_id = %call_id, digit = %digit, "Phone handling INFO DTMF");
    let call = inner.lock().calls.get(call_id).cloned();
    if let Some(call) = call {
        call.fire_dtmf(digit);
    } else {
        debug!(call_id = %call_id, "Phone INFO DTMF for unknown call");
    }
}

fn handle_notify(inner: &Arc<Mutex<Inner>>, call_id: &str, code: u16) {
    info!(call_id = %call_id, code = code, "Phone handling NOTIFY");
    let call = inner.lock().calls.get(call_id).cloned();
    if let Some(call) = call {
        call.fire_notify(code);
    } else {
        warn!(call_id = %call_id, "Phone NOTIFY for unknown call");
    }
}

/// Handles an incoming SIP MESSAGE — fires the on_message callback.
fn handle_message(inner: &Arc<Mutex<Inner>>, from: &str, content_type: &str, body: &str) {
    info!(from = %from, "Phone handling MESSAGE");
    let cbs = inner.lock().on_message_fn.clone();
    for f in cbs {
        let msg = SipMessage {
            from: from.to_string(),
            to: String::new(),
            content_type: content_type.to_string(),
            body: body.to_string(),
        };
        crate::callback_pool::spawn_callback(move || f(msg));
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::mock::transport::{MockTransport, Response};
    use std::time::Duration;

    fn test_cfg() -> Config {
        Config {
            register_expiry: Duration::from_secs(60),
            register_retry: Duration::from_millis(50),
            register_max_retry: 3,
            nat_keepalive_interval: None,
            ..Config::default()
        }
    }

    #[test]
    fn connect_and_state() {
        let tr = Arc::new(MockTransport::new());
        tr.respond_with(200, "OK"); // for REGISTER

        let phone = Phone::new(test_cfg());
        phone.connect_with_transport(Arc::clone(&tr) as Arc<dyn SipTransport>);

        assert_eq!(phone.state(), PhoneState::Registered);
        assert_eq!(tr.count_sent("REGISTER"), 1);
    }

    #[test]
    fn disconnect_sets_disconnected() {
        let tr = Arc::new(MockTransport::new());
        tr.respond_with(200, "OK");

        let phone = Phone::new(test_cfg());
        phone.connect_with_transport(Arc::clone(&tr) as Arc<dyn SipTransport>);
        phone.disconnect().unwrap();

        assert_eq!(phone.state(), PhoneState::Disconnected);
        assert!(tr.closed());
    }

    #[test]
    fn disconnect_when_not_connected_returns_error() {
        let phone = Phone::new(test_cfg());
        let result = phone.disconnect();
        assert!(result.is_err());
    }

    #[test]
    fn dial_before_connect_returns_error() {
        let phone = Phone::new(test_cfg());
        let result = phone.dial("sip:1002@pbx.local", DialOptions::default());
        assert!(result.is_err());
    }

    #[test]
    fn dial_sends_invite_and_creates_call() {
        let tr = Arc::new(MockTransport::new());
        tr.respond_with(200, "OK"); // REGISTER
        let phone = Phone::new(test_cfg());
        phone.connect_with_transport(Arc::clone(&tr) as Arc<dyn SipTransport>);

        // Queue INVITE response.
        tr.respond_with(200, "OK");
        let call = phone
            .dial("sip:1002@pbx.local", DialOptions::default())
            .unwrap();

        assert_eq!(tr.count_sent("INVITE"), 1);
        // Call should be active after 200 OK.
        assert_eq!(call.state(), crate::types::CallState::Active);
    }

    #[test]
    fn dial_with_ringing() {
        let tr = Arc::new(MockTransport::new());
        tr.respond_with(200, "OK"); // REGISTER

        let phone = Phone::new(test_cfg());
        phone.connect_with_transport(Arc::clone(&tr) as Arc<dyn SipTransport>);

        // Queue a sequence: 180 Ringing -> 200 OK.
        tr.respond_sequence(vec![
            Response::new(180, "Ringing"),
            Response::new(200, "OK"),
        ]);

        let call = phone
            .dial("sip:1002@pbx.local", DialOptions::default())
            .unwrap();
        assert_eq!(call.state(), crate::types::CallState::Active);
    }

    #[test]
    fn incoming_call_fires_callback() {
        let tr = Arc::new(MockTransport::new());
        tr.respond_with(200, "OK"); // REGISTER

        let phone = Phone::new(test_cfg());

        let (tx, rx) = crossbeam_channel::bounded(1);
        phone.on_incoming(move |_call| {
            let _ = tx.send(true);
        });

        phone.connect_with_transport(Arc::clone(&tr) as Arc<dyn SipTransport>);

        tr.simulate_invite("sip:1001@pbx.local", "sip:1002@pbx.local");

        let fired = rx.recv_timeout(Duration::from_secs(2)).unwrap();
        assert!(fired);
    }

    #[test]
    fn incoming_call_sends_100_and_180() {
        let tr = Arc::new(MockTransport::new());
        tr.respond_with(200, "OK"); // REGISTER

        let phone = Phone::new(test_cfg());
        phone.on_incoming(|_| {});
        phone.connect_with_transport(Arc::clone(&tr) as Arc<dyn SipTransport>);

        // Wait for 100 and 180.
        let rx100 = tr.wait_for_response(100, Duration::from_secs(2));
        let rx180 = tr.wait_for_response(180, Duration::from_secs(2));

        tr.simulate_invite("sip:1001@pbx.local", "sip:1002@pbx.local");

        assert!(rx100.recv_timeout(Duration::from_secs(2)).unwrap());
        assert!(rx180.recv_timeout(Duration::from_secs(2)).unwrap());
    }

    #[test]
    fn on_registered_callback() {
        let tr = Arc::new(MockTransport::new());
        tr.respond_with(200, "OK");

        let phone = Phone::new(test_cfg());

        let (tx, rx) = crossbeam_channel::bounded(1);
        phone.on_registered(move || {
            let _ = tx.send(true);
        });

        phone.connect_with_transport(Arc::clone(&tr) as Arc<dyn SipTransport>);

        let fired = rx.recv_timeout(Duration::from_secs(2)).unwrap();
        assert!(fired);
    }

    #[test]
    fn on_unregistered_fires_on_disconnect() {
        let tr = Arc::new(MockTransport::new());
        tr.respond_with(200, "OK");

        let phone = Phone::new(test_cfg());

        let (tx, rx) = crossbeam_channel::bounded(1);
        phone.on_unregistered(move || {
            let _ = tx.send(true);
        });

        phone.connect_with_transport(Arc::clone(&tr) as Arc<dyn SipTransport>);
        phone.disconnect().unwrap();

        let fired = rx.recv_timeout(Duration::from_secs(2)).unwrap();
        assert!(fired);
    }

    #[test]
    fn call_tracking() {
        let tr = Arc::new(MockTransport::new());
        tr.respond_with(200, "OK"); // REGISTER

        let phone = Phone::new(test_cfg());
        phone.connect_with_transport(Arc::clone(&tr) as Arc<dyn SipTransport>);

        tr.respond_with(200, "OK"); // INVITE
        let call = phone
            .dial("sip:1002@pbx.local", DialOptions::default())
            .unwrap();
        let call_id = call.call_id();

        // Call should be tracked.
        assert!(phone.find_call(&call_id).is_some());

        // End the call.
        call.end().unwrap();

        // Give the callback thread time to fire.
        std::thread::sleep(Duration::from_millis(100));

        // Call should be untracked.
        assert!(phone.find_call(&call_id).is_none());
    }

    #[test]
    fn dial_uses_advertised_addr_in_sdp() {
        let tr = Arc::new(MockTransport::new());
        tr.respond_with(200, "OK"); // REGISTER

        // Simulate a STUN-mapped address.
        let stun_ip: std::net::SocketAddr = "203.0.113.42:5060".parse().unwrap();
        tr.set_advertised_addr(stun_ip);

        let phone = Phone::new(test_cfg());
        phone.connect_with_transport(Arc::clone(&tr) as Arc<dyn SipTransport>);

        tr.respond_with(200, "OK"); // INVITE
        let call = phone
            .dial("sip:1002@pbx.local", DialOptions::default())
            .unwrap();

        // The local SDP should contain the STUN-mapped IP, not a local IP.
        let sdp = call.local_sdp();
        assert!(
            sdp.contains("c=IN IP4 203.0.113.42"),
            "SDP should contain STUN-mapped IP, got: {}",
            sdp
        );
    }

    #[test]
    fn dial_prefers_local_ip_config_over_advertised_addr() {
        let tr = Arc::new(MockTransport::new());
        tr.respond_with(200, "OK"); // REGISTER

        // Set both advertised addr and explicit local_ip.
        let stun_ip: std::net::SocketAddr = "203.0.113.42:5060".parse().unwrap();
        tr.set_advertised_addr(stun_ip);

        let mut cfg = test_cfg();
        cfg.local_ip = "10.0.0.99".into();
        let phone = Phone::new(cfg);
        phone.connect_with_transport(Arc::clone(&tr) as Arc<dyn SipTransport>);

        tr.respond_with(200, "OK"); // INVITE
        let call = phone
            .dial("sip:1002@pbx.local", DialOptions::default())
            .unwrap();

        // Explicit local_ip should take priority over STUN.
        let sdp = call.local_sdp();
        assert!(
            sdp.contains("c=IN IP4 10.0.0.99"),
            "SDP should use explicit local_ip over STUN, got: {}",
            sdp
        );
    }

    #[test]
    fn dial_with_early_media_transitions_through_early_media_state() {
        let tr = Arc::new(MockTransport::new());
        tr.respond_with(200, "OK"); // REGISTER

        let phone = Phone::new(test_cfg());
        phone.connect_with_transport(Arc::clone(&tr) as Arc<dyn SipTransport>);

        // Set up early media SDP from the "remote" side.
        let early_sdp = "v=0\r\no=- 0 0 IN IP4 10.0.0.1\r\ns=-\r\nc=IN IP4 10.0.0.1\r\nm=audio 20000 RTP/AVP 8\r\n";
        tr.set_early_sdp(early_sdp);
        tr.respond_with(200, "OK"); // INVITE

        // Use a channel to detect EarlyMedia state (callbacks fire in spawned threads).
        let (em_tx, em_rx) = crossbeam_channel::bounded(1);
        phone.on_call_state(move |_call, state| {
            if state == crate::types::CallState::EarlyMedia {
                let _ = em_tx.try_send(());
            }
        });

        let opts = crate::config::DialOptions {
            early_media: true,
            ..Default::default()
        };

        let call = phone.dial("sip:1002@pbx.local", opts).unwrap();
        assert_eq!(call.state(), crate::types::CallState::Active);

        // Verify the call transitioned through EarlyMedia.
        let got_early = em_rx.recv_timeout(Duration::from_secs(2)).is_ok();
        assert!(got_early, "should have transitioned through EarlyMedia");

        // Remote SDP should have been set from the early media SDP.
        assert!(!call.remote_sdp().is_empty());
    }

    #[test]
    fn phone_and_user_callbacks_both_fire() {
        let tr = Arc::new(MockTransport::new());
        tr.respond_with(200, "OK"); // REGISTER

        let phone = Phone::new(test_cfg());

        // Phone-level callback (wired internally).
        let (phone_tx, phone_rx) = crossbeam_channel::bounded(1);
        phone.on_call_state(move |_call, state| {
            if state == crate::types::CallState::Active {
                let _ = phone_tx.try_send(());
            }
        });

        phone.connect_with_transport(Arc::clone(&tr) as Arc<dyn SipTransport>);

        tr.respond_with(200, "OK"); // INVITE
        let call = phone
            .dial("sip:1002@pbx.local", DialOptions::default())
            .unwrap();

        // User-level callback (should NOT overwrite phone-level).
        let (user_tx, user_rx) = crossbeam_channel::bounded(1);
        call.on_state(move |state| {
            if state == crate::types::CallState::Ended {
                let _ = user_tx.try_send(());
            }
        });

        // Phone-level should have already fired for Active.
        let got_phone = phone_rx.recv_timeout(Duration::from_secs(2)).is_ok();
        assert!(got_phone, "phone-level on_call_state should have fired");

        // End the call — user-level callback should fire.
        call.end().unwrap();
        let got_user = user_rx.recv_timeout(Duration::from_secs(2)).is_ok();
        assert!(got_user, "user-level on_state should have fired");
    }

    #[test]
    fn info_dtmf_fires_call_dtmf_callback() {
        let tr = Arc::new(MockTransport::new());
        tr.respond_with(200, "OK"); // REGISTER

        let phone = Phone::new(test_cfg());

        let (dtmf_tx, dtmf_rx) = crossbeam_channel::bounded(1);
        phone.on_call_dtmf(move |_call, digit| {
            let _ = dtmf_tx.send(digit);
        });

        phone.connect_with_transport(Arc::clone(&tr) as Arc<dyn SipTransport>);

        // Dial to create a call.
        tr.respond_with(200, "OK"); // INVITE
        let call = phone
            .dial("sip:1002@pbx.local", DialOptions::default())
            .unwrap();
        let call_id = call.call_id();

        // Simulate incoming SIP INFO DTMF.
        tr.simulate_info_dtmf(&call_id, "5");

        let digit = dtmf_rx.recv_timeout(Duration::from_secs(2)).unwrap();
        assert_eq!(digit, "5");
    }

    #[test]
    fn dtmf_mode_propagated_to_calls() {
        let tr = Arc::new(MockTransport::new());
        tr.respond_with(200, "OK"); // REGISTER

        let mut cfg = test_cfg();
        cfg.dtmf_mode = crate::config::DtmfMode::SipInfo;
        let phone = Phone::new(cfg);
        phone.connect_with_transport(Arc::clone(&tr) as Arc<dyn SipTransport>);

        // Dial to create a call.
        tr.respond_with(200, "OK"); // INVITE
        let call = phone
            .dial("sip:1002@pbx.local", DialOptions::default())
            .unwrap();

        // Verify dtmf_mode was propagated: send_dtmf("3") should use SIP INFO.
        // Detailed MockDialog inspection is in call::tests::send_dtmf_sip_info_mode.
        // Here we just verify it doesn't error (SIP INFO path doesn't need RTP socket).
        call.send_dtmf("3").unwrap();
    }

    // --- Call waiting / multi-call ---

    #[test]
    fn two_concurrent_outbound_calls() {
        let tr = Arc::new(MockTransport::new());
        tr.respond_with(200, "OK"); // REGISTER

        let phone = Phone::new(test_cfg());
        phone.connect_with_transport(Arc::clone(&tr) as Arc<dyn SipTransport>);

        tr.respond_with(200, "OK"); // INVITE 1
        let call1 = phone
            .dial("sip:1002@pbx.local", DialOptions::default())
            .unwrap();

        tr.respond_with(200, "OK"); // INVITE 2
        let call2 = phone
            .dial("sip:1003@pbx.local", DialOptions::default())
            .unwrap();

        assert_ne!(call1.call_id(), call2.call_id());
        assert!(phone.find_call(&call1.call_id()).is_some());
        assert!(phone.find_call(&call2.call_id()).is_some());
        assert_eq!(phone.calls().len(), 2);
    }

    #[test]
    fn incoming_during_active_call_fires_callback() {
        let tr = Arc::new(MockTransport::new());
        tr.respond_with(200, "OK"); // REGISTER

        let phone = Phone::new(test_cfg());

        let (tx, rx) = crossbeam_channel::bounded(1);
        phone.on_incoming(move |_call| {
            let _ = tx.send(true);
        });

        phone.connect_with_transport(Arc::clone(&tr) as Arc<dyn SipTransport>);

        // Create an active outbound call.
        tr.respond_with(200, "OK"); // INVITE
        let call1 = phone
            .dial("sip:1002@pbx.local", DialOptions::default())
            .unwrap();
        assert_eq!(call1.state(), crate::types::CallState::Active);

        // Simulate an incoming INVITE while the first call is active.
        tr.simulate_invite("sip:1001@pbx.local", "sip:1003@pbx.local");

        let fired = rx.recv_timeout(Duration::from_secs(2)).unwrap();
        assert!(fired);
        assert_eq!(phone.calls().len(), 2);
    }

    #[test]
    fn bye_for_one_call_leaves_other_active() {
        let tr = Arc::new(MockTransport::new());
        tr.respond_with(200, "OK"); // REGISTER

        let phone = Phone::new(test_cfg());
        phone.connect_with_transport(Arc::clone(&tr) as Arc<dyn SipTransport>);

        tr.respond_with(200, "OK");
        let call1 = phone
            .dial("sip:1002@pbx.local", DialOptions::default())
            .unwrap();
        tr.respond_with(200, "OK");
        let call2 = phone
            .dial("sip:1003@pbx.local", DialOptions::default())
            .unwrap();

        assert_eq!(phone.calls().len(), 2);

        // End call1 — call2 should remain active.
        call1.end().unwrap();
        std::thread::sleep(Duration::from_millis(100));

        assert!(phone.find_call(&call1.call_id()).is_none());
        assert!(phone.find_call(&call2.call_id()).is_some());
        assert_eq!(call2.state(), crate::types::CallState::Active);
        assert_eq!(phone.calls().len(), 1);
    }

    #[test]
    fn disconnect_ends_all_calls() {
        let tr = Arc::new(MockTransport::new());
        tr.respond_with(200, "OK"); // REGISTER

        let phone = Phone::new(test_cfg());
        phone.connect_with_transport(Arc::clone(&tr) as Arc<dyn SipTransport>);

        tr.respond_with(200, "OK");
        let call1 = phone
            .dial("sip:1002@pbx.local", DialOptions::default())
            .unwrap();
        tr.respond_with(200, "OK");
        let call2 = phone
            .dial("sip:1003@pbx.local", DialOptions::default())
            .unwrap();

        phone.disconnect().unwrap();

        assert_eq!(call1.state(), crate::types::CallState::Ended);
        assert_eq!(call2.state(), crate::types::CallState::Ended);
        assert!(phone.calls().is_empty());
    }

    #[test]
    fn calls_returns_all_active() {
        let tr = Arc::new(MockTransport::new());
        tr.respond_with(200, "OK"); // REGISTER

        let phone = Phone::new(test_cfg());
        phone.connect_with_transport(Arc::clone(&tr) as Arc<dyn SipTransport>);

        assert!(phone.calls().is_empty());

        tr.respond_with(200, "OK");
        phone
            .dial("sip:1002@pbx.local", DialOptions::default())
            .unwrap();
        assert_eq!(phone.calls().len(), 1);

        tr.respond_with(200, "OK");
        phone
            .dial("sip:1003@pbx.local", DialOptions::default())
            .unwrap();
        assert_eq!(phone.calls().len(), 2);
    }

    #[test]
    fn dialog_invite_during_active_call() {
        let tr = Arc::new(MockTransport::new());
        tr.respond_with(200, "OK"); // REGISTER

        let phone = Phone::new(test_cfg());

        let (tx, rx) = crossbeam_channel::bounded(1);
        phone.on_incoming(move |call| {
            let _ = tx.send(call.call_id());
        });

        phone.connect_with_transport(Arc::clone(&tr) as Arc<dyn SipTransport>);

        // Active outbound call.
        tr.respond_with(200, "OK");
        let call1 = phone
            .dial("sip:1002@pbx.local", DialOptions::default())
            .unwrap();

        // Incoming via dialog path (production path).
        let sdp = "v=0\r\no=- 0 0 IN IP4 10.0.0.1\r\ns=-\r\nc=IN IP4 10.0.0.1\r\nm=audio 20000 RTP/AVP 8\r\n";
        tr.simulate_dialog_invite("sip:1001@pbx.local", "sip:1003@pbx.local", sdp);

        let incoming_id = rx.recv_timeout(Duration::from_secs(2)).unwrap();
        assert_ne!(incoming_id, call1.call_id());
        assert_eq!(phone.calls().len(), 2);
    }

    #[test]
    fn call_arc_freed_after_end() {
        // Verifies circular Arc references are broken when a call ends.
        let tr = Arc::new(MockTransport::new());
        tr.respond_with(200, "OK"); // REGISTER

        let phone = Phone::new(test_cfg());
        phone.on_call_state(|_call, _state| {});
        phone.on_call_ended(|_call, _reason| {});
        phone.on_call_dtmf(|_call, _digit| {});
        phone.connect_with_transport(Arc::clone(&tr) as Arc<dyn SipTransport>);

        tr.respond_with(200, "OK");
        let call = phone
            .dial("sip:1002@pbx.local", DialOptions::default())
            .unwrap();
        call.end().unwrap();

        // Give callback threads time to complete.
        std::thread::sleep(Duration::from_millis(200));

        // After end, our local `call` + the on_ended spawn should be the only Arc holders.
        // Phone's HashMap should have removed it. The circular callback references
        // should have been cleared by fire_on_ended.
        assert!(phone.find_call(&call.call_id()).is_none());
        // The Arc strong count should be 1 (our local variable only).
        assert_eq!(
            Arc::strong_count(&call),
            1,
            "Call Arc should have no other holders after end + callback cleanup"
        );
    }

    // --- Attended Transfer ---

    fn mock_dlg_with_tags(
        call_id: &str,
        from: &str,
        to: &str,
    ) -> Arc<crate::mock::dialog::MockDialog> {
        let mut h = std::collections::HashMap::new();
        h.insert("From".into(), vec![from.into()]);
        h.insert("To".into(), vec![to.into()]);
        let dlg = crate::mock::dialog::MockDialog::with_headers(h);
        dlg.set_call_id(call_id);
        Arc::new(dlg)
    }

    #[test]
    fn attended_transfer_sends_refer_with_replaces() {
        let tr = Arc::new(MockTransport::new());
        tr.respond_with(200, "OK"); // REGISTER
        let phone = Phone::new(test_cfg());
        phone.connect_with_transport(Arc::clone(&tr) as Arc<dyn SipTransport>);

        // Create Call A (outbound to Bob) with dialog tags.
        let dlg_a = mock_dlg_with_tags(
            "call-a-id",
            "<sip:1001@pbx>;tag=alice-a",
            "<sip:bob@pbx>;tag=bob-a",
        );
        let call_a = Call::new_outbound(dlg_a.clone(), DialOptions::default());
        call_a.simulate_response(200, "OK");

        // Create Call B (outbound to Charlie) with dialog tags.
        let dlg_b = mock_dlg_with_tags(
            "call-b-id@pbx.local",
            "<sip:1001@pbx>;tag=alice-b",
            "<sip:charlie@pbx>;tag=charlie-b",
        );
        let call_b = Call::new_outbound(dlg_b.clone(), DialOptions::default());
        call_b.simulate_response(200, "OK");
        call_b.hold().unwrap(); // typically call_b is active during consultation

        // Execute attended transfer.
        phone.attended_transfer(&call_a, &call_b).unwrap();

        // Verify REFER was sent on Call A's dialog.
        assert!(dlg_a.refer_sent());
        let refer_target = dlg_a.last_refer_target();

        // Refer-To should point to Charlie's URI with Replaces encoding.
        assert!(
            refer_target.starts_with("sip:charlie@pbx?Replaces="),
            "REFER target should start with Charlie's URI: {}",
            refer_target
        );
        // Call-ID should be URL-encoded (@ -> %40).
        assert!(
            refer_target.contains("call-b-id%40pbx.local"),
            "Call-ID @ should be encoded: {}",
            refer_target
        );
        // Tags should be present with URL-encoded separators.
        assert!(
            refer_target.contains("to-tag%3Dcharlie-b"),
            "remote tag (charlie) should be in to-tag: {}",
            refer_target
        );
        assert!(
            refer_target.contains("from-tag%3Dalice-b"),
            "local tag (alice) should be in from-tag: {}",
            refer_target
        );
    }

    #[test]
    fn attended_transfer_ends_both_on_notify_200() {
        let tr = Arc::new(MockTransport::new());
        tr.respond_with(200, "OK");
        let phone = Phone::new(test_cfg());
        phone.connect_with_transport(Arc::clone(&tr) as Arc<dyn SipTransport>);

        let dlg_a = mock_dlg_with_tags("call-a", "<sip:1001@pbx>;tag=a1", "<sip:bob@pbx>;tag=b1");
        let dlg_b = mock_dlg_with_tags(
            "call-b",
            "<sip:1001@pbx>;tag=a2",
            "<sip:charlie@pbx>;tag=c2",
        );
        let call_a = Call::new_outbound(dlg_a.clone(), DialOptions::default());
        call_a.simulate_response(200, "OK");
        let call_b = Call::new_outbound(dlg_b.clone(), DialOptions::default());
        call_b.simulate_response(200, "OK");

        let (tx_a, rx_a) = crossbeam_channel::bounded(1);
        let (tx_b, rx_b) = crossbeam_channel::bounded(1);
        call_a.on_ended(move |r| {
            let _ = tx_a.send(r);
        });
        call_b.on_ended(move |r| {
            let _ = tx_b.send(r);
        });

        phone.attended_transfer(&call_a, &call_b).unwrap();

        // Simulate successful NOTIFY from Bob.
        dlg_a.simulate_notify(200);

        // Wait for callbacks.
        std::thread::sleep(Duration::from_millis(100));

        assert_eq!(call_a.state(), CallState::Ended);
        assert_eq!(call_b.state(), CallState::Ended);
        assert_eq!(
            rx_a.recv_timeout(Duration::from_millis(200)).unwrap(),
            EndReason::Transfer
        );
        assert_eq!(
            rx_b.recv_timeout(Duration::from_millis(200)).unwrap(),
            EndReason::Transfer
        );
    }

    #[test]
    fn attended_transfer_rejects_inactive_call_a() {
        let phone = Phone::new(test_cfg());
        let dlg_a = Arc::new(MockDialog::new());
        let dlg_b = Arc::new(MockDialog::new());
        let call_a = Call::new_inbound(dlg_a); // Ringing, not Active
        let call_b = Call::new_outbound(dlg_b, DialOptions::default());
        call_b.simulate_response(200, "OK");

        let result = phone.attended_transfer(&call_a, &call_b);
        assert!(result.is_err());
    }

    #[test]
    fn attended_transfer_rejects_inactive_call_b() {
        let phone = Phone::new(test_cfg());
        let dlg_a = Arc::new(MockDialog::new());
        let dlg_b = Arc::new(MockDialog::new());
        let call_a = Call::new_inbound(dlg_a);
        call_a.accept().unwrap();
        let call_b = Call::new_inbound(dlg_b); // Ringing, not Active

        let result = phone.attended_transfer(&call_a, &call_b);
        assert!(result.is_err());
    }

    #[test]
    fn attended_transfer_notify_non_200_keeps_calls_alive() {
        let tr = Arc::new(MockTransport::new());
        tr.respond_with(200, "OK");
        let phone = Phone::new(test_cfg());
        phone.connect_with_transport(Arc::clone(&tr) as Arc<dyn SipTransport>);

        let dlg_a = mock_dlg_with_tags("call-a", "<sip:1001@pbx>;tag=a1", "<sip:bob@pbx>;tag=b1");
        let dlg_b = mock_dlg_with_tags(
            "call-b",
            "<sip:1001@pbx>;tag=a2",
            "<sip:charlie@pbx>;tag=c2",
        );
        let call_a = Call::new_outbound(dlg_a.clone(), DialOptions::default());
        call_a.simulate_response(200, "OK");
        let call_b = Call::new_outbound(dlg_b.clone(), DialOptions::default());
        call_b.simulate_response(200, "OK");

        phone.attended_transfer(&call_a, &call_b).unwrap();

        // NOTIFY 100 (Trying) should NOT end the calls.
        dlg_a.simulate_notify(100);
        std::thread::sleep(Duration::from_millis(50));

        assert_eq!(call_a.state(), CallState::Active);
        assert_eq!(call_b.state(), CallState::Active);
    }

    // --- MWI ---

    #[test]
    fn mwi_subscribes_on_connect() {
        let tr = Arc::new(MockTransport::new());
        tr.respond_with(200, "OK"); // REGISTER
        tr.respond_with(200, "OK"); // SUBSCRIBE

        let mut cfg = test_cfg();
        cfg.voicemail_uri = Some("sip:*97@pbx.local".into());
        let phone = Phone::new(cfg);
        phone.connect_with_transport(Arc::clone(&tr) as Arc<dyn SipTransport>);

        // Give MWI thread time to send SUBSCRIBE.
        std::thread::sleep(Duration::from_millis(300));

        assert!(
            tr.count_sent("SUBSCRIBE") >= 1,
            "expected at least 1 SUBSCRIBE, got {}",
            tr.count_sent("SUBSCRIBE")
        );

        phone.disconnect().unwrap();
    }

    #[test]
    fn mwi_fires_on_voicemail_callback() {
        let tr = Arc::new(MockTransport::new());
        tr.respond_with(200, "OK"); // REGISTER
        tr.respond_with(200, "OK"); // SUBSCRIBE

        let mut cfg = test_cfg();
        cfg.voicemail_uri = Some("sip:*97@pbx.local".into());
        let phone = Phone::new(cfg);

        let (tx, rx) = crossbeam_channel::bounded(1);
        phone.on_voicemail(move |status| {
            let _ = tx.send(status);
        });

        phone.connect_with_transport(Arc::clone(&tr) as Arc<dyn SipTransport>);
        std::thread::sleep(Duration::from_millis(200));

        // Simulate MWI NOTIFY.
        tr.simulate_mwi_notify("Messages-Waiting: yes\r\nVoice-Message: 2/4\r\n");

        let status = rx.recv_timeout(Duration::from_secs(2)).unwrap();
        assert!(status.messages_waiting);
        assert_eq!(status.voice, (2, 4));

        phone.disconnect().unwrap();
    }

    #[test]
    fn no_mwi_without_voicemail_uri() {
        let tr = Arc::new(MockTransport::new());
        tr.respond_with(200, "OK"); // REGISTER

        let phone = Phone::new(test_cfg()); // no voicemail_uri
        phone.connect_with_transport(Arc::clone(&tr) as Arc<dyn SipTransport>);

        std::thread::sleep(Duration::from_millis(200));
        assert_eq!(tr.count_sent("SUBSCRIBE"), 0);

        phone.disconnect().unwrap();
    }

    #[test]
    fn send_message_before_connect_returns_error() {
        let phone = Phone::new(test_cfg());
        let result = phone.send_message("sip:1002@pbx.local", "Hello");
        assert!(result.is_err());
    }

    #[test]
    fn send_message_sends_via_transport() {
        let tr = Arc::new(MockTransport::new());
        tr.respond_with(200, "OK"); // REGISTER
        tr.respond_with(200, "OK"); // MESSAGE

        let phone = Phone::new(test_cfg());
        phone.connect_with_transport(Arc::clone(&tr) as Arc<dyn SipTransport>);

        phone.send_message("sip:1002@pbx.local", "Hello!").unwrap();
        assert_eq!(tr.count_sent("MESSAGE"), 1);

        phone.disconnect().unwrap();
    }

    #[test]
    fn on_message_fires_on_incoming() {
        let tr = Arc::new(MockTransport::new());
        tr.respond_with(200, "OK"); // REGISTER

        let phone = Phone::new(test_cfg());
        let received = Arc::new(Mutex::new(None));
        let received_clone = Arc::clone(&received);
        phone.on_message(move |msg| {
            *received_clone.lock() = Some(msg);
        });
        phone.connect_with_transport(Arc::clone(&tr) as Arc<dyn SipTransport>);

        tr.simulate_message("sip:1001@pbx.local", "text/plain", "Hi there");
        // spawn_callback is async — give it a moment.
        std::thread::sleep(Duration::from_millis(100));

        let msg = received.lock().clone().unwrap();
        assert_eq!(msg.from, "sip:1001@pbx.local");
        assert_eq!(msg.body, "Hi there");
        assert_eq!(msg.content_type, "text/plain");

        phone.disconnect().unwrap();
    }

    #[test]
    fn watch_before_connect_errors() {
        let phone = Phone::new(test_cfg());
        let result = phone.watch("1001", |_, _| {});
        assert!(result.is_err());
    }

    #[test]
    fn watch_fires_callback_on_notify() {
        let tr = Arc::new(MockTransport::new());
        tr.respond_with(200, "OK"); // REGISTER
        tr.respond_with(200, "OK"); // SUBSCRIBE

        let phone = Phone::new(test_cfg());
        phone.connect_with_transport(Arc::clone(&tr) as Arc<dyn SipTransport>);

        let (tx, rx) = crossbeam_channel::bounded(1);
        phone
            .watch("1002", move |status, prev| {
                let _ = tx.send((status, prev));
            })
            .unwrap();

        // Simulate a dialog-info NOTIFY with confirmed state.
        std::thread::sleep(Duration::from_millis(300));
        tr.simulate_subscription_notify(
            "dialog",
            "application/dialog-info+xml",
            r#"<?xml version="1.0"?>
<dialog-info xmlns="urn:ietf:params:xml:ns:dialog-info"
             version="1" state="full" entity="sip:1002@test">
  <dialog id="d1"><state>confirmed</state></dialog>
</dialog-info>"#,
            "active;expires=600",
            "sip:1002@test",
        );

        let (status, prev) = rx.recv_timeout(Duration::from_secs(2)).unwrap();
        assert_eq!(status.extension, "1002");
        assert_eq!(status.state, ExtensionState::OnThePhone);
        assert!(prev.is_none() || prev == Some(ExtensionState::Unknown));

        phone.disconnect().unwrap();
    }

    #[test]
    fn watch_duplicate_suppression() {
        let tr = Arc::new(MockTransport::new());
        tr.respond_with(200, "OK"); // REGISTER
        tr.respond_with(200, "OK"); // SUBSCRIBE

        let phone = Phone::new(test_cfg());
        phone.connect_with_transport(Arc::clone(&tr) as Arc<dyn SipTransport>);

        let (tx, rx) = crossbeam_channel::bounded(10);
        phone
            .watch("1002", move |status, _| {
                let _ = tx.send(status.state);
            })
            .unwrap();
        std::thread::sleep(Duration::from_millis(300));

        let confirmed_xml = r#"<?xml version="1.0"?>
<dialog-info xmlns="urn:ietf:params:xml:ns:dialog-info"
             version="1" state="full" entity="sip:1002@test">
  <dialog id="d1"><state>confirmed</state></dialog>
</dialog-info>"#;

        // Send same state twice.
        tr.simulate_subscription_notify(
            "dialog",
            "application/dialog-info+xml",
            confirmed_xml,
            "active;expires=600",
            "sip:1002@test",
        );
        std::thread::sleep(Duration::from_millis(100));
        tr.simulate_subscription_notify(
            "dialog",
            "application/dialog-info+xml",
            confirmed_xml,
            "active;expires=600",
            "sip:1002@test",
        );
        std::thread::sleep(Duration::from_millis(100));

        // Should only get one callback (duplicate suppressed).
        let _first = rx.recv_timeout(Duration::from_secs(1)).unwrap();
        let second = rx.recv_timeout(Duration::from_millis(500));
        assert!(second.is_err(), "duplicate should be suppressed");

        phone.disconnect().unwrap();
    }

    #[test]
    fn unwatch_removes_subscription() {
        let tr = Arc::new(MockTransport::new());
        tr.respond_with(200, "OK"); // REGISTER
        tr.respond_with(200, "OK"); // SUBSCRIBE
        tr.respond_with(200, "OK"); // unsubscribe

        let phone = Phone::new(test_cfg());
        phone.connect_with_transport(Arc::clone(&tr) as Arc<dyn SipTransport>);
        phone.watch("1002", |_, _| {}).unwrap();
        std::thread::sleep(Duration::from_millis(300));

        phone.unwatch("1002").unwrap();
        std::thread::sleep(Duration::from_millis(200));

        // Should have sent at least 2 SUBSCRIBEs (initial + unsubscribe).
        assert!(tr.count_sent("SUBSCRIBE") >= 2);

        phone.disconnect().unwrap();
    }

    #[test]
    fn subscribe_event_returns_id() {
        let tr = Arc::new(MockTransport::new());
        tr.respond_with(200, "OK"); // REGISTER
        tr.respond_with(200, "OK"); // SUBSCRIBE

        let phone = Phone::new(test_cfg());
        phone.connect_with_transport(Arc::clone(&tr) as Arc<dyn SipTransport>);

        let id = phone
            .subscribe_event(
                "sip:1002@test",
                "dialog",
                "application/dialog-info+xml",
                |_| {},
            )
            .unwrap();
        assert!(id > 0);
        std::thread::sleep(Duration::from_millis(200));

        phone.unsubscribe_event(id).unwrap();

        phone.disconnect().unwrap();
    }

    // --- Video ---

    #[test]
    fn dial_with_video_builds_video_sdp() {
        let tr = Arc::new(MockTransport::new());
        tr.respond_with(200, "OK"); // REGISTER

        let phone = Phone::new(test_cfg());
        phone.connect_with_transport(Arc::clone(&tr) as Arc<dyn SipTransport>);

        tr.respond_with(200, "OK"); // INVITE
        let opts = DialOptions {
            video: true,
            ..DialOptions::default()
        };
        let call = phone.dial("sip:1002@pbx.local", opts).unwrap();
        assert_eq!(call.state(), crate::types::CallState::Active);

        // The local SDP should contain a video m= line.
        let sdp = call.local_sdp();
        assert!(sdp.contains("m=video"), "SDP should contain video m= line");
        assert!(
            sdp.contains("m=audio"),
            "SDP should still contain audio m= line"
        );
    }

    #[test]
    fn dial_without_video_no_video_sdp() {
        let tr = Arc::new(MockTransport::new());
        tr.respond_with(200, "OK"); // REGISTER

        let phone = Phone::new(test_cfg());
        phone.connect_with_transport(Arc::clone(&tr) as Arc<dyn SipTransport>);

        tr.respond_with(200, "OK"); // INVITE
        let call = phone
            .dial("sip:1002@pbx.local", DialOptions::default())
            .unwrap();
        let sdp = call.local_sdp();
        assert!(
            !sdp.contains("m=video"),
            "SDP should not contain video m= line"
        );
    }
}