active-call 0.3.91

A SIP/WebRTC voice agent
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
use crate::media::{ambiance::AmbianceOption, recorder::RecorderFormat};
use crate::useragent::RegisterOption;
use anyhow::{Error, Result};
use clap::Parser;
use rsipstack::dialog::invitation::InviteOption;
use rsipstack::rsip::uri::{Auth, HostWithPort, Uri};
use rustrtc::IceServer;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;

#[derive(Parser, Debug)]
#[command(version)]
pub struct Cli {
    /// Path to configuration file
    #[clap(long)]
    pub conf: Option<String>,
    /// HTTP listening address
    #[clap(long)]
    pub http: Option<String>,

    /// SIP listening port
    #[clap(long)]
    pub sip: Option<String>,

    /// SIP invitation handler: URL for webhook (http://...) or playbook file (.md)
    #[clap(long)]
    pub handler: Option<String>,

    /// Call a SIP address immediately and use the handler for the call
    #[clap(long)]
    pub call: Option<String>,

    /// External IP address for SIP/RTP
    #[clap(long)]
    pub external_ip: Option<String>,

    /// Supported codecs (e.g., pcmu,pcma,g722,g729,opus)
    #[clap(long, value_delimiter = ',')]
    pub codecs: Option<Vec<String>>,

    /// Download models (sensevoice, supertonic, or all)
    #[cfg(feature = "offline")]
    #[clap(long)]
    pub download_models: Option<String>,

    /// Models directory for offline inference
    #[cfg(feature = "offline")]
    #[clap(long, default_value = "./models")]
    pub models_dir: String,

    /// Exit after downloading models
    #[cfg(feature = "offline")]
    #[clap(long)]
    pub exit_after_download: bool,
}

pub(crate) fn default_config_recorder_path() -> String {
    #[cfg(target_os = "windows")]
    return "./config/recorders".to_string();
    #[cfg(not(target_os = "windows"))]
    return "./config/recorders".to_string();
}

fn default_config_media_cache_path() -> String {
    #[cfg(target_os = "windows")]
    return "./config/mediacache".to_string();
    #[cfg(not(target_os = "windows"))]
    return "./config/mediacache".to_string();
}

fn default_config_http_addr() -> String {
    "0.0.0.0:8080".to_string()
}

fn default_sip_addr() -> String {
    "0.0.0.0".to_string()
}

fn default_sip_port() -> u16 {
    25060
}

fn default_config_rtp_start_port() -> Option<u16> {
    Some(12000)
}

fn default_config_rtp_end_port() -> Option<u16> {
    Some(42000)
}

fn default_config_rtp_latching() -> Option<bool> {
    Some(true)
}

fn default_graceful_shutdown() -> Option<bool> {
    Some(true)
}

fn default_graceful_shutdown_timeout() -> Option<u64> {
    Some(30)
}

fn default_config_useragent() -> Option<String> {
    Some(format!(
        "active-call({} miuda.ai)",
        env!("CARGO_PKG_VERSION")
    ))
}

fn default_enable_options_response() -> Option<bool> {
    Some(true)
}

fn default_options_allow_registered_servers() -> Option<bool> {
    Some(true)
}

fn default_options_auto_learn() -> Option<bool> {
    Some(true)
}

fn default_options_learn_ttl() -> Option<String> {
    Some("7d".to_string())
}

fn default_codecs() -> Option<Vec<String>> {
    let codecs = vec![
        "pcmu".to_string(),
        "pcma".to_string(),
        "g722".to_string(),
        "g729".to_string(),
        "opus".to_string(),
        "telephone_event".to_string(),
    ];
    Some(codecs)
}

#[derive(Debug, Clone, Deserialize, Serialize, Default)]
#[serde(rename_all = "snake_case")]
pub struct RecordingPolicy {
    #[serde(default)]
    pub enabled: bool,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub auto_start: Option<bool>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub filename_pattern: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub samplerate: Option<u32>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub ptime: Option<u32>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub path: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub format: Option<RecorderFormat>,
    /// Record at the source's native sample rate instead of resampling to
    /// 16 kHz. The actual rate is detected from the caller leg's codec.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub native_samplerate: Option<bool>,
}

impl RecordingPolicy {
    pub fn recorder_path(&self) -> String {
        self.path
            .as_ref()
            .map(|p| p.trim())
            .filter(|p| !p.is_empty())
            .map(|p| p.to_string())
            .unwrap_or_else(default_config_recorder_path)
    }

    pub fn recorder_format(&self) -> RecorderFormat {
        self.format.unwrap_or_default()
    }

    pub fn ensure_defaults(&mut self) -> bool {
        if self
            .path
            .as_ref()
            .map(|p| p.trim().is_empty())
            .unwrap_or(true)
        {
            self.path = Some(default_config_recorder_path());
        }

        false
    }
}

#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct RewriteRule {
    pub r#match: String,
    pub rewrite: String,
}

/// Trunk-like SIP INVITE/REFER rewriting rule.
///
/// Rules are evaluated in declaration order and the first rule whose `match`
/// conditions all hold (AND) is applied via its `rewrite` actions
/// (first-match-wins). A rule with an empty `match` section always matches and
/// therefore acts as a catch-all default.
///
/// ```toml
/// [[trunk_rules]]
/// rule.match.to.host = "^172\\.25\\."
/// rule.rewrite.contact.host = "172.25.225.2"
/// ```
#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)]
#[serde(rename_all = "snake_case")]
pub struct TrunkRule {
    pub rule: TrunkRuleDef,
}

#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)]
#[serde(rename_all = "snake_case")]
pub struct TrunkRuleDef {
    #[serde(default, rename = "match")]
    pub r#match: TrunkMatch,
    pub rewrite: TrunkRewrite,
}

/// Match conditions for a trunk rule. All non-None fields must match (AND).
/// `from` matches the SIP From header (caller), `to` matches the SIP To header
/// and Request-URI (callee) of the outgoing INVITE/REFER.
#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, Default)]
#[serde(rename_all = "snake_case")]
pub struct TrunkMatch {
    pub from: Option<UriMatch>,
    pub to: Option<UriMatch>,
}

/// Matches a URI against optional regex patterns on its user and host parts.
/// `user` matches the username before `@`; `host` matches the host after `@`.
#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, Default)]
#[serde(rename_all = "snake_case")]
pub struct UriMatch {
    /// Regex matched against the SIP URI user part (before `@`).
    pub user: Option<String>,
    /// Regex matched against the SIP URI host part (after `@`).
    pub host: Option<String>,
}

/// Rewrite actions applied once a rule matches. All non-None fields are applied.
#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, Default)]
#[serde(rename_all = "snake_case")]
pub struct TrunkRewrite {
    pub from: Option<UriRewrite>,
    pub to: Option<UriRewrite>,
    pub contact: Option<UriRewrite>,
}

/// Rewrites the user and/or host of a SIP URI. When a `host` value carries no
/// port (e.g. `"172.25.225.2"`), the original URI port is preserved; include a
/// port (e.g. `"172.25.225.2:15060"`) to also change it.
#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, Default)]
#[serde(rename_all = "snake_case")]
pub struct UriRewrite {
    pub user: Option<String>,
    pub host: Option<String>,
}

impl TrunkRule {
    fn matches(&self, invite: &InviteOption) -> bool {
        self.rule.r#match.matches(invite)
    }

    fn apply(&self, invite: &mut InviteOption) {
        self.rule.rewrite.apply(invite);
    }
}

impl TrunkMatch {
    fn matches(&self, invite: &InviteOption) -> bool {
        let from_ok = self
            .from
            .as_ref()
            .map(|from| from.matches(&invite.caller))
            .unwrap_or(true);
        let to_ok = self
            .to
            .as_ref()
            .map(|to| to.matches(&invite.callee))
            .unwrap_or(true);
        from_ok && to_ok
    }
}

impl UriMatch {
    fn matches(&self, uri: &Uri) -> bool {
        let user_ok = self
            .user
            .as_ref()
            .map(|user| {
                uri.auth
                    .as_ref()
                    .map(|auth| regex_is_match(user, &auth.user))
                    .unwrap_or(false)
            })
            .unwrap_or(true);
        let host_ok = self
            .host
            .as_ref()
            .map(|host| regex_is_match(host, &uri.host_with_port.host.to_string()))
            .unwrap_or(true);
        user_ok && host_ok
    }
}

impl TrunkRewrite {
    fn apply(&self, invite: &mut InviteOption) {
        if let Some(from) = &self.from {
            from.apply(&mut invite.caller);
        }
        if let Some(to) = &self.to {
            to.apply(&mut invite.callee);
        }
        if let Some(contact) = &self.contact {
            contact.apply(&mut invite.contact);
        }
    }
}

impl UriRewrite {
    fn apply(&self, uri: &mut Uri) {
        if let Some(user) = &self.user {
            let auth = uri.auth.get_or_insert_with(|| Auth {
                user: String::new(),
                password: None,
            });
            auth.user = user.clone();
        }
        if let Some(host) = &self.host
            && let Ok(mut host_with_port) = HostWithPort::try_from(host.as_str())
        {
            // Preserve the original port when the rewrite value omits one.
            if host_with_port.port.is_none() {
                host_with_port.port = uri.host_with_port.port;
            }
            uri.host_with_port = host_with_port;
        }
    }
}

fn regex_is_match(pattern: &str, value: &str) -> bool {
    regex::Regex::new(pattern)
        .map(|re| re.is_match(value))
        .unwrap_or(false)
}

/// Extracts the host part of a `register_users[].server` value, which may be
/// `host`, `host:port`, or `[ipv6]:port`.
fn host_of_server(server: &str) -> Option<String> {
    let server = server.trim();
    if server.is_empty() {
        return None;
    }
    if let Some(rest) = server.strip_prefix('[') {
        // [ipv6]:port or [ipv6]
        return rest
            .split(']')
            .next()
            .map(|h| h.to_ascii_lowercase());
    }
    // A bare ipv6 literal without brackets contains multiple colons; keep it whole.
    if server.matches(':').count() > 1 {
        return Some(server.to_ascii_lowercase());
    }
    server.split(':').next().map(|h| h.to_ascii_lowercase())
}

/// One parsed `[options_response].allow` entry: an exact IP, a CIDR block, or
/// a hostname.
#[derive(Debug, Clone, PartialEq)]
pub enum OptionsAclEntry {
    Ip(std::net::IpAddr),
    Cidr(ipnet::IpNet),
    Host(String),
}

impl OptionsAclEntry {
    fn parse(raw: &str) -> Option<Self> {
        let raw = raw.trim();
        if raw.is_empty() {
            return None;
        }
        if let Ok(ip) = raw.parse::<std::net::IpAddr>() {
            return Some(Self::Ip(ip));
        }
        if let Ok(cidr) = raw.parse::<ipnet::IpNet>() {
            return Some(Self::Cidr(cidr));
        }
        Some(Self::Host(raw.to_ascii_lowercase()))
    }

    pub fn matches(&self, source_ip: Option<std::net::IpAddr>, source_host: &str) -> bool {
        match self {
            Self::Ip(ip) => source_ip == Some(*ip),
            Self::Cidr(net) => source_ip.map(|ip| net.contains(&ip)).unwrap_or(false),
            Self::Host(host) => host.eq_ignore_ascii_case(source_host),
        }
    }
}

/// `[options_response]` — customizes the 200 OK answers to out-of-dialog
/// OPTIONS keep-alive probes and restricts which sources are answered.
///
/// A probe is answered only when its source (top Via header) matches the
/// static `allow` ACL, a `register_users[].server` host, or a peer address
/// learned from call traffic (`auto_learn`). Everything else is dropped
/// silently.
#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, Default)]
#[serde(rename_all = "snake_case")]
pub struct OptionsResponseConfig {
    /// Answer out-of-dialog OPTIONS probes; falls back to the legacy
    /// `enable_options_response` field, defaulting to `true`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub enabled: Option<bool>,
    /// Static ACL entries: exact IP (`139.224.72.64`), CIDR (`10.0.0.0/8`),
    /// or hostname (`sip.ccc.aliyuncs.com`).
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub allow: Vec<String>,
    /// Also answer probes coming from the hosts of `register_users[].server`.
    #[serde(default = "default_options_allow_registered_servers")]
    pub allow_registered_servers: Option<bool>,
    /// Learn peer addresses from call traffic — inbound INVITEs and responses
    /// to our outbound INVITEs — and answer probes from those sources within
    /// `learn_ttl` (strict mode: until the first peer is learned, only the
    /// static ACL and registered hosts apply).
    #[serde(default = "default_options_auto_learn")]
    pub auto_learn: Option<bool>,
    /// How long a learned peer address stays valid, e.g. `"7d"` (default).
    #[serde(default = "default_options_learn_ttl")]
    pub learn_ttl: Option<String>,
    /// Extra headers appended to the OPTIONS 200 OK response.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub extra_headers: Vec<(String, String)>,
}

#[derive(Debug, Deserialize, Serialize)]
pub struct Config {
    #[serde(default = "default_config_http_addr")]
    pub http_addr: String,
    pub addr: String,
    pub udp_port: u16,
    pub auto_learn_public_address: Option<bool>,

    pub log_level: Option<String>,
    pub log_file: Option<String>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub http_access_skip_paths: Vec<String>,

    /// Peer active-call nodes ("ip:port" of their HTTP/WS endpoint).
    ///
    /// When a websocket client connects with a session id that is not hosted on
    /// this node, the originator (empty `forward`) polls each peer once
    /// (`forward=true`) and tunnels the websocket to the peer that hosts the
    /// call. Any request whose `forward` is set must not hop further.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub peers: Vec<String>,

    #[serde(default = "default_config_useragent")]
    pub useragent: Option<String>,
    pub register_users: Option<Vec<RegisterOption>>,
    #[serde(default = "default_graceful_shutdown")]
    pub graceful_shutdown: Option<bool>,
    /// Total seconds to wait during graceful shutdown before forcing exit.
    /// SIP de-registration and active call draining run in parallel, both with this timeout.
    #[serde(default = "default_graceful_shutdown_timeout")]
    pub graceful_shutdown_timeout: Option<u64>,
    pub handler: Option<InviteHandlerConfig>,
    pub accept_timeout: Option<String>,
    #[serde(default = "default_codecs")]
    pub codecs: Option<Vec<String>>,
    pub external_ip: Option<String>,
    #[serde(default = "default_config_rtp_start_port")]
    pub rtp_start_port: Option<u16>,
    #[serde(default = "default_config_rtp_end_port")]
    pub rtp_end_port: Option<u16>,
    #[serde(default = "default_config_rtp_latching")]
    pub enable_rtp_latching: Option<bool>,
    pub enable_ice_lite: Option<bool>,
    pub rtp_bind_ip: Option<String>,
    pub tls_port: Option<u16>,
    pub tls_cert_file: Option<String>,
    pub tls_key_file: Option<String>,

    pub enable_srtp: Option<bool>,

    pub callrecord: Option<CallRecordConfig>,
    #[serde(default = "default_config_media_cache_path")]
    pub media_cache_path: String,
    pub ambiance: Option<AmbianceOption>,
    pub ice_servers: Option<Vec<IceServer>>,
    #[serde(default)]
    pub recording: Option<RecordingPolicy>,
    pub rewrites: Option<Vec<RewriteRule>>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub trunk_rules: Option<Vec<TrunkRule>>,
    #[serde(default = "default_enable_options_response")]
    pub enable_options_response: Option<bool>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub options_response: Option<OptionsResponseConfig>,
}

#[derive(Debug, Deserialize, Clone, Serialize)]
#[serde(rename_all = "snake_case")]
#[serde(tag = "type")]
pub enum InviteHandlerConfig {
    Webhook {
        url: Option<String>,
        urls: Option<Vec<String>>,
        method: Option<String>,
        headers: Option<Vec<(String, String)>>,
    },
    Playbook {
        rules: Option<Vec<PlaybookRule>>,
        default: Option<String>,
    },
}

#[derive(Debug, Deserialize, Clone, Serialize)]
#[serde(rename_all = "snake_case")]
pub struct PlaybookRule {
    pub caller: Option<String>,
    pub callee: Option<String>,
    pub playbook: String,
}

#[derive(Debug, Deserialize, Clone, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum S3Vendor {
    Aliyun,
    Tencent,
    Minio,
    AWS,
    GCP,
    Azure,
    DigitalOcean,
}

#[derive(Debug, Deserialize, Clone, Serialize)]
#[serde(tag = "type")]
#[serde(rename_all = "snake_case")]
pub enum CallRecordConfig {
    Local {
        root: String,
    },
    S3 {
        vendor: S3Vendor,
        bucket: String,
        region: String,
        access_key: String,
        secret_key: String,
        endpoint: String,
        root: String,
        with_media: Option<bool>,
        keep_media_copy: Option<bool>,
    },
    Http {
        url: String,
        headers: Option<HashMap<String, String>>,
        with_media: Option<bool>,
        keep_media_copy: Option<bool>,
    },
}

impl Default for CallRecordConfig {
    fn default() -> Self {
        Self::Local {
            #[cfg(target_os = "windows")]
            root: "./config/cdr".to_string(),
            #[cfg(not(target_os = "windows"))]
            root: "./config/cdr".to_string(),
        }
    }
}

impl Default for Config {
    fn default() -> Self {
        Self {
            http_addr: default_config_http_addr(),
            log_level: None,
            log_file: None,
            http_access_skip_paths: Vec::new(),
            peers: Vec::new(),
            addr: default_sip_addr(),
            udp_port: default_sip_port(),
            auto_learn_public_address: None,
            useragent: None,
            register_users: None,
            graceful_shutdown: Some(true),
            graceful_shutdown_timeout: default_graceful_shutdown_timeout(),
            handler: None,
            accept_timeout: Some("50s".to_string()),
            media_cache_path: default_config_media_cache_path(),
            ambiance: None,
            callrecord: None,
            ice_servers: None,
            codecs: None,
            external_ip: None,
            rtp_start_port: default_config_rtp_start_port(),
            rtp_end_port: default_config_rtp_end_port(),
            enable_rtp_latching: Some(true),
            rtp_bind_ip: None,
            enable_ice_lite: None,
            tls_port: None,
            tls_cert_file: None,
            tls_key_file: None,
            enable_srtp: None,
            recording: None,
            rewrites: None,
            trunk_rules: None,
            enable_options_response: default_enable_options_response(),
            options_response: None,
        }
    }
}

impl Clone for Config {
    fn clone(&self) -> Self {
        // This is a bit expensive but Config is not cloned often in hot paths
        // and implementing Clone manually for all nested structs is tedious
        let s = toml::to_string(self).unwrap();
        toml::from_str(&s).unwrap()
    }
}

impl Config {
    pub fn load(path: &str) -> Result<Self, Error> {
        let config: Self = toml::from_str(
            &std::fs::read_to_string(path).map_err(|e| anyhow::anyhow!("{}: {}", e, path))?,
        )?;
        Ok(config)
    }

    /// Whether out-of-dialog OPTIONS probes should be answered at all.
    pub fn options_response_enabled(&self) -> bool {
        self.options_response
            .as_ref()
            .and_then(|o| o.enabled)
            .or(self.enable_options_response)
            .unwrap_or(true)
    }

    /// Whether peer addresses should be learned from call traffic.
    pub fn options_auto_learn(&self) -> bool {
        self.options_response
            .as_ref()
            .and_then(|o| o.auto_learn)
            .unwrap_or(true)
    }

    /// TTL for learned peer addresses; unparsable/missing values default to 7 days.
    pub fn options_learn_ttl(&self) -> std::time::Duration {
        const DEFAULT: std::time::Duration = std::time::Duration::from_secs(7 * 24 * 3600);
        self.options_response
            .as_ref()
            .and_then(|o| o.learn_ttl.as_deref())
            .map(|raw| {
                humantime::parse_duration(raw).unwrap_or(DEFAULT)
            })
            .unwrap_or(DEFAULT)
    }

    /// Parsed static ACL entries for OPTIONS probing.
    pub fn options_acl_entries(&self) -> Vec<OptionsAclEntry> {
        self.options_response
            .as_ref()
            .map(|o| o.allow.iter().filter_map(|raw| OptionsAclEntry::parse(raw)).collect())
            .unwrap_or_default()
    }

    /// Hosts of `register_users[].server` when `allow_registered_servers` is
    /// on (the default); empty otherwise.
    pub fn options_registered_hosts(&self) -> Vec<String> {
        let enabled = self
            .options_response
            .as_ref()
            .and_then(|o| o.allow_registered_servers)
            .unwrap_or(true);
        if !enabled {
            return vec![];
        }
        self.register_users
            .as_ref()
            .map(|users| {
                users
                    .iter()
                    .filter_map(|user| host_of_server(&user.server))
                    .collect()
            })
            .unwrap_or_default()
    }

    /// Extra headers appended to OPTIONS 200 OK responses.
    pub fn options_extra_headers(&self) -> Vec<(String, String)> {
        self.options_response
            .as_ref()
            .map(|o| o.extra_headers.clone())
            .unwrap_or_default()
    }

    /// Whether `source_ip`/`source_host` matches the static ACL or the
    /// registered-server hosts (the configured, non-learned allow sets).
    pub fn options_matches_static(&self, source_ip: Option<std::net::IpAddr>, source_host: &str) -> bool {
        self.options_acl_entries()
            .iter()
            .any(|entry| entry.matches(source_ip, source_host))
            || self
                .options_registered_hosts()
                .iter()
                .any(|host| host.eq_ignore_ascii_case(source_host))
    }

    pub fn recorder_path(&self) -> String {
        self.recording
            .as_ref()
            .map(|policy| policy.recorder_path())
            .unwrap_or_else(default_config_recorder_path)
    }

    pub fn recorder_format(&self) -> RecorderFormat {
        self.recording
            .as_ref()
            .map(|policy| policy.recorder_format())
            .unwrap_or_default()
    }

    pub fn recorder_native_samplerate(&self) -> bool {
        self.recording
            .as_ref()
            .and_then(|policy| policy.native_samplerate)
            .unwrap_or(false)
    }

    pub fn ensure_recording_defaults(&mut self) -> bool {
        let mut fallback = false;

        if let Some(policy) = self.recording.as_mut() {
            fallback |= policy.ensure_defaults();
        }

        fallback
    }

    /// Apply the first matching trunk rule to an outgoing SIP INVITE/REFER.
    ///
    /// Rules are evaluated in declaration order; the first rule whose `match`
    /// conditions (all AND) hold is applied and later rules are skipped
    /// (first-match-wins). A rule with an empty `match` section always matches
    /// and acts as a catch-all default. If no rule matches, the invite is left
    /// untouched. Does nothing when [`Config::trunk_rules`] is not configured.
    pub fn apply_trunk_rules(&self, invite: &mut InviteOption) {
        if let Some(rules) = &self.trunk_rules {
            for rule in rules {
                if rule.matches(invite) {
                    rule.apply(invite);
                    break;
                }
            }
        }
    }

    /// Normalize a configured peer to a `ws://` (or `wss://`) base URL.
    ///
    /// Accepts bare `ip:port`, or an explicit `ws://`, `wss://`, `http://` or
    /// `https://` scheme. Returns `None` when the value is empty or unusable.
    pub fn peer_ws_endpoint(peer: &str) -> Option<String> {
        let peer = peer.trim();
        if peer.is_empty() {
            return None;
        }
        if peer.starts_with("wss://") {
            return Some(peer.to_string());
        }
        if peer.starts_with("ws://") {
            return Some(peer.to_string());
        }
        if peer.starts_with("https://") {
            return Some(peer.replacen("https://", "wss://", 1));
        }
        if peer.starts_with("http://") {
            return Some(peer.replacen("http://", "ws://", 1));
        }
        Some(format!("ws://{}", peer))
    }
}

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

    #[test]
    fn test_playbook_handler_config_parsing() {
        let toml_config = r#"
http_addr = "0.0.0.0:8080"
addr = "0.0.0.0"
udp_port = 25060

[handler]
type = "playbook"
default = "default.md"

[[handler.rules]]
caller = "^\\+1\\d{10}$"
callee = "^sip:support@.*"
playbook = "support.md"

[[handler.rules]]
caller = "^\\+86\\d+"
playbook = "chinese.md"

[[handler.rules]]
callee = "^sip:sales@.*"
playbook = "sales.md"
"#;

        let config: Config = toml::from_str(toml_config).unwrap();

        assert!(config.handler.is_some());
        if let Some(InviteHandlerConfig::Playbook { rules, default }) = config.handler {
            assert_eq!(default, Some("default.md".to_string()));
            let rules = rules.unwrap();
            assert_eq!(rules.len(), 3);

            assert_eq!(rules[0].caller, Some(r"^\+1\d{10}$".to_string()));
            assert_eq!(rules[0].callee, Some("^sip:support@.*".to_string()));
            assert_eq!(rules[0].playbook, "support.md");

            assert_eq!(rules[1].caller, Some(r"^\+86\d+".to_string()));
            assert_eq!(rules[1].callee, None);
            assert_eq!(rules[1].playbook, "chinese.md");

            assert_eq!(rules[2].caller, None);
            assert_eq!(rules[2].callee, Some("^sip:sales@.*".to_string()));
            assert_eq!(rules[2].playbook, "sales.md");
        } else {
            panic!("Expected Playbook handler config");
        }
    }

    #[test]
    fn test_playbook_handler_config_without_default() {
        let toml_config = r#"
http_addr = "0.0.0.0:8080"
addr = "0.0.0.0"
udp_port = 25060

[handler]
type = "playbook"

[[handler.rules]]
caller = "^\\+1.*"
playbook = "us.md"
"#;

        let config: Config = toml::from_str(toml_config).unwrap();

        if let Some(InviteHandlerConfig::Playbook { rules, default }) = config.handler {
            assert_eq!(default, None);
            let rules = rules.unwrap();
            assert_eq!(rules.len(), 1);
        } else {
            panic!("Expected Playbook handler config");
        }
    }

    #[test]
    fn test_webhook_handler_config_still_works() {
        let toml_config = r#"
http_addr = "0.0.0.0:8080"
addr = "0.0.0.0"
udp_port = 25060

[handler]
type = "webhook"
url = "http://example.com/webhook"
"#;

        let config: Config = toml::from_str(toml_config).unwrap();

        if let Some(InviteHandlerConfig::Webhook { url, .. }) = config.handler {
            assert_eq!(url, Some("http://example.com/webhook".to_string()));
        } else {
            panic!("Expected Webhook handler config");
        }
    }

    // ---------------------------------------------------------------------------
    // options_response: config parsing + accessors
    // ---------------------------------------------------------------------------

    #[test]
    fn test_options_response_defaults() {
        let config: Config = toml::from_str(
            r#"
http_addr = "0.0.0.0:8080"
addr = "0.0.0.0"
udp_port = 25060
"#,
        )
        .unwrap();

        assert!(config.options_response.is_none());
        // Section absent: enabled via the legacy field/default, auto-learn on,
        // 7d TTL, no static entries, no extra headers.
        assert!(config.options_response_enabled());
        assert!(config.options_auto_learn());
        assert_eq!(
            config.options_learn_ttl(),
            std::time::Duration::from_secs(7 * 24 * 3600)
        );
        assert!(config.options_acl_entries().is_empty());
        assert!(config.options_registered_hosts().is_empty());
        assert!(config.options_extra_headers().is_empty());
    }

    #[test]
    fn test_options_response_config_parsing() {
        let toml_config = r#"
http_addr = "0.0.0.0:8080"
addr = "0.0.0.0"
udp_port = 25060

[options_response]
enabled = true
allow = ["139.224.72.64", "10.0.0.0/8", "SIP.CCC.AliyunCS.com"]
allow_registered_servers = false
auto_learn = false
learn_ttl = "1h"
extra_headers = [["X-Node-Id", "node-1"], ["User-Agent", "ActiveCall-Test"]]
"#;

        let config: Config = toml::from_str(toml_config).unwrap();
        let options = config.options_response.as_ref().unwrap();
        assert_eq!(options.enabled, Some(true));
        assert_eq!(options.allow_registered_servers, Some(false));
        assert_eq!(options.auto_learn, Some(false));

        assert!(!config.options_auto_learn());
        assert_eq!(
            config.options_learn_ttl(),
            std::time::Duration::from_secs(3600)
        );

        let entries = config.options_acl_entries();
        assert_eq!(entries.len(), 3);
        assert_eq!(
            entries[0],
            OptionsAclEntry::Ip("139.224.72.64".parse().unwrap())
        );
        assert!(matches!(entries[1], OptionsAclEntry::Cidr(_)));
        assert_eq!(
            entries[2],
            OptionsAclEntry::Host("sip.ccc.aliyuncs.com".to_string())
        );

        let headers = config.options_extra_headers();
        assert_eq!(headers.len(), 2);
        assert_eq!(headers[0], ("X-Node-Id".to_string(), "node-1".to_string()));
    }

    #[test]
    fn test_options_response_enabled_fallback_chain() {
        // Legacy field only.
        let config: Config = toml::from_str(
            r#"
addr = "0.0.0.0"
udp_port = 25060
enable_options_response = false
"#,
        )
        .unwrap();
        assert!(!config.options_response_enabled());

        // New section wins over the legacy field.
        let config: Config = toml::from_str(
            r#"
addr = "0.0.0.0"
udp_port = 25060
enable_options_response = false

[options_response]
enabled = true
"#,
        )
        .unwrap();
        assert!(config.options_response_enabled());

        // New section with enabled unset falls back to the legacy field.
        let config: Config = toml::from_str(
            r#"
addr = "0.0.0.0"
udp_port = 25060
enable_options_response = false

[options_response]
extra_headers = [["X-A", "1"]]
"#,
        )
        .unwrap();
        assert!(!config.options_response_enabled());
    }

    #[test]
    fn test_options_acl_matching() {
        let toml_config = r#"
addr = "0.0.0.0"
udp_port = 25060

[options_response]
allow = ["139.224.72.64", "10.0.0.0/8", "sip.ccc.aliyuncs.com"]
"#;
        let config: Config = toml::from_str(toml_config).unwrap();
        let ip = |s: &str| Some(s.parse::<std::net::IpAddr>().unwrap());

        // Exact IP.
        assert!(config.options_matches_static(ip("139.224.72.64"), "139.224.72.64"));
        assert!(!config.options_matches_static(ip("139.224.72.65"), "139.224.72.65"));
        // CIDR.
        assert!(config.options_matches_static(ip("10.1.2.3"), "10.1.2.3"));
        assert!(!config.options_matches_static(ip("192.168.1.1"), "192.168.1.1"));
        // Hostname, case-insensitive.
        assert!(config
            .options_matches_static(None, "SIP.CCC.ALIYUNCS.COM"));
        assert!(!config.options_matches_static(None, "sip.example.com"));
        // An IP source does not match the hostname entry and vice versa.
        assert!(!config.options_matches_static(None, "139.224.72.64"));
    }

    #[test]
    fn test_options_registered_hosts() {
        let toml_config = r#"
addr = "0.0.0.0"
udp_port = 25060

[[register_users]]
server = "sip.example.com:5060"
username = "1001"

[[register_users]]
server = "10.0.0.5"
username = "1002"
"#;
        let config: Config = toml::from_str(toml_config).unwrap();
        // Default: registered servers are allowed.
        assert_eq!(
            config.options_registered_hosts(),
            vec![
                "sip.example.com".to_string(),
                "10.0.0.5".to_string()
            ]
        );
        assert!(config.options_matches_static(None, "SIP.EXAMPLE.COM"));
        assert!(config.options_matches_static(
            Some("10.0.0.5".parse().unwrap()),
            "10.0.0.5"
        ));

        // Opt out via allow_registered_servers = false.
        let toml_config_off = r#"
addr = "0.0.0.0"
udp_port = 25060

[[register_users]]
server = "sip.example.com"
username = "1001"

[options_response]
allow_registered_servers = false
"#;
        let config: Config = toml::from_str(toml_config_off).unwrap();
        assert!(config.options_registered_hosts().is_empty());
        assert!(!config.options_matches_static(None, "sip.example.com"));
    }

    #[test]
    fn test_host_of_server() {
        assert_eq!(
            host_of_server("sip.example.com:5060"),
            Some("sip.example.com".to_string())
        );
        assert_eq!(
            host_of_server("SIP.Example.COM"),
            Some("sip.example.com".to_string())
        );
        assert_eq!(
            host_of_server("[2001:db8::1]:5060"),
            Some("2001:db8::1".to_string())
        );
        assert_eq!(
            host_of_server("2001:db8::1"),
            Some("2001:db8::1".to_string())
        );
        assert_eq!(host_of_server(""), None);
    }

    // ---------------------------------------------------------------------------
    // trunk_rules: config parsing
    // ---------------------------------------------------------------------------

    #[test]
    fn test_trunk_rules_config_parsing() {
        let toml_config = r#"
http_addr = "0.0.0.0:8080"
addr = "0.0.0.0"
udp_port = 25060

[[trunk_rules]]
rule.match.to.host = "^172\\.25\\."
rule.rewrite.contact.host = "172.25.225.2"

[[trunk_rules]]
rule.match.from.user = "^\\+86.*"
rule.match.to.host = "^10\\."
rule.rewrite.from.user = "10086"
rule.rewrite.to.host = "10.0.0.1"
rule.rewrite.contact.user = "active-call"
rule.rewrite.contact.host = "10.0.0.1:25060"

[[trunk_rules]]
rule.rewrite.contact.host = "116.62.75.161"
"#;

        let config: Config = toml::from_str(toml_config).unwrap();
        let rules = config.trunk_rules.expect("trunk_rules should be parsed");

        assert_eq!(rules.len(), 3);

        // Rule 1: match to.host, rewrite contact.host
        let m = &rules[0].rule.r#match;
        assert_eq!(m.to.as_ref().unwrap().host.as_deref(), Some("^172\\.25\\."));
        assert_eq!(m.to.as_ref().unwrap().user, None);
        assert_eq!(m.from, None);
        let w = &rules[0].rule.rewrite;
        assert_eq!(
            w.contact.as_ref().unwrap().host.as_deref(),
            Some("172.25.225.2")
        );
        assert_eq!(w.from, None);
        assert_eq!(w.to, None);

        // Rule 2: combined match + all rewrites
        let m = &rules[1].rule.r#match;
        assert_eq!(m.from.as_ref().unwrap().user.as_deref(), Some("^\\+86.*"));
        assert_eq!(m.to.as_ref().unwrap().host.as_deref(), Some("^10\\."));
        let w = &rules[1].rule.rewrite;
        assert_eq!(w.from.as_ref().unwrap().user.as_deref(), Some("10086"));
        assert_eq!(w.to.as_ref().unwrap().host.as_deref(), Some("10.0.0.1"));
        assert_eq!(
            w.contact.as_ref().unwrap().user.as_deref(),
            Some("active-call")
        );
        assert_eq!(
            w.contact.as_ref().unwrap().host.as_deref(),
            Some("10.0.0.1:25060")
        );

        // Rule 3: catch-all (empty match)
        assert_eq!(rules[2].rule.r#match.from, None);
        assert_eq!(rules[2].rule.r#match.to, None);
        assert_eq!(
            rules[2]
                .rule
                .rewrite
                .contact
                .as_ref()
                .unwrap()
                .host
                .as_deref(),
            Some("116.62.75.161")
        );
    }

    #[test]
    fn test_trunk_rules_absent_by_default() {
        let config = Config::default();
        assert!(config.trunk_rules.is_none());
    }

    // ---------------------------------------------------------------------------
    // trunk_rules: match + rewrite behaviour
    // ---------------------------------------------------------------------------

    fn invite_option(caller: &str, callee: &str, contact: &str) -> InviteOption {
        InviteOption {
            caller: caller.try_into().unwrap(),
            callee: callee.try_into().unwrap(),
            contact: contact.try_into().unwrap(),
            ..Default::default()
        }
    }

    #[test]
    fn test_trunk_rule_matches_on_to_host() {
        let config: Config = toml::from_str(
            r#"
addr = "0.0.0.0"
udp_port = 25060

[[trunk_rules]]
rule.match.to.host = "^172\\.25\\."
rule.rewrite.contact.host = "172.25.225.2"
"#,
        )
        .unwrap();

        // Internal target -> matched, contact host rewritten.
        let mut invite = invite_option(
            "sip:ai@116.62.75.161:13050",
            "sip:agent1@172.25.225.3:15060",
            "sip:ai@127.0.0.1:13050",
        );
        config.apply_trunk_rules(&mut invite);
        assert_eq!(
            invite.contact.host_with_port.host.to_string(),
            "172.25.225.2"
        );

        // External target -> no match, contact untouched.
        let mut invite = invite_option(
            "sip:ai@116.62.75.161:13050",
            "sip:+8613800138000@sbc.example.com:5060",
            "sip:ai@127.0.0.1:13050",
        );
        config.apply_trunk_rules(&mut invite);
        assert_eq!(invite.contact.host_with_port.host.to_string(), "127.0.0.1");
    }

    #[test]
    fn test_trunk_rule_matches_on_from_user_and_to_host() {
        let config: Config = toml::from_str(
            r#"
addr = "0.0.0.0"
udp_port = 25060

[[trunk_rules]]
rule.match.from.user = "^anonymous$"
rule.match.to.host = "^sbc\\."
rule.rewrite.contact.host = "116.62.75.161"
"#,
        )
        .unwrap();

        // from.user + to.host both match -> rewritten.
        let mut invite = invite_option(
            "sip:anonymous@116.62.75.161:13050",
            "sip:+8613800138000@sbc.example.com:5060",
            "sip:ai@127.0.0.1:13050",
        );
        config.apply_trunk_rules(&mut invite);
        assert_eq!(
            invite.contact.host_with_port.host.to_string(),
            "116.62.75.161"
        );

        // from.user does not match -> no rewrite.
        let mut invite = invite_option(
            "sip:alice@116.62.75.161:13050",
            "sip:+8613800138000@sbc.example.com:5060",
            "sip:ai@127.0.0.1:13050",
        );
        config.apply_trunk_rules(&mut invite);
        assert_eq!(invite.contact.host_with_port.host.to_string(), "127.0.0.1");
    }

    #[test]
    fn test_trunk_rule_rewrites_from_to_contact() {
        let config: Config = toml::from_str(
            r#"
addr = "0.0.0.0"
udp_port = 25060

[[trunk_rules]]
rule.match.to.host = "^10\\."
rule.rewrite.from.user = "10086"
rule.rewrite.from.host = "116.62.75.161"
rule.rewrite.to.user = "30000"
rule.rewrite.to.host = "10.0.0.1:25060"
rule.rewrite.contact.user = "active-call"
rule.rewrite.contact.host = "10.0.0.1"
"#,
        )
        .unwrap();

        let mut invite = invite_option(
            "sip:ai@127.0.0.1:13050",
            "sip:agent1@10.0.0.2:25060",
            "sip:ai@127.0.0.1:13050",
        );
        config.apply_trunk_rules(&mut invite);

        // caller (from)
        assert_eq!(invite.caller.auth.as_ref().unwrap().user, "10086");
        assert_eq!(
            invite.caller.host_with_port.host.to_string(),
            "116.62.75.161"
        );

        // callee (to)
        assert_eq!(invite.callee.auth.as_ref().unwrap().user, "30000");
        assert_eq!(invite.callee.host_with_port.host.to_string(), "10.0.0.1");
        assert_eq!(invite.callee.host_with_port.port.unwrap().0, 25060);

        // contact: host rewritten without port -> original port preserved
        assert_eq!(invite.contact.auth.as_ref().unwrap().user, "active-call");
        assert_eq!(invite.contact.host_with_port.host.to_string(), "10.0.0.1");
        assert_eq!(invite.contact.host_with_port.port.unwrap().0, 13050);
    }

    #[test]
    fn test_trunk_rule_catch_all_default() {
        let config: Config = toml::from_str(
            r#"
addr = "0.0.0.0"
udp_port = 25060

[[trunk_rules]]
rule.match.to.host = "^172\\.25\\."
rule.rewrite.contact.host = "172.25.225.2"

[[trunk_rules]]
rule.rewrite.contact.host = "116.62.75.161"
"#,
        )
        .unwrap();

        // Not matched by rule 1 -> falls through to catch-all rule 2.
        let mut invite = invite_option(
            "sip:ai@116.62.75.161:13050",
            "sip:+8613800138000@sbc.example.com:5060",
            "sip:ai@127.0.0.1:13050",
        );
        config.apply_trunk_rules(&mut invite);
        assert_eq!(
            invite.contact.host_with_port.host.to_string(),
            "116.62.75.161"
        );
    }

    #[test]
    fn test_trunk_rule_first_match_wins() {
        let config: Config = toml::from_str(
            r#"
addr = "0.0.0.0"
udp_port = 25060

[[trunk_rules]]
rule.match.to.host = ".*"
rule.rewrite.contact.host = "1.1.1.1"

[[trunk_rules]]
rule.match.to.host = ".*"
rule.rewrite.contact.host = "2.2.2.2"
"#,
        )
        .unwrap();

        let mut invite = invite_option(
            "sip:ai@116.62.75.161:13050",
            "sip:any@example.com:5060",
            "sip:ai@127.0.0.1:13050",
        );
        config.apply_trunk_rules(&mut invite);
        // Only the first rule applies.
        assert_eq!(invite.contact.host_with_port.host.to_string(), "1.1.1.1");
    }

    #[test]
    fn test_trunk_rule_no_config_noop() {
        let config = Config::default();
        let mut invite = invite_option(
            "sip:ai@116.62.75.161:13050",
            "sip:agent1@172.25.225.3:15060",
            "sip:ai@127.0.0.1:13050",
        );
        let before = invite.contact.to_string();
        config.apply_trunk_rules(&mut invite);
        assert_eq!(invite.contact.to_string(), before);
    }

    #[test]
    fn test_trunk_rule_rewrite_missing_auth_creates_user() {
        let config: Config = toml::from_str(
            r#"
addr = "0.0.0.0"
udp_port = 25060

[[trunk_rules]]
rule.match.to.host = ".*"
rule.rewrite.contact.user = "active-call"
"#,
        )
        .unwrap();

        // A contact without a user part (e.g. "sip:127.0.0.1:13050").
        let mut invite = InviteOption {
            caller: "sip:ai@127.0.0.1:13050".try_into().unwrap(),
            callee: "sip:agent1@172.25.225.3:15060".try_into().unwrap(),
            contact: "sip:127.0.0.1:13050".try_into().unwrap(),
            ..Default::default()
        };
        config.apply_trunk_rules(&mut invite);
        assert_eq!(invite.contact.auth.as_ref().unwrap().user, "active-call");
    }
}