rustpbx 0.4.4

A SIP PBX implementation in Rust
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
//! IVR application — built-in, config-driven interactive voice response.
//!
//! Reads TOML configuration from `config/ivr/{name}.toml` and drives a
//! menu-based state machine through the [`CallApp`] trait.
//!
//! # State Machine
//!
//! ```text
//! Init → PlayingGreeting → WaitingDtmf ──→ (action)
//!                              ↑   │
//!                              │   ├─ timeout → PlayingInvalid/retry
//!                              │   └─ invalid → PlayingInvalid/retry
//!                              │       │
//!                              └───────┘
//!       PlayingAnnouncement → (return to menu)
//!       CollectingExtension → Transfer
//!       Webhook → (response determines next action)
//! ```

use super::config::{EntryAction, IvrDefinition, WebhookResponse};
use crate::call::app::{
    AppAction, ApplicationContext, CallApp, CallAppType, CallController, DtmfCollectConfig,
};
use crate::callrecord::CallRecordHangupReason;
use async_trait::async_trait;
use serde::{Deserialize, Serialize};
use std::sync::Arc;
use std::time::Duration;
use tracing::{debug, error, info, warn};

/// Internal state of the IVR state machine.
#[derive(Debug, Clone, PartialEq)]
enum IvrState {
    /// Initial state before `on_enter`.
    Init,
    /// Playing the greeting audio for a menu.
    PlayingGreeting { menu_key: String },
    /// Waiting for a DTMF key press.
    WaitingDtmf { menu_key: String, retry_count: u32 },
    /// Playing the "invalid input" prompt, will retry afterwards.
    PlayingInvalid { menu_key: String, retry_count: u32 },
    /// Playing an announcement (from `play` action), returns to `return_menu`.
    PlayingAnnouncement { return_menu: String },
    /// Playing a hangup/goodbye prompt before disconnecting.
    PlayingHangup,
    /// Playing a prompt before hanging up with a specific SIP code.
    PlayingAndHangup { code: Option<u16> },
    /// Collecting multi-digit extension input.
    CollectingExtension,
    /// Terminal state.
    Done,
}

/// Payload sent to the webhook endpoint with call context information.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct WebhookPayload {
    /// Unique call session identifier.
    pub session_id: String,
    /// Caller number/URI.
    pub caller: String,
    /// Callee number/URI.
    pub callee: String,
    /// Call direction ("inbound" / "outbound").
    pub direction: String,
    /// IVR definition name.
    pub ivr_name: String,
    /// Current menu key.
    pub menu: String,
    /// Collected variables from Collect actions.
    #[serde(default)]
    pub variables: std::collections::HashMap<String, String>,
}

/// A built-in IVR application driven by TOML configuration.
///
/// Supports nested menus, DTMF routing, timeouts, retries, transfer,
/// queue, voicemail, play-and-return, extension collection, and more.
pub struct IvrApp {
    /// Parsed IVR definition (menus, entries, actions).
    definition: IvrDefinition,
    /// Current state machine state.
    state: IvrState,
    /// Menu navigation stack (e.g. `["root", "sales"]`).
    menu_stack: Vec<String>,
    /// Retry count carried across greeting replay (since `PlayingGreeting`
    /// state itself doesn't track retries).
    pending_retry_count: u32,
    /// Variables collected via Collect actions.
    collected_variables: std::collections::HashMap<String, String>,
    /// First digit collected for unknown_key_action (direct dial scenario).
    pending_unknown_digit: Option<String>,
    /// Optional TTS service synthesized from the IVR's own TTS config.
    tts_service: Option<Arc<crate::tts::TtsService>>,
}

impl IvrApp {
    /// Create a new `IvrApp` from a parsed [`IvrDefinition`].
    pub fn new(definition: IvrDefinition) -> Self {
        let tts_service = definition
            .tts
            .as_ref()
            .map(|cfg| Arc::new(crate::tts::TtsService::new(cfg.clone())));
        Self {
            definition,
            state: IvrState::Init,
            menu_stack: vec!["root".to_string()],
            pending_retry_count: 0,
            collected_variables: std::collections::HashMap::new(),
            pending_unknown_digit: None,
            tts_service,
        }
    }

    /// Create a new `IvrApp` with an explicit TTS config override.
    pub fn with_tts(mut self, tts: Option<crate::tts::TtsConfig>) -> Self {
        self.tts_service = tts.map(|cfg| Arc::new(crate::tts::TtsService::new(cfg)));
        self
    }

    /// Load an `IvrApp` from a TOML file path.
    pub fn from_file(path: &str) -> anyhow::Result<Self> {
        let content = std::fs::read_to_string(path)
            .map_err(|e| anyhow::anyhow!("Failed to read IVR config '{}': {}", path, e))?;
        let file_config: super::config::IvrFileConfig = toml::from_str(&content)
            .map_err(|e| anyhow::anyhow!("Failed to parse IVR config '{}': {}", path, e))?;
        file_config
            .ivr
            .validate()
            .map_err(|e| anyhow::anyhow!("IVR config validation failed '{}': {}", path, e))?;
        Ok(Self::new(file_config.ivr))
    }

    /// Emit an RWI event via the gateway in the application context, if configured.
    fn emit_rwi_event(&self, ctx: &ApplicationContext, event: crate::rwi::proto::RwiEvent) {
        if let Some(ref gw) = ctx.rwi_gateway {
            let gw = gw.clone();
            let call_id = ctx.call_info.session_id.clone();
            tokio::spawn(async move {
                let guard = gw.read().await;
                guard.fan_out_event_to_context(&call_id, &event, &call_id);
            });
        }
    }

    /// Emit IvrFlowCompleted when the IVR flow ends via a terminal action.
    async fn ivr_flow_completed(
        &self,
        ctx: &ApplicationContext,
        final_result: &str,
        target: Option<&str>,
    ) {
        self.emit_rwi_event(
            ctx,
            crate::rwi::proto::RwiEvent::IvrFlowCompleted {
                call_id: ctx.call_info.session_id.clone(),
                app_id: self.definition.name.clone(),
                total_nodes_traversed: 0,
                total_duration_ms: 0,
                final_result: final_result.to_string(),
                completion_time: chrono::Utc::now().to_rfc3339(),
                final_routing_target: target.map(|s| s.to_string()),
                context: Default::default(),
            },
        );
    }

    /// Check if the current time falls within business hours.
    fn is_within_business_hours(&self, bh: &super::config::BusinessHours) -> bool {
        use chrono::{Datelike, Utc};

        let tz: chrono_tz::Tz = match bh.timezone.parse() {
            Ok(tz) => tz,
            Err(_) => {
                warn!(
                    ivr = %self.definition.name,
                    timezone = %bh.timezone,
                    "Invalid timezone, defaulting to UTC"
                );
                chrono_tz::UTC
            }
        };

        let now = Utc::now().with_timezone(&tz);
        let weekday = match now.weekday() {
            chrono::Weekday::Mon => "mon",
            chrono::Weekday::Tue => "tue",
            chrono::Weekday::Wed => "wed",
            chrono::Weekday::Thu => "thu",
            chrono::Weekday::Fri => "fri",
            chrono::Weekday::Sat => "sat",
            chrono::Weekday::Sun => "sun",
        };

        for schedule in &bh.schedules {
            if !schedule
                .days
                .iter()
                .any(|d| d.eq_ignore_ascii_case(weekday))
            {
                continue;
            }

            let start = match chrono::NaiveTime::parse_from_str(&schedule.start, "%H:%M") {
                Ok(t) => t,
                Err(_) => continue,
            };
            let end = match chrono::NaiveTime::parse_from_str(&schedule.end, "%H:%M") {
                Ok(t) => t,
                Err(_) => continue,
            };

            let current_time = now.time();
            if current_time >= start && current_time <= end {
                return true;
            }
        }

        // If no schedules defined, always open
        bh.schedules.is_empty()
    }

    /// Get the current menu key (top of stack).
    fn current_menu_key(&self) -> &str {
        self.menu_stack.last().map(|s| s.as_str()).unwrap_or("root")
    }

    /// Navigate to a menu. If `"root"`, reset the stack. Otherwise push only
    /// if the menu is not already the current top (avoids unbounded growth on Repeat).
    fn navigate_to_menu(&mut self, menu_key: &str) {
        let old_stack = self.menu_stack.clone();
        if menu_key == "root" {
            self.menu_stack.clear();
            self.menu_stack.push("root".to_string());
        } else if self.current_menu_key() != menu_key {
            self.menu_stack.push(menu_key.to_string());
        }
        if old_stack != self.menu_stack {
            info!(
                ivr = %self.definition.name,
                old_stack = ?old_stack,
                new_stack = ?self.menu_stack,
                "IVR menu stack changed"
            );
        }
        // If already on this menu (e.g. Repeat), keep the stack as-is.
    }

    fn navigate_back(&mut self) -> String {
        if self.menu_stack.len() > 1 {
            let popped = self.menu_stack.pop();
            info!(
                ivr = %self.definition.name,
                popped = ?popped,
                new_top = ?self.menu_stack.last(),
                "IVR navigating back"
            );
        } else {
            info!(ivr = %self.definition.name, "IVR Back called at root, staying on root");
        }
        self.menu_stack
            .last()
            .cloned()
            .unwrap_or_else(|| "root".to_string())
    }

    async fn resolve_audio(
        &self,
        file: Option<&str>,
        text: Option<&str>,
        voice: Option<&str>,
    ) -> Option<String> {
        if let Some(path) = file
            && !path.is_empty()
        {
            // tts:// URI: parse text and optional voice from the URI, then synthesize
            if let Some(rest) = path.strip_prefix("tts://") {
                let (encoded_text, tts_voice) = if let Some((t, q)) = rest.split_once('?') {
                    let v = q.strip_prefix("voice=").filter(|v| !v.is_empty());
                    (t, v)
                } else {
                    (rest, None)
                };
                let tts_text = urlencoding::decode(encoded_text)
                    .map(|s| s.into_owned())
                    .unwrap_or_else(|_| encoded_text.to_string());
                if let Some(service) = self.tts_service.as_ref() {
                    match service.synthesize(&tts_text, tts_voice).await {
                        Ok(audio_path) => return Some(audio_path),
                        Err(e) => {
                            warn!(ivr = %self.definition.name, text = %tts_text, error = %e, "TTS synthesis failed for tts:// URI");
                        }
                    }
                } else {
                    // Fallback: try edge-cli if available
                    let voice_str = tts_voice.unwrap_or("zh-CN-XiaoxiaoNeural").to_string();
                    let fallback_cfg = crate::tts::TtsConfig {
                        cache_dir: std::env::temp_dir()
                            .join("rustpbx_tts_cache")
                            .to_string_lossy()
                            .to_string(),
                        cache_ttl_seconds: 86400,
                        driver: crate::tts::TtsDriverConfig::Cli(crate::tts::CliTtsConfig {
                            command: "edge-cli".to_string(),
                            args: vec![
                                "speak".to_string(),
                                "--text".to_string(),
                                "{text}".to_string(),
                                "--voice".to_string(),
                                "{voice}".to_string(),
                                "--output".to_string(),
                                "{output}".to_string(),
                            ],
                            output_format: "mp3".to_string(),
                        }),
                    };
                    let fallback_service = crate::tts::TtsService::new(fallback_cfg);
                    match fallback_service
                        .synthesize(&tts_text, Some(&voice_str))
                        .await
                    {
                        Ok(audio_path) => return Some(audio_path),
                        Err(e) => {
                            warn!(ivr = %self.definition.name, text = %tts_text, error = %e, "edge-cli fallback TTS failed");
                        }
                    }
                }
                return None;
            }
            return Some(path.to_string());
        }
        if let (Some(t), Some(service)) = (text, self.tts_service.as_ref()) {
            match service.synthesize(t, voice).await {
                Ok(path) => return Some(path),
                Err(e) => {
                    warn!(ivr = %self.definition.name, text = %t, error = %e, "TTS synthesis failed");
                }
            }
        }
        None
    }

    /// Start playing the greeting for the specified menu.
    async fn enter_menu(
        &mut self,
        menu_key: &str,
        ctrl: &mut CallController,
        ctx: &ApplicationContext,
    ) -> anyhow::Result<AppAction> {
        self.navigate_to_menu(menu_key);
        info!(
            ivr = %self.definition.name,
            menu = menu_key,
            menu_stack = ?self.menu_stack,
            "IVR entering menu"
        );

        // Emit IvrNodeEntered event
        let previous_node = self.menu_stack.iter().rev().nth(1).cloned();
        self.emit_rwi_event(
            ctx,
            crate::rwi::proto::RwiEvent::IvrNodeEntered {
                call_id: ctx.call_info.session_id.clone(),
                node_id: menu_key.to_string(),
                node_name: menu_key.to_string(),
                node_type: "menu".to_string(),
                app_id: self.definition.name.clone(),
                entry_time: chrono::Utc::now().to_rfc3339(),
                ani: Some(ctx.call_info.caller.clone()),
                dnis: Some(ctx.call_info.callee.clone()),
                routing_target: Some(menu_key.to_string()),
                previous_node_id: previous_node,
                context: Default::default(),
            },
        );
        let menu = self
            .definition
            .get_menu(menu_key)
            .ok_or_else(|| anyhow::anyhow!("IVR menu '{}' not found", menu_key))?;
        let greeting = self
            .resolve_audio(
                Some(&menu.greeting),
                menu.greeting_text.as_deref(),
                menu.greeting_voice.as_deref(),
            )
            .await;
        self.state = IvrState::PlayingGreeting {
            menu_key: menu_key.to_string(),
        };
        if let Some(path) = greeting {
            info!(ivr = %self.definition.name, menu = menu_key, "Playing greeting: {}", path);
            ctrl.play_audio(&path, false).await?;
        } else {
            info!(
                ivr = %self.definition.name,
                menu = menu_key,
                "No greeting audio, waiting DTMF immediately"
            );
            self.start_waiting_dtmf(menu_key, self.pending_retry_count, ctrl);
        }
        Ok(AppAction::Continue)
    }

    /// Start waiting for DTMF input with a timeout.
    fn start_waiting_dtmf(&mut self, menu_key: &str, retry_count: u32, ctrl: &CallController) {
        let menu = self.definition.get_menu(menu_key);
        let timeout_ms = menu.map(|m| m.timeout_ms).unwrap_or(5000);
        self.state = IvrState::WaitingDtmf {
            menu_key: menu_key.to_string(),
            retry_count,
        };
        ctrl.set_timeout("ivr_dtmf_timeout", Duration::from_millis(timeout_ms));
        info!(
            ivr = %self.definition.name,
            menu = menu_key,
            retry_count,
            timeout_ms,
            "IVR waiting for DTMF input"
        );
    }

    /// Execute an action from a DTMF press or timeout/max-retries fallback.
    async fn execute_action(
        &mut self,
        action: &EntryAction,
        ctrl: &mut CallController,
        ctx: &ApplicationContext,
    ) -> anyhow::Result<AppAction> {
        ctrl.cancel_timeout("ivr_dtmf_timeout");

        // Emit IvrNodeExited event when leaving a menu node.
        if let IvrState::WaitingDtmf { ref menu_key, .. }
        | IvrState::PlayingGreeting { ref menu_key } = self.state
        {
            let node_name = menu_key.clone();
            self.emit_rwi_event(
                ctx,
                crate::rwi::proto::RwiEvent::IvrNodeExited {
                    call_id: ctx.call_info.session_id.clone(),
                    node_id: menu_key.clone(),
                    node_name,
                    result_value: None,
                    duration_ms: 0,
                    exit_time: chrono::Utc::now().to_rfc3339(),
                    next_node_id: None,
                    hangup_reason: None,
                    call_result: None,
                    context: Default::default(),
                },
            );
        }
        match action {
            EntryAction::Transfer { target } => {
                info!(ivr = %self.definition.name, target, "IVR transferring call");
                self.ivr_flow_completed(ctx, "transferred", Some(target))
                    .await;
                self.state = IvrState::Done;
                Ok(AppAction::Transfer(target.clone()))
            }
            EntryAction::Queue {
                target,
                return_to_ivr,
            } => {
                info!(
                    ivr = %self.definition.name,
                    queue = target,
                    return_to_ivr = ?return_to_ivr,
                    "IVR sending to queue"
                );
                self.ivr_flow_completed(ctx, "queue", Some(target)).await;
                self.state = IvrState::Done;
                if return_to_ivr.unwrap_or(false) {
                    // Encode return IVR name so the queue can come back on failure
                    Ok(AppAction::Transfer(format!(
                        "queue:{}?return_ivr={}",
                        target, self.definition.name
                    )))
                } else {
                    Ok(AppAction::Transfer(format!("queue:{}", target)))
                }
            }
            EntryAction::Menu { menu } => {
                info!(ivr = %self.definition.name, from = %self.current_menu_key(), to = %menu, "IVR navigating to menu");
                self.enter_menu(menu, ctrl, ctx).await
            }
            EntryAction::Back => {
                let target = self.navigate_back();
                info!(ivr = %self.definition.name, menu = %target, "IVR entering parent menu after Back");
                self.enter_menu(&target, ctrl, ctx).await
            }
            EntryAction::Voicemail { target } => {
                info!(ivr = %self.definition.name, target, "IVR transferring to voicemail");
                self.ivr_flow_completed(ctx, "voicemail", Some(target))
                    .await;
                self.state = IvrState::Done;
                Ok(AppAction::Transfer(format!("voicemail:{}", target)))
            }
            EntryAction::Play {
                prompt,
                prompt_text,
                prompt_voice,
            } => {
                let return_menu = self.current_menu_key().to_string();
                self.state = IvrState::PlayingAnnouncement {
                    return_menu: return_menu.clone(),
                };
                if let Some(path) = self
                    .resolve_audio(
                        Some(prompt),
                        prompt_text.as_deref(),
                        prompt_voice.as_deref(),
                    )
                    .await
                {
                    info!(ivr = %self.definition.name, prompt = %path, return_menu, "IVR playing announcement");
                    ctrl.play_audio(&path, false).await?;
                    Ok(AppAction::Continue)
                } else {
                    info!(ivr = %self.definition.name, return_menu, "IVR announcement has no audio, returning to menu");
                    return self.enter_menu(&return_menu, ctrl, ctx).await;
                }
            }
            EntryAction::Repeat => {
                let current = self.current_menu_key().to_string();
                info!(ivr = %self.definition.name, menu = %current, "IVR repeating menu");
                self.enter_menu(&current, ctrl, ctx).await
            }
            EntryAction::Hangup { prompt, prompt_text, prompt_voice, .. } => {
                if let Some(path) = self
                    .resolve_audio(
                        prompt.as_deref(),
                        prompt_text.as_deref(),
                        prompt_voice.as_deref(),
                    )
                    .await
                {
                    self.state = IvrState::PlayingAndHangup { code: None };
                    debug!(ivr = %self.definition.name, prompt = %path, "Playing prompt before hangup");
                    ctrl.play_audio(&path, false).await?;
                    Ok(AppAction::Continue)
                } else {
                    info!(ivr = %self.definition.name, "IVR hanging up");
                    self.ivr_flow_completed(ctx, "hangup", None).await;
                    self.state = IvrState::Done;
                    Ok(AppAction::Hangup {
                        reason: None,
                        code: None,
                    })
                }
            }
            EntryAction::PlayAndHangup {
                prompt,
                prompt_text,
                prompt_voice,
                code,
            } => {
                self.state = IvrState::PlayingAndHangup { code: *code };
                if let Some(path) = self
                    .resolve_audio(
                        prompt.as_deref(),
                        prompt_text.as_deref(),
                        prompt_voice.as_deref(),
                    )
                    .await
                {
                    debug!(ivr = %self.definition.name, prompt = %path, code = ?code, "Playing prompt before hangup with code");
                    ctrl.play_audio(&path, false).await?;
                    Ok(AppAction::Continue)
                } else {
                    // No prompt — hang up immediately with the given code
                    info!(ivr = %self.definition.name, code = ?code, "IVR hanging up immediately with code (no prompt)");
                    self.state = IvrState::Done;
                    Ok(AppAction::Hangup {
                        reason: None,
                        code: *code,
                    })
                }
            }
            EntryAction::CollectExtension {
                prompt,
                prompt_text,
                prompt_voice,
                min_digits,
                max_digits,
                inter_digit_timeout_ms,
            } => {
                self.state = IvrState::CollectingExtension;
                let resolved_prompt = self
                    .resolve_audio(
                        Some(prompt),
                        prompt_text.as_deref(),
                        prompt_voice.as_deref(),
                    )
                    .await;
                debug!(
                    ivr = %self.definition.name,
                    prompt = ?resolved_prompt, min_digits, max_digits, inter_digit_timeout_ms,
                    "Collecting extension digits"
                );

                // Check if we have a pending digit from unknown_key_action
                let initial_digit = self.pending_unknown_digit.take();
                let digits = if let Some(first) = initial_digit {
                    // Already have first digit, collect more if needed
                    if first.len() >= *min_digits {
                        first.clone()
                    } else {
                        let mut combined = first;
                        let more = ctrl
                            .collect_dtmf(DtmfCollectConfig {
                                min_digits: 1,
                                max_digits: max_digits.saturating_sub(combined.len()),
                                timeout: Duration::from_millis(
                                    *inter_digit_timeout_ms * (*max_digits as u64 + 1),
                                ),
                                terminator: Some('#'),
                                play_prompt: resolved_prompt.clone(),
                                inter_digit_timeout: Some(Duration::from_millis(
                                    *inter_digit_timeout_ms,
                                )),
                            })
                            .await?;
                        combined.push_str(&more);
                        combined
                    }
                } else {
                    ctrl.collect_dtmf(DtmfCollectConfig {
                        min_digits: *min_digits,
                        max_digits: *max_digits,
                        timeout: Duration::from_millis(
                            *inter_digit_timeout_ms * (*max_digits as u64 + 1),
                        ),
                        terminator: Some('#'),
                        play_prompt: resolved_prompt.clone(),
                        inter_digit_timeout: Some(Duration::from_millis(*inter_digit_timeout_ms)),
                    })
                    .await?
                };

                if digits.is_empty() {
                    // No digits collected, go back to current menu
                    let current = self.current_menu_key().to_string();
                    self.enter_menu(&current, ctrl, ctx).await
                } else {
                    info!(ivr = %self.definition.name, extension = %digits, "Transferring to collected extension");
                    self.state = IvrState::Done;
                    Ok(AppAction::Transfer(digits))
                }
            }
            EntryAction::Collect {
                variable,
                prompt,
                prompt_text,
                prompt_voice,
                min_digits,
                max_digits,
                end_key,
                inter_digit_timeout_ms,
            } => {
                debug!(
                    ivr = %self.definition.name,
                    variable, min_digits, max_digits, inter_digit_timeout_ms,
                    "Collecting digits into variable"
                );
                let terminator = end_key.as_ref().and_then(|k| k.chars().next());
                let resolved_prompt = self
                    .resolve_audio(
                        prompt.as_deref(),
                        prompt_text.as_deref(),
                        prompt_voice.as_deref(),
                    )
                    .await;

                // Check if we have a pending digit from unknown_key_action
                let initial_digit = self.pending_unknown_digit.take();
                let digits = if let Some(first) = initial_digit {
                    // Already have first digit, collect more if needed
                    if first.len() >= *min_digits {
                        // Already have enough digits
                        first.clone()
                    } else {
                        // Collect more digits, starting with what we have
                        let mut combined = first;
                        let more = ctrl
                            .collect_dtmf(DtmfCollectConfig {
                                min_digits: 1,
                                max_digits: max_digits.saturating_sub(combined.len()),
                                timeout: Duration::from_millis(
                                    *inter_digit_timeout_ms * (*max_digits as u64 + 1),
                                ),
                                terminator,
                                play_prompt: resolved_prompt.clone(),
                                inter_digit_timeout: Some(Duration::from_millis(
                                    *inter_digit_timeout_ms,
                                )),
                            })
                            .await?;
                        combined.push_str(&more);
                        combined
                    }
                } else {
                    ctrl.collect_dtmf(DtmfCollectConfig {
                        min_digits: *min_digits,
                        max_digits: *max_digits,
                        timeout: Duration::from_millis(
                            *inter_digit_timeout_ms * (*max_digits as u64 + 1),
                        ),
                        terminator,
                        play_prompt: resolved_prompt.clone(),
                        inter_digit_timeout: Some(Duration::from_millis(*inter_digit_timeout_ms)),
                    })
                    .await?
                };

                if digits.is_empty() {
                    debug!(ivr = %self.definition.name, variable, "No digits collected for variable");
                } else {
                    info!(ivr = %self.definition.name, variable, digits, "Collected digits into variable");
                    self.collected_variables.insert(variable.clone(), digits);
                }

                // Return to current menu after collecting
                let current = self.current_menu_key().to_string();
                self.enter_menu(&current, ctrl, ctx).await
            }
            EntryAction::Webhook {
                url,
                method,
                headers,
                variables,
                timeout,
            } => {
                let method_str = method.as_deref().unwrap_or("POST");
                info!(
                    ivr = %self.definition.name,
                    url, method = method_str,
                    "IVR calling webhook"
                );

                let webhook_response = self
                    .call_webhook(
                        url,
                        method_str,
                        headers,
                        variables.as_deref(),
                        *timeout,
                        ctx,
                    )
                    .await;

                match webhook_response {
                    Ok(response) => {
                        debug!(
                            ivr = %self.definition.name,
                            url,
                            "Webhook responded successfully, executing returned command"
                        );
                        // Convert WebhookResponse into an EntryAction and execute it
                        let derived_action = response.into_entry_action();
                        // Use Box::pin to avoid recursion issues with async fn
                        Box::pin(self.execute_action(&derived_action, ctrl, ctx)).await
                    }
                    Err(e) => {
                        error!(
                            ivr = %self.definition.name,
                            url,
                            error = %e,
                            "Webhook call failed, continuing IVR"
                        );
                        // On error, stay in current menu (re-play greeting)
                        let current = self.current_menu_key().to_string();
                        self.enter_menu(&current, ctrl, ctx).await
                    }
                }
            }

            EntryAction::Prompt { .. }
            | EntryAction::DtmfMenu { .. }
            | EntryAction::CollectDtmf { .. }
            | EntryAction::InputPhone { .. }
            | EntryAction::InputVoice { .. }
            | EntryAction::Api { .. }
            | EntryAction::Torecord { .. }
            | EntryAction::JumpIvr { .. }
            | EntryAction::RouteToAgent { .. }
            | EntryAction::VoipBridge { .. } => {
                error!(ivr = %self.definition.name, action = ?std::mem::discriminant(action),
                    "Tree mode IVR received unsupported step-mode action");
                Err(anyhow::anyhow!("unsupported action type for tree mode"))
            }
        }
    }

    /// Call an external webhook and return the parsed [`WebhookResponse`].
    ///
    /// The request body (for POST) or query params (for GET) include the
    /// current call context so that the webhook can make routing decisions.
    async fn call_webhook(
        &self,
        url: &str,
        method: &str,
        headers: &std::collections::HashMap<String, String>,
        variables_filter: Option<&str>,
        timeout_secs: u64,
        ctx: &ApplicationContext,
    ) -> anyhow::Result<WebhookResponse> {
        // Filter variables if a filter is specified
        let filtered_vars = if let Some(filter) = variables_filter {
            let filter_set: std::collections::HashSet<&str> = filter
                .split(',')
                .map(|s| s.trim())
                .filter(|s| !s.is_empty())
                .collect();
            self.collected_variables
                .iter()
                .filter(|(k, _)| filter_set.contains(k.as_str()))
                .map(|(k, v)| (k.clone(), v.clone()))
                .collect()
        } else {
            self.collected_variables.clone()
        };

        // Build the request with custom headers.
        // For GET: send context as query params to avoid a JSON body.
        // For POST (and everything else): serialize the full payload as JSON.
        let mut req_builder = if method.eq_ignore_ascii_case("GET") {
            let mut params = vec![
                ("session_id", ctx.call_info.session_id.as_str()),
                ("caller", ctx.call_info.caller.as_str()),
                ("callee", ctx.call_info.callee.as_str()),
                ("direction", ctx.call_info.direction.as_str()),
                ("ivr_name", self.definition.name.as_str()),
                ("menu", self.current_menu_key()),
            ];
            // Add collected variables as query params
            for (k, v) in &filtered_vars {
                params.push((k, v));
            }
            ctx.http_client.get(url).query(&params)
        } else {
            let payload = WebhookPayload {
                session_id: ctx.call_info.session_id.clone(),
                caller: ctx.call_info.caller.clone(),
                callee: ctx.call_info.callee.clone(),
                direction: ctx.call_info.direction.clone(),
                ivr_name: self.definition.name.clone(),
                menu: self.current_menu_key().to_string(),
                variables: filtered_vars,
            };
            ctx.http_client.post(url).json(&payload)
        };

        for (key, value) in headers {
            req_builder = req_builder.header(key, value);
        }

        let response = tokio::time::timeout(Duration::from_secs(timeout_secs), req_builder.send())
            .await
            .map_err(|_| {
                anyhow::anyhow!("Webhook request timed out after {} seconds", timeout_secs)
            })?
            .map_err(|e| anyhow::anyhow!("Webhook request failed: {}", e))?;

        let status = response.status();
        if !status.is_success() {
            return Err(anyhow::anyhow!(
                "Webhook returned non-success status: {}",
                status
            ));
        }

        let webhook_response: WebhookResponse = response
            .json()
            .await
            .map_err(|e| anyhow::anyhow!("Failed to parse webhook response: {}", e))?;

        Ok(webhook_response)
    }

    /// Handle timeout: either retry or execute timeout_action.
    async fn handle_timeout(
        &mut self,
        menu_key: String,
        retry_count: u32,
        ctrl: &mut CallController,
        ctx: &ApplicationContext,
    ) -> anyhow::Result<AppAction> {
        // Extract only what we need before any mutable borrow of self.
        let (max_retries, timeout_action, max_retries_action, menu) = {
            let menu = self
                .definition
                .get_menu(&menu_key)
                .ok_or_else(|| anyhow::anyhow!("menu '{}' not found", menu_key))?;
            (
                menu.max_retries,
                menu.timeout_action.clone(),
                menu.max_retries_action.clone(),
                menu.clone(),
            )
        };

        let new_retry = retry_count + 1;
        if new_retry > max_retries {
            if let Some(action) = max_retries_action {
                info!(
                    ivr = %self.definition.name,
                    menu = %menu_key,
                    retries = new_retry,
                    "IVR max retries exceeded (timeout), executing fallback action"
                );
                return self.execute_action(&action, ctrl, ctx).await;
            } else {
                info!(
                    ivr = %self.definition.name,
                    menu = %menu_key,
                    retries = new_retry,
                    "IVR max retries exceeded (timeout), no fallback — hanging up"
                );
                self.state = IvrState::Done;
                return Ok(AppAction::Hangup {
                    reason: None,
                    code: None,
                });
            }
        }

        // Retry: check timeout_action
        if let Some(action) = timeout_action {
            match action {
                EntryAction::Repeat => {
                    info!(
                        ivr = %self.definition.name,
                        menu = %menu_key,
                        retry = new_retry,
                        "IVR timeout: repeating menu"
                    );
                    self.state = IvrState::PlayingGreeting {
                        menu_key: menu_key.clone(),
                    };
                    self.pending_retry_count = new_retry;
                    if let Some(path) = self
                        .resolve_audio(
                            Some(&menu.greeting),
                            menu.greeting_text.as_deref(),
                            menu.greeting_voice.as_deref(),
                        )
                        .await
                    {
                        ctrl.play_audio(&path, false).await?;
                    } else {
                        self.start_waiting_dtmf(&menu_key, new_retry, ctrl);
                    }
                    Ok(AppAction::Continue)
                }
                other => self.execute_action(&other, ctrl, ctx).await,
            }
        } else {
            // No timeout_action defined; replay the greeting
            info!(
                ivr = %self.definition.name,
                menu = %menu_key,
                retry = new_retry,
                "IVR timeout: replaying greeting (default)"
            );
            self.state = IvrState::PlayingGreeting {
                menu_key: menu_key.clone(),
            };
            self.pending_retry_count = new_retry;
            if let Some(path) = self
                .resolve_audio(
                    Some(&menu.greeting),
                    menu.greeting_text.as_deref(),
                    menu.greeting_voice.as_deref(),
                )
                .await
            {
                ctrl.play_audio(&path, false).await?;
            } else {
                self.start_waiting_dtmf(&menu_key, new_retry, ctrl);
            }
            Ok(AppAction::Continue)
        }
    }

    /// Handle an invalid DTMF key press.
    async fn handle_invalid_key(
        &mut self,
        menu_key: &str,
        retry_count: u32,
        digit: &str,
        ctrl: &mut CallController,
        ctx: &ApplicationContext,
    ) -> anyhow::Result<AppAction> {
        ctrl.cancel_timeout("ivr_dtmf_timeout");

        // Extract only what we need before any mutable borrow of self.
        let (max_retries, max_retries_action, invalid_prompt, invalid_text, invalid_voice) = {
            let menu = self
                .definition
                .get_menu(menu_key)
                .ok_or_else(|| anyhow::anyhow!("menu '{}' not found", menu_key))?;
            (
                menu.max_retries,
                menu.max_retries_action.clone(),
                menu.invalid_prompt.clone(),
                menu.invalid_text.clone(),
                menu.invalid_voice.clone(),
            )
        };

        let new_retry = retry_count + 1;
        info!(
            ivr = %self.definition.name,
            menu = menu_key,
            digit = %digit,
            retry = new_retry,
            max_retries,
            "IVR invalid DTMF key"
        );

        if new_retry > max_retries {
            if let Some(action) = max_retries_action {
                info!(
                    ivr = %self.definition.name,
                    menu = menu_key,
                    retries = new_retry,
                    "IVR max retries exceeded after invalid key, executing fallback"
                );
                return self.execute_action(&action, ctrl, ctx).await;
            } else {
                info!(
                    ivr = %self.definition.name,
                    menu = menu_key,
                    retries = new_retry,
                    "IVR max retries exceeded after invalid key, hanging up"
                );
                self.state = IvrState::Done;
                return Ok(AppAction::Hangup {
                    reason: None,
                    code: None,
                });
            }
        }

        if let Some(path) = self
            .resolve_audio(
                invalid_prompt.as_deref(),
                invalid_text.as_deref(),
                invalid_voice.as_deref(),
            )
            .await
        {
            info!(
                ivr = %self.definition.name,
                menu = menu_key,
                "IVR playing invalid prompt"
            );
            self.state = IvrState::PlayingInvalid {
                menu_key: menu_key.to_string(),
                retry_count: new_retry,
            };
            ctrl.play_audio(&path, false).await?;
            Ok(AppAction::Continue)
        } else {
            // No invalid prompt — just go back to waiting
            info!(
                ivr = %self.definition.name,
                menu = menu_key,
                retry = new_retry,
                "IVR no invalid prompt, returning to wait DTMF"
            );
            self.start_waiting_dtmf(menu_key, new_retry, ctrl);
            Ok(AppAction::Continue)
        }
    }
}

#[async_trait]
impl CallApp for IvrApp {
    fn app_type(&self) -> CallAppType {
        CallAppType::Ivr
    }

    fn name(&self) -> &str {
        &self.definition.name
    }

    async fn on_enter(
        &mut self,
        ctrl: &mut CallController,
        ctx: &ApplicationContext,
    ) -> anyhow::Result<AppAction> {
        info!(ivr = %self.definition.name, "IVR application started");
        ctrl.answer().await?;

        // Check business hours
        let closed_action = if let Some(bh) = &self.definition.business_hours {
            if bh.enabled && !self.is_within_business_hours(bh) {
                info!(ivr = %self.definition.name, "Outside business hours");
                if let Some(path) = self
                    .resolve_audio(
                        bh.closed_greeting.as_deref(),
                        bh.closed_text.as_deref(),
                        None,
                    )
                    .await
                {
                    self.state = IvrState::PlayingHangup;
                    ctrl.play_audio(&path, false).await?;
                    // After playing, the on_audio_complete will handle closed_action
                    return Ok(AppAction::Continue);
                }
                Some(bh.closed_action.clone())
            } else {
                None
            }
        } else {
            None
        };

        if let Some(action) = closed_action {
            if let Some(action) = action {
                return self.execute_action(&action, ctrl, ctx).await;
            }
            // Default: hang up
            self.state = IvrState::Done;
            return Ok(AppAction::Hangup {
                reason: Some(CallRecordHangupReason::Other("closed".to_string())),
                code: None,
            });
        }

        self.enter_menu("root", ctrl, ctx).await
    }

    async fn on_dtmf(
        &mut self,
        digit: String,
        ctrl: &mut CallController,
        ctx: &ApplicationContext,
    ) -> anyhow::Result<AppAction> {
        // Extract state data we need before the mutable calls below.
        // We only clone the String fields, not the full IvrState enum.
        let state_snapshot = match &self.state {
            IvrState::WaitingDtmf {
                menu_key,
                retry_count,
            } => Some((*retry_count, menu_key.clone(), false)),
            IvrState::PlayingGreeting { menu_key } => Some((0, menu_key.clone(), true)),
            _ => None,
        };

        let Some((retry_count, menu_key, is_greeting)) = state_snapshot else {
            // DTMF in other states is ignored
            info!(
                ivr = %self.definition.name,
                digit,
                state = ?self.state,
                "IVR DTMF ignored in current state"
            );
            return Ok(AppAction::Continue);
        };

        if is_greeting {
            // DTMF during greeting — barge-in if key is mapped
            let action = self
                .definition
                .get_menu(&menu_key)
                .and_then(|m| m.entries.iter().find(|e| e.key == digit))
                .map(|e| e.action.clone());

            if let Some(action) = action {
                info!(
                    ivr = %self.definition.name,
                    menu = %menu_key,
                    digit = %digit,
                    "IVR DTMF barge-in during greeting"
                );
                ctrl.cancel_timeout("ivr_dtmf_timeout");
                let _ = ctrl.stop_audio().await;
                self.execute_action(&action, ctrl, ctx).await
            } else {
                info!(
                    ivr = %self.definition.name,
                    menu = %menu_key,
                    digit = %digit,
                    "IVR DTMF ignored during greeting (no matching entry)"
                );
                Ok(AppAction::Continue)
            }
        } else {
            // WaitingDtmf — look up the entry for this digit
            let entry_action = self
                .definition
                .get_menu(&menu_key)
                .and_then(|m| m.entries.iter().find(|e| e.key == digit))
                .map(|e| {
                    debug!(
                        ivr = %self.definition.name,
                        menu = %menu_key,
                        digit = %digit,
                        label = e.label.as_deref().unwrap_or(""),
                        "DTMF matched"
                    );
                    e.action.clone()
                });

            if let Some(action) = entry_action {
                info!(
                    ivr = %self.definition.name,
                    menu = %menu_key,
                    digit = %digit,
                    "IVR DTMF matched entry, executing action"
                );
                self.execute_action(&action, ctrl, ctx).await
            } else if let Some(menu) = self.definition.get_menu(&menu_key) {
                // Check for unknown_key_action (e.g., direct extension dial)
                let unknown_action = menu.unknown_key_action.clone();
                if let Some(unknown_action) = unknown_action {
                    info!(
                        ivr = %self.definition.name,
                        menu = %menu_key,
                        digit = %digit,
                        "IVR DTMF not matched, executing unknown_key_action"
                    );
                    // Store the first digit for Collect actions
                    self.pending_unknown_digit = Some(digit.to_string());
                    self.execute_action(&unknown_action, ctrl, ctx).await
                } else {
                    info!(
                        ivr = %self.definition.name,
                        menu = %menu_key,
                        digit = %digit,
                        "IVR DTMF invalid key"
                    );
                    self.handle_invalid_key(&menu_key, retry_count, &digit, ctrl, ctx)
                        .await
                }
            } else {
                warn!(ivr = %self.definition.name, menu = %menu_key, "Menu not found during DTMF handling");
                self.state = IvrState::Done;
                Ok(AppAction::Hangup {
                    reason: None,
                    code: None,
                })
            }
        }
    }

    async fn on_audio_complete(
        &mut self,
        _track_id: String,
        ctrl: &mut CallController,
        _ctx: &ApplicationContext,
    ) -> anyhow::Result<AppAction> {
        // Extract string fields we need before the mutable borrows below.
        enum AudioDone {
            Greeting { menu_key: String },
            Invalid { menu_key: String, retry_count: u32 },
            Announcement { return_menu: String },
            Hangup,
            AndHangup { code: Option<u16> },
            Other,
        }

        let done = match &self.state {
            IvrState::PlayingGreeting { menu_key } => AudioDone::Greeting {
                menu_key: menu_key.clone(),
            },
            IvrState::PlayingInvalid {
                menu_key,
                retry_count,
            } => AudioDone::Invalid {
                menu_key: menu_key.clone(),
                retry_count: *retry_count,
            },
            IvrState::PlayingAnnouncement { return_menu } => AudioDone::Announcement {
                return_menu: return_menu.clone(),
            },
            IvrState::PlayingHangup => AudioDone::Hangup,
            IvrState::PlayingAndHangup { code } => AudioDone::AndHangup { code: *code },
            _ => AudioDone::Other,
        };

        match done {
            AudioDone::Greeting { menu_key } => {
                let retry_count = self.pending_retry_count;
                self.pending_retry_count = 0;
                info!(
                    ivr = %self.definition.name,
                    menu = %menu_key,
                    retry_count,
                    "IVR greeting complete, waiting DTMF"
                );
                self.start_waiting_dtmf(&menu_key, retry_count, ctrl);
                Ok(AppAction::Continue)
            }
            AudioDone::Invalid {
                menu_key,
                retry_count,
            } => {
                // Invalid prompt finished → re-play greeting
                info!(
                    ivr = %self.definition.name,
                    menu = %menu_key,
                    retry_count,
                    "IVR invalid prompt complete, replaying greeting"
                );
                let menu = self.definition.get_menu(&menu_key).cloned();
                if let Some(menu) = menu {
                    self.state = IvrState::PlayingGreeting {
                        menu_key: menu_key.clone(),
                    };
                    self.pending_retry_count = retry_count;
                    if let Some(path) = self
                        .resolve_audio(
                            Some(&menu.greeting),
                            menu.greeting_text.as_deref(),
                            menu.greeting_voice.as_deref(),
                        )
                        .await
                    {
                        ctrl.play_audio(&path, false).await?;
                    } else {
                        self.start_waiting_dtmf(&menu_key, retry_count, ctrl);
                    }
                }
                Ok(AppAction::Continue)
            }
            AudioDone::Announcement { return_menu } => {
                info!(
                    ivr = %self.definition.name,
                    return_menu = %return_menu,
                    "IVR announcement complete, returning to menu"
                );
                self.enter_menu(&return_menu, ctrl, _ctx).await
            }
            AudioDone::Hangup => {
                info!(ivr = %self.definition.name, "IVR hangup prompt complete, hanging up");
                self.state = IvrState::Done;
                Ok(AppAction::Hangup {
                    reason: None,
                    code: None,
                })
            }
            AudioDone::AndHangup { code } => {
                info!(ivr = %self.definition.name, code = ?code, "IVR prompt complete, hanging up with code");
                self.state = IvrState::Done;
                Ok(AppAction::Hangup { reason: None, code })
            }
            AudioDone::Other => Ok(AppAction::Continue),
        }
    }

    async fn on_timeout(
        &mut self,
        timeout_id: String,
        ctrl: &mut CallController,
        ctx: &ApplicationContext,
    ) -> anyhow::Result<AppAction> {
        if timeout_id != "ivr_dtmf_timeout" {
            return Ok(AppAction::Continue);
        }

        let waiting = match &self.state {
            IvrState::WaitingDtmf {
                menu_key,
                retry_count,
            } => Some((menu_key.clone(), *retry_count)),
            _ => None,
        };

        if let Some((menu_key, retry_count)) = waiting {
            info!(
                ivr = %self.definition.name,
                menu = %menu_key,
                retry_count,
                "IVR DTMF timeout fired"
            );
            self.handle_timeout(menu_key, retry_count, ctrl, ctx).await
        } else {
            Ok(AppAction::Continue)
        }
    }
}