cal-core 0.2.158

Callable core lib
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
// Filename cal-core/src/device/device.rs

use crate::{AsrVendor, ConnectState, FlowState, Region, VoiceServer};
use std::fmt::{Debug, Formatter};
use std::sync::Arc;

use cal_jambonz::dial::TranscribeDial;
use cal_jambonz::listen::Listen;

pub use crate::device::ani_router::ANIRouter;
pub use crate::device::app_flow::AppFlow;
pub use crate::device::client::Client;
pub use crate::device::date_range_router::DateRangeRouter;
pub use crate::device::day_of_week_router::DayOfWeekRouter;
pub use crate::device::digit_router::DigitRouter;
pub use crate::device::dnis_router::DNISRouter;
pub use crate::device::email::Email;
pub use crate::device::event::Event;
pub use crate::device::hunt_group::HuntGroup;
pub use crate::device::inbound_flow::InboundFlow;
pub use crate::device::message_ani_router::MessageAniRouter;
pub use crate::device::message_buttons::MessageButtons;
pub use crate::device::message_dnis_router::MessageDnisRouter;
pub use crate::device::message_plugin::MessagePlugin;
pub use crate::device::message_template::MessageTemplate;
pub use crate::device::message_text::MessageText;
pub use crate::device::outbound_flow::OutboundFlow;
pub use crate::device::play::Play;
pub use crate::device::plugin::Plugin;
pub use crate::device::queue::Queue;
pub use crate::device::remote::Remote;
pub use crate::device::say::Say;
pub use crate::device::service::Service;
pub use crate::device::shared::{RecordOptions, TranscribeOptions};
pub use crate::device::sip_extension::SipExtension;
pub use crate::device::sip_gateway::SipGateway;
pub use crate::device::sms::Sms;
pub use crate::device::tag_router::TagRouter;
pub use crate::device::teams::Teams;
pub use crate::device::time_range_router::TimeRangeRouter;
pub use crate::device::voicemail::VoiceMail;
pub use crate::device::whatsapp_flow::WhatsAppFlow;
pub use crate::zone_router::ZoneRouter;
use serde::{Deserialize, Deserializer, Serialize};
use serde_json::Value;
#[cfg(feature = "openapi")]
use utoipa::{ToSchema, IntoParams};

use crate::script::Script;
use crate::tag::Tag;

pub trait Connector {
    fn get_connect_to(&mut self, state: &mut FlowState) -> ConnectState;

    // Default implementation indicates this is not an endpoint
    fn is_endpoint(&self) -> bool {
        false
    }

    // Whether this device can route to other devices when in connector mode
    fn supports_routing(&self) -> bool {
        true
    }
}

pub trait BaseDevice {
    fn get_id(&mut self) -> String;
    fn get_name(&mut self) -> String;
    fn get_extension(&mut self) -> u16;
}

/// Type of device in the telephony system
#[derive(Serialize, Deserialize, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "openapi", derive(ToSchema))]
#[cfg_attr(feature = "openapi", schema(
    title ="Enumeration of all available device types in the system",
    example = "CLIENT"
))]
pub enum DeviceType {
    /// Inbound call flow starting point
    #[serde(rename = "ROUTE_START")]
    InboundFlow,

    /// Outbound call flow with pattern matching
    #[serde(rename = "MATCH_START")]
    OutboundFlow,

    /// WhatsApp messaging flow
    #[serde(rename = "WHATSAPP_START")]
    WhatsAppFlow,

    /// Application flow entry point
    #[serde(rename = "APP_START")]
    AppFlow,

    /// Routes based on caller ID (ANI)
    #[serde(rename = "ANI_ROUTER")]
    AniRouter,

    /// Routes based on called number (DNIS)
    #[serde(rename = "DNIS_ROUTER")]
    DnisRouter,

    /// Routes based on geographic zone
    #[serde(rename = "ZONE_ROUTER")]
    ZoneRouter,

    /// Routes based on digit input
    #[serde(rename = "NUMBER_PLAN")]
    DigitRouter,

    /// Routes based on time ranges
    #[serde(rename = "TIME_RANGE_ROUTER")]
    TimeRangeRouter,

    /// Routes based on day of week
    #[serde(rename = "DAY_OF_WEEK_ROUTER")]
    DayOfWeekRouter,

    /// Routes based on date ranges
    #[serde(rename = "DATE_RANGE_ROUTER")]
    DateRangeRouter,

    /// Hunt group for distributing calls
    #[serde(rename = "HUNT_GROUP")]
    HuntGroup,

    /// Client endpoint device
    #[serde(rename = "CLIENT")]
    Client,

    /// Microsoft Teams integration
    #[serde(rename = "TEAMS")]
    Teams,

    /// SIP extension endpoint
    #[serde(rename = "SIP")]
    SipExtension,

    /// SIP gateway for external connectivity
    #[serde(rename = "SIP_GATEWAY")]
    SipGateway,

    /// Remote endpoint
    #[serde(rename = "REMOTE")]
    Remote,

    /// Plugin for custom functionality
    #[serde(rename = "PLUGIN")]
    Plugin,

    /// Play audio file
    #[serde(rename = "PLAY")]
    Play,

    /// Text-to-speech
    #[serde(rename = "SAY")]
    Say,

    /// Voicemail system
    #[serde(rename = "VOICEMAIL")]
    Voicemail,

    /// Custom script execution
    #[serde(rename = "SCRIPT")]
    Script,

    /// Call queue
    #[serde(rename = "QUEUE")]
    Queue,

    /// SMS messaging
    #[serde(rename = "SMS")]
    Sms,

    /// Email integration
    #[serde(rename = "EMAIL")]
    Email,

    /// Tag assignment
    #[serde(rename = "TAG")]
    Tag,

    /// Routes based on tags
    #[serde(rename = "TAG_ROUTER")]
    TagRouter,

    /// Message plugin for custom messaging
    #[serde(rename = "MESSAGE_PLUGIN")]
    MessagePlugin,

    /// Simple text message
    #[serde(rename = "MESSAGE_TEXT")]
    MessageText,

    /// Interactive message buttons
    #[serde(rename = "MESSAGE_BUTTONS")]
    MessageButtons,

    /// Message template
    #[serde(rename = "MESSAGE_TEMPLATE")]
    MessageTemplate,

    /// Message routing based on ANI
    #[serde(rename = "MESSAGE_ANI_ROUTER")]
    MessageAniRouter,

    /// Service endpoint
    #[serde(rename = "SERVICE")]
    Service,
}

/// Polymorphic device representation
#[derive(Serialize, Deserialize, Clone)]
#[serde(untagged)]
pub enum Device {
    InboundFlow(InboundFlow),
    OutboundFlow(OutboundFlow),
    WhatsAppFlow(WhatsAppFlow),
    AppFlow(AppFlow),
    AniRouter(ANIRouter),
    DnisRouter(DNISRouter),
    DigitRouter(DigitRouter),
    TimeRangeRouter(TimeRangeRouter),
    DayOfWeekRouter(DayOfWeekRouter),
    DateRangeRouter(DateRangeRouter),
    ZoneRouter(ZoneRouter),
    HuntGroup(HuntGroup),
    Client(Client),
    Teams(Teams),
    SipExtension(SipExtension),
    SipGateway(SipGateway),
    Remote(Remote),
    Plugin(Plugin),
    Play(Play),
    Say(Say),
    Voicemail(VoiceMail),
    Script(Script),
    Queue(Queue),
    Sms(Sms),
    Email(Email),
    Tag(Tag),
    TagRouter(TagRouter),
    MessagePlugin(MessagePlugin),
    MessageButtons(MessageButtons),
    MessageText(MessageText),
    MessageTemplate(MessageTemplate),
    MessageAniRouter(MessageAniRouter),
    Service(Service),
}

/// Complete device configuration structure
#[derive(Serialize, Deserialize, Clone)]
#[cfg_attr(feature = "openapi", derive(ToSchema))]
#[cfg_attr(feature = "openapi", schema(
    title ="Device configuration containing all possible device types and their settings",
    example = json!({
        "_id": "dev_507f1f77bcf86cd799439011",
        "type": "CLIENT",
        "name": "John's Desk Phone",
        "extension": 1001,
        "tags": [
            {
                "type": "session",
                "name": "department",
                "value": "sales"
            }
        ],
        "client": {
            "username": "john.doe",
            "password": "encrypted_password",
            "realm": "sip.example.com"
        }
    })
))]
#[serde(rename_all = "camelCase")]
pub struct DeviceStruct {
    /// Unique device identifier
    #[serde(rename = "_id")]
    #[cfg_attr(feature = "openapi", schema(example = "dev_507f1f77bcf86cd799439011"))]
    pub id: String,

    /// Type of device
    #[serde(rename = "type")]
    pub device_type: DeviceType,

    /// Display name for the device
    #[cfg_attr(feature = "openapi", schema(example = "Reception Phone", min_length = 1))]
    pub name: String,

    /// Extension number
    #[serde(deserialize_with = "from_str")]
    #[cfg_attr(feature = "openapi", schema(example = 1001, minimum = 1, maximum = 9999))]
    pub extension: u16,

    /// Tags associated with the device
    #[serde(default)]
    pub tags: Vec<DeviceTag>,

    /// Inbound flow configuration
    #[serde(rename = "startRoute")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub start_route: Option<InboundFlow>,

    /// Outbound flow configuration
    #[serde(rename = "regexRoute")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub regex_route: Option<OutboundFlow>,

    /// Application flow configuration
    #[serde(rename = "appRoute")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub app_route: Option<AppFlow>,

    /// Digit router configuration
    #[serde(rename = "numberPlan")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub number_plan: Option<DigitRouter>,

    /// ANI router configuration
    #[serde(rename = "aniRouter")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub ani_router: Option<ANIRouter>,

    /// DNIS router configuration
    #[serde(rename = "dnisRouter")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub dnis_router: Option<DNISRouter>,

    /// Zone router configuration
    #[serde(rename = "zoneRouter")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub zone_router: Option<ZoneRouter>,

    /// Tag router configuration
    #[serde(rename = "tagRouter")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub tag_router: Option<TagRouter>,

    /// Time range router configuration
    #[serde(rename = "timeRangeRoute")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub time_range_router: Option<TimeRangeRouter>,

    /// Day of week router configuration
    #[serde(rename = "dayOfWeekRoute")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub day_of_week_router: Option<DayOfWeekRouter>,

    /// Date range router configuration
    #[serde(rename = "dateRangeRoute")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub date_range_router: Option<DateRangeRouter>,

    /// Hunt group configuration
    #[serde(rename = "huntGroup")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub hunt_group: Option<HuntGroup>,

    /// Client device configuration
    #[serde(rename = "client")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub client: Option<Client>,

    /// Teams integration configuration
    #[serde(rename = "teams")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub teams: Option<Teams>,

    /// SIP extension configuration
    #[serde(rename = "sipExtension")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub sip_extension: Option<SipExtension>,

    /// SIP gateway configuration
    #[serde(rename = "sipGateway")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub sip_gateway: Option<SipGateway>,

    /// Remote endpoint configuration
    #[serde(rename = "remote")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub remote: Option<Remote>,

    /// Voicemail configuration
    #[serde(rename = "voicemail")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub voice_mail: Option<VoiceMail>,

    /// Queue configuration
    #[serde(rename = "queue")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub queue: Option<Queue>,

    /// Plugin configuration
    #[serde(rename = "plugin")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub plugin: Option<Plugin>,

    /// Service configuration
    #[serde(rename = "service")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub service: Option<Service>,

    /// Play audio configuration
    #[serde(rename = "play")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub play: Option<Play>,

    /// Text-to-speech configuration
    #[serde(rename = "say")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub say: Option<Say>,

    /// Script configuration
    #[serde(rename = "script")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub script: Option<Script>,

    /// Email configuration
    #[serde(rename = "email")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub email: Option<Email>,

    /// SMS configuration
    #[serde(rename = "sms")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub sms: Option<Sms>,

    /// Tag configuration
    #[serde(rename = "tag")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub tag: Option<Tag>,

    /// Event configuration
    #[serde(rename = "event")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub event: Option<Event>,

    /// WhatsApp flow configuration
    #[serde(rename = "whatsAppRoute")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub whats_app_flow: Option<WhatsAppFlow>,

    /// Message plugin configuration
    #[serde(rename = "messagePlugin")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub message_plugin: Option<MessagePlugin>,

    /// Message text configuration
    #[serde(rename = "messageText")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub message_text: Option<MessageText>,

    /// Message buttons configuration
    #[serde(rename = "messageButtons")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub message_buttons: Option<MessageButtons>,

    /// Message template configuration
    #[serde(rename = "messageTemplate")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub message_template: Option<MessageTemplate>,

    /// Message ANI router configuration
    #[serde(rename = "messageANIRouter")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub message_ani_router: Option<MessageAniRouter>,

    /// Message DNIS router configuration
    #[serde(rename = "messageDNISRouter")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub message_dnis_router: Option<MessageDnisRouter>,
}

/// Custom deserializer for extension field
fn from_str<'de, D>(deserializer: D) -> Result<u16, D::Error>
where
    D: Deserializer<'de>,
{
    let value = Value::deserialize(deserializer)?;
    if value.is_string() {
        Ok(value.as_str().unwrap().parse().unwrap())
    } else if value.is_u64() {
        Ok(value.as_u64().unwrap() as u16)
    } else if value.is_i64() {
        Ok(value.as_i64().unwrap() as u16)
    } else {
        Err(serde::de::Error::custom("Cannot map extension to u16"))
    }
}

impl DeviceStruct {
    /// Get recording options based on device type
    pub fn record_options(&self) -> Option<RecordOptions> {
        match &self.device_type {
            DeviceType::HuntGroup => self.hunt_group.as_ref().map(|h| h.record_options.clone()),
            DeviceType::Client => self.client.as_ref().map(|c| c.record_options.clone()),
            DeviceType::Teams => self.teams.as_ref().map(|t| t.record_options.clone()),
            DeviceType::SipExtension => self.sip_extension.as_ref().map(|s| s.record_options.clone()),
            DeviceType::SipGateway => self.sip_gateway.as_ref().map(|s| s.record_options.clone()),
            DeviceType::Remote => self.remote.as_ref().map(|r| r.record_options.clone()),
            DeviceType::Plugin => self.plugin.as_ref().map(|p| p.record_options.clone()),
            DeviceType::Voicemail => self.voice_mail.as_ref().map(|v| v.record_options.clone()),
            _ => None,
        }
    }

    /// Get transcription options based on device type
    pub fn transcribe_options(&self) -> Option<TranscribeOptions> {
        match &self.device_type {
            DeviceType::HuntGroup => self.hunt_group.as_ref().map(|h| h.transcribe_options.clone()),
            DeviceType::Client => self.client.as_ref().map(|c| c.transcribe_options.clone()),
            DeviceType::Teams => self.teams.as_ref().map(|t| t.transcribe_options.clone()),
            DeviceType::SipExtension => self.sip_extension.as_ref().map(|s| s.transcribe_options.clone()),
            DeviceType::SipGateway => self.sip_gateway.as_ref().map(|s| s.transcribe_options.clone()),
            DeviceType::Remote => self.remote.as_ref().map(|r| r.transcribe_options.clone()),
            DeviceType::Plugin => self.plugin.as_ref().map(|p| p.transcribe_options.clone()),
            DeviceType::Voicemail => self.voice_mail.as_ref().map(|v| v.transcribe_options.clone()),
            _ => None,
        }
    }

    /// Check if device has the given ID
    pub fn is_id(&self, _id: &str) -> bool {
        self.id == _id
    }

    /// Check if device is of the given type
    pub fn is_device_type(&self, device_type: DeviceType) -> bool {
        self.device_type == device_type
    }

    /// Match device by various identifiers
    pub fn match_device(&self, str: &str) -> bool {
        let matched = match &self.device_type {
            DeviceType::InboundFlow => {
                self.start_route
                    .as_ref()
                    .map_or(false, |v| v.ddis.contains(&str.to_string()))
            }
            DeviceType::Client => {
                self.client
                    .as_ref()
                    .map_or(false, |v| v.username.eq(str))
            }
            DeviceType::SipGateway => {
                self.sip_gateway
                    .as_ref()
                    .map_or(false, |v| v.trunks.contains(&str.to_string()))
            }
            _ => false,
        };

        matched || self.id.eq(str) || self.extension.to_string().eq(str)
    }

    /// Check if this is an outbound flow device
    pub fn match_outbound_flow(&self) -> bool {
        match &self.device_type {
            DeviceType::OutboundFlow => true,
            _ => false,
        }
    }

    /// Check if device acts as a connector
    pub fn is_connector(&self) -> bool {
        vec![
            DeviceType::InboundFlow,
            DeviceType::OutboundFlow,
            DeviceType::AppFlow,
            DeviceType::WhatsAppFlow,
            DeviceType::AniRouter,
            DeviceType::DnisRouter,
            DeviceType::DigitRouter,
            DeviceType::TimeRangeRouter,
            DeviceType::DayOfWeekRouter,
            DeviceType::DateRangeRouter,
            DeviceType::Play,
            DeviceType::Say,
            DeviceType::Voicemail,
            DeviceType::Script,
            DeviceType::Queue,
            DeviceType::Sms,
            DeviceType::Email,
            DeviceType::Tag,
            DeviceType::TagRouter,
            DeviceType::Service,
        ]
            .contains(&self.device_type)
    }

    /// Check if device handles calls
    pub fn is_call_handler(&self) -> bool {
        vec![
            DeviceType::HuntGroup,
            DeviceType::Client,
            DeviceType::Teams,
            DeviceType::SipExtension,
            DeviceType::SipGateway,
            DeviceType::Remote,
            DeviceType::Plugin,
        ]
            .contains(&self.device_type)
    }
}

/// Tag associated with a device
#[derive(Serialize, Deserialize, Clone)]
#[cfg_attr(feature = "openapi", derive(ToSchema))]
#[cfg_attr(feature = "openapi", schema(
    title ="Tag for categorizing and routing devices",
    example = json!({
        "type": "session",
        "name": "department",
        "value": "sales"
    })
))]
#[serde(rename_all = "camelCase")]
pub struct DeviceTag {
    /// Type of tag (session or global)
    #[serde(rename = "type")]
    pub tag_type: TagType,

    /// Tag name/key
    #[cfg_attr(feature = "openapi", schema(example = "department"))]
    pub name: String,

    /// Tag value
    #[cfg_attr(feature = "openapi", schema(example = "sales"))]
    pub value: String,
}

/// Tag scope type
#[derive(Serialize, Deserialize, Eq, PartialEq, Clone)]
#[cfg_attr(feature = "openapi", derive(ToSchema))]
#[cfg_attr(feature = "openapi", schema(
    title ="Scope of the tag - session-specific or globally available"
))]
#[serde(rename_all = "camelCase")]
pub enum TagType {
    /// Tag persists for the session only
    Session,
    /// Tag is globally available
    Global,
}

pub trait Endpoint {
    fn get_caller_id(&self, state: &FlowState) -> String {
        state.initial_request.from.clone()
    }
    fn get_called_id(&self, state: &FlowState) -> String {
        state.initial_request.to.clone()
    }
    fn get_listen(&self, state: &FlowState) -> Option<Listen>;
    fn get_proxy(&self, _state: &FlowState, _regions:Vec<Arc<Region>>) -> Option<VoiceServer> {
        None
    }
    fn get_transcribe(&self, _state: &FlowState) -> Option<TranscribeDial> {
        None
    }
}

// New trait for endpoint devices that can terminate calls
pub trait EndpointDevice: Connector {
    fn is_endpoint(&self) -> bool {
        true
    }

    // This method returns the device type name for logging
    fn device_type_name(&self) -> &'static str;

    // Whether this endpoint can also act as a connector (for post-dial routing)
    fn supports_routing(&self) -> bool {
        false
    }
}

//DEBUG

// DeviceType Debug Implementation
impl Debug for DeviceType {
    fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), std::fmt::Error> {
        match self {
            DeviceType::InboundFlow => write!(f, "InboundFlow"),
            DeviceType::OutboundFlow => write!(f, "OutboundFlow"),
            DeviceType::WhatsAppFlow => write!(f, "WhatsAppFlow"),
            DeviceType::AppFlow => write!(f, "AppFlow"),
            DeviceType::AniRouter => write!(f, "AniRouter"),
            DeviceType::DnisRouter => write!(f, "DnisRouter"),
            DeviceType::DigitRouter => write!(f, "DigitRouter"),
            DeviceType::TimeRangeRouter => write!(f, "TimeRangeRouter"),
            DeviceType::DayOfWeekRouter => write!(f, "DayOfWeekRouter"),
            DeviceType::DateRangeRouter => write!(f, "DateRangeRouter"),
            DeviceType::ZoneRouter => write!(f, "ZoneRouter"),
            DeviceType::HuntGroup => write!(f, "HuntGroup"),
            DeviceType::Client => write!(f, "Client"),
            DeviceType::Teams => write!(f, "Teams"),
            DeviceType::SipExtension => write!(f, "SipExtension"),
            DeviceType::SipGateway => write!(f, "SipGateway"),
            DeviceType::Remote => write!(f, "Remote"),
            DeviceType::Plugin => write!(f, "Plugin"),
            DeviceType::Play => write!(f, "Play"),
            DeviceType::Say => write!(f, "Say"),
            DeviceType::Voicemail => write!(f, "Voicemail"),
            DeviceType::Script => write!(f, "Script"),
            DeviceType::Queue => write!(f, "Queue"),
            DeviceType::Sms => write!(f, "Sms"),
            DeviceType::Email => write!(f, "Email"),
            DeviceType::Tag => write!(f, "Tag"),
            DeviceType::TagRouter => write!(f, "TagRouter"),
            DeviceType::MessagePlugin => write!(f, "MessagePlugin"),
            DeviceType::MessageText => write!(f, "MessageText"),
            DeviceType::MessageButtons => write!(f, "MessageButtons"),
            DeviceType::MessageTemplate => write!(f, "MessageTemplate"),
            DeviceType::MessageAniRouter => write!(f, "MessageAniRouter"),
            DeviceType::Service => write!(f, "Service"),
        }
    }
}

// Device Enum Debug Implementation
impl Debug for Device {
    fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), std::fmt::Error> {
        match self {
            Device::InboundFlow(_) => write!(f, "Device::InboundFlow"),
            Device::OutboundFlow(_) => write!(f, "Device::OutboundFlow"),
            Device::WhatsAppFlow(_) => write!(f, "Device::WhatsAppFlow"),
            Device::AppFlow(_) => write!(f, "Device::AppFlow"),
            Device::AniRouter(_) => write!(f, "Device::AniRouter"),
            Device::DnisRouter(_) => write!(f, "Device::DnisRouter"),
            Device::DigitRouter(_) => write!(f, "Device::DigitRouter"),
            Device::TimeRangeRouter(_) => write!(f, "Device::TimeRangeRouter"),
            Device::DayOfWeekRouter(_) => write!(f, "Device::DayOfWeekRouter"),
            Device::DateRangeRouter(_) => write!(f, "Device::DateRangeRouter"),
            Device::ZoneRouter(_) => write!(f, "Device::ZoneRouter"),
            Device::HuntGroup(_) => write!(f, "Device::HuntGroup"),
            Device::Client(_) => write!(f, "Device::Client"),
            Device::Teams(_) => write!(f, "Device::Teams"),
            Device::SipExtension(_) => write!(f, "Device::SipExtension"),
            Device::SipGateway(_) => write!(f, "Device::SipGateway"),
            Device::Remote(_) => write!(f, "Device::Remote"),
            Device::Plugin(_) => write!(f, "Device::Plugin"),
            Device::Play(_) => write!(f, "Device::Play"),
            Device::Say(_) => write!(f, "Device::Say"),
            Device::Voicemail(_) => write!(f, "Device::Voicemail"),
            Device::Script(_) => write!(f, "Device::Script"),
            Device::Queue(_) => write!(f, "Device::Queue"),
            Device::Sms(_) => write!(f, "Device::Sms"),
            Device::Email(_) => write!(f, "Device::Email"),
            Device::Tag(_) => write!(f, "Device::Tag"),
            Device::TagRouter(_) => write!(f, "Device::TagRouter"),
            Device::MessagePlugin(_) => write!(f, "Device::MessagePlugin"),
            Device::MessageButtons(_) => write!(f, "Device::MessageButtons"),
            Device::MessageText(_) => write!(f, "Device::MessageText"),
            Device::MessageTemplate(_) => write!(f, "Device::MessageTemplate"),
            Device::MessageAniRouter(_) => write!(f, "Device::MessageAniRouter"),
            Device::Service(_) => write!(f, "Device::Service"),
        }
    }
}

// DeviceStruct Debug Implementation
impl Debug for DeviceStruct {
    fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), std::fmt::Error> {
        f.debug_struct("DeviceStruct")
            .field("id", &self.id)
            .field("device_type", &self.device_type)
            .field("name", &self.name)
            .field("extension", &self.extension)
            .finish_non_exhaustive()
    }
}

// TagType Debug Implementation
impl Debug for TagType {
    fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), std::fmt::Error> {
        match self {
            TagType::Session => write!(f, "Session"),
            TagType::Global => write!(f, "Global"),
        }
    }
}

// DeviceTag Debug Implementation
impl Debug for DeviceTag {
    fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), std::fmt::Error> {
        f.debug_struct("DeviceTag")
            .field("tag_type", &self.tag_type)
            .field("name", &self.name)
            .field("value", &self.value)
            .finish()
    }
}

// RecordOptions Debug Implementation
impl Debug for RecordOptions {
    fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), std::fmt::Error> {
        f.debug_struct("RecordOptions")
            .field("enabled", &self.enabled)
            .field("retention", &self.retention)
            .field("mix_type", &self.mix_type)
            .field("sample_rate", &self.sample_rate)
            .finish()
    }
}

// TranscribeOptions Debug Implementation
impl Debug for TranscribeOptions {
    fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), std::fmt::Error> {
        f.debug_struct("TranscribeOptions")
            .field("enabled", &self.enabled)
            .field("language", &self.language)
            .finish()
    }
}

// AsrVendor Debug Implementation
impl Debug for AsrVendor {
    fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), std::fmt::Error> {
        match self {
            AsrVendor::Google => write!(f, "Google"),
            AsrVendor::Deepgram => write!(f, "DeepGram"),
            AsrVendor::Microsoft => write!(f, "Microsoft"),
            AsrVendor::Aws => write!(f, "Aws"),
            AsrVendor::Ibm => write!(f, "Ibm"),
            AsrVendor::Nuance => write!(f, "Nuance"),
            AsrVendor::Nvidia =>write!(f, "Nvidia"),
            AsrVendor::Soniox => write!(f, "Soniox"),
        }
    }
}