zeptoclaw 0.7.3

Ultra-lightweight personal AI assistant
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
//! WhatsApp channel implementation (via whatsmeow-rs bridge).
//!
//! Connects to an external whatsmeow-rs bridge binary over WebSocket.
//! The bridge handles WhatsApp protocol complexity (E2E encryption, QR pairing,
//! session persistence). ZeptoClaw just consumes/sends JSON messages.
//!
//! # Bridge Protocol (JSON over WebSocket)
//!
//! Inbound (bridge → ZeptoClaw):
//! ```json
//! {"type":"message","from":"60123456789","chat_id":"60123456789@s.whatsapp.net","content":"Hello","message_id":"wamid.xyz","timestamp":1707900000,"sender_name":"John"}
//! {"type":"connected"}
//! {"type":"disconnected","reason":"session expired"}
//! {"type":"qr_code","data":"2@base64data"}
//! ```
//!
//! Outbound (ZeptoClaw → bridge):
//! ```json
//! {"type":"send","to":"60123456789@s.whatsapp.net","content":"Reply text","reply_to":"wamid.xyz"}
//! ```

use async_trait::async_trait;
use futures::{FutureExt, SinkExt, StreamExt};
use serde::{Deserialize, Serialize};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
use std::time::Duration;
use tokio::sync::{mpsc, watch};
use tokio_tungstenite::connect_async;
use tokio_tungstenite::tungstenite::Message as WsMessage;
use tracing::{debug, error, info, warn};

use crate::bus::{InboundMessage, MediaAttachment, MediaType, MessageBus, OutboundMessage};
use crate::config::WhatsAppConfig;
use crate::deps::{DepKind, Dependency, HasDependencies, HealthCheck};
use crate::error::{Result, ZeptoError};

use super::{BaseChannelConfig, Channel};

// ---------------------------------------------------------------------------
// Constants
// ---------------------------------------------------------------------------

/// Maximum reconnect delay (in seconds) for exponential backoff.
const MAX_RECONNECT_DELAY_SECS: u64 = 120;
/// Base reconnect delay (in seconds).
const BASE_RECONNECT_DELAY_SECS: u64 = 2;
/// Maximum number of consecutive reconnect attempts before resetting backoff.
const MAX_RECONNECT_ATTEMPTS: u32 = 10;

// ---------------------------------------------------------------------------
// Bridge protocol types
// ---------------------------------------------------------------------------

/// Inbound message from the whatsmeow-rs bridge.
#[derive(Debug, Deserialize)]
struct BridgeMessage {
    /// Message type: "message", "connected", "disconnected", "qr_code", etc.
    #[serde(rename = "type")]
    msg_type: String,
    /// Sender phone number (message type only).
    #[serde(default)]
    from: Option<String>,
    /// WhatsApp chat JID (e.g. "60123456789@s.whatsapp.net").
    #[serde(default)]
    chat_id: Option<String>,
    /// Message text content.
    #[serde(default)]
    content: Option<String>,
    /// WhatsApp message ID.
    #[serde(default)]
    message_id: Option<String>,
    /// Unix timestamp.
    #[serde(default)]
    timestamp: Option<u64>,
    /// Sender display name.
    #[serde(default)]
    sender_name: Option<String>,
    /// Disconnect reason (disconnected type only).
    #[serde(default)]
    reason: Option<String>,
    /// QR code data (qr_code type only).
    #[serde(default)]
    #[allow(dead_code)]
    data: Option<String>,
    /// Base64-encoded media data (image messages).
    #[serde(default)]
    media_base64: Option<String>,
    /// MIME type of the media (e.g. "image/jpeg").
    #[serde(default)]
    media_mime_type: Option<String>,
}

/// Outbound message to the whatsmeow-rs bridge.
#[derive(Debug, Serialize)]
struct BridgeSendMessage {
    /// Always "send".
    #[serde(rename = "type")]
    msg_type: String,
    /// Recipient chat JID.
    to: String,
    /// Message text content.
    content: String,
    /// Optional message ID to reply to.
    #[serde(skip_serializing_if = "Option::is_none")]
    reply_to: Option<String>,
}

// ---------------------------------------------------------------------------
// WhatsAppChannel
// ---------------------------------------------------------------------------

/// WhatsApp channel backed by the whatsmeow-rs bridge over WebSocket.
pub struct WhatsAppChannel {
    config: WhatsAppConfig,
    base_config: BaseChannelConfig,
    bus: Arc<MessageBus>,
    running: Arc<AtomicBool>,
    shutdown_tx: Option<watch::Sender<bool>>,
    outbound_tx: Option<mpsc::Sender<BridgeSendMessage>>,
}

impl WhatsAppChannel {
    /// Creates a new WhatsApp channel.
    pub fn new(config: WhatsAppConfig, bus: Arc<MessageBus>) -> Self {
        let base_config = BaseChannelConfig {
            name: "whatsapp".to_string(),
            allowlist: config.allow_from.clone(),
            deny_by_default: config.deny_by_default,
        };

        Self {
            config,
            base_config,
            bus,
            running: Arc::new(AtomicBool::new(false)),
            shutdown_tx: None,
            outbound_tx: None,
        }
    }

    /// Returns a reference to the WhatsApp configuration.
    pub fn whatsapp_config(&self) -> &WhatsAppConfig {
        &self.config
    }

    /// Returns whether the channel is enabled in configuration.
    pub fn is_enabled(&self) -> bool {
        self.config.enabled
    }

    // -----------------------------------------------------------------------
    // Bridge message parsing
    // -----------------------------------------------------------------------

    /// Parses a bridge "message" event into an `InboundMessage`, returning
    /// `None` if it should be ignored (empty content, disallowed user, etc.).
    fn parse_bridge_message(
        msg: &BridgeMessage,
        allowlist: &[String],
        deny_by_default: bool,
    ) -> Option<InboundMessage> {
        let from = msg.from.as_deref().unwrap_or("").trim().to_string();
        if from.is_empty() {
            return None;
        }

        let chat_id = msg.chat_id.as_deref().unwrap_or("").trim().to_string();
        if chat_id.is_empty() {
            return None;
        }

        let content = msg.content.as_deref().unwrap_or("").trim().to_string();
        if content.is_empty() {
            return None;
        }

        // Allowlist check with deny_by_default support (by phone number).
        let allowed = if allowlist.is_empty() {
            !deny_by_default
        } else {
            allowlist.contains(&from)
        };
        if !allowed {
            info!("WhatsApp: user {} not in allowlist, ignoring message", from);
            return None;
        }

        let mut inbound = InboundMessage::new("whatsapp", &from, &chat_id, &content);

        if let Some(ref mid) = msg.message_id {
            inbound = inbound.with_metadata("whatsapp_message_id", mid);
        }
        if let Some(ts) = msg.timestamp {
            inbound = inbound.with_metadata("timestamp", &ts.to_string());
        }
        if let Some(ref name) = msg.sender_name {
            inbound = inbound.with_metadata("sender_name", name);
        }

        // Decode and attach inline image data from the bridge
        if let Some(ref b64_data) = msg.media_base64 {
            use base64::Engine;
            if let Ok(bytes) = base64::engine::general_purpose::STANDARD.decode(b64_data) {
                if bytes.len() <= 20 * 1024 * 1024 {
                    let mime = msg.media_mime_type.as_deref().unwrap_or("image/jpeg");
                    if mime.starts_with("image/") {
                        let media = MediaAttachment::new(MediaType::Image)
                            .with_data(bytes)
                            .with_mime_type(mime);
                        inbound = inbound.with_media(media);
                    }
                }
            }
        }

        Some(inbound)
    }

    // -----------------------------------------------------------------------
    // Backoff calculation
    // -----------------------------------------------------------------------

    /// Calculates the exponential backoff delay for a given attempt number.
    fn backoff_delay(attempt: u32) -> Duration {
        let delay_secs = BASE_RECONNECT_DELAY_SECS
            .saturating_mul(2u64.saturating_pow(attempt))
            .min(MAX_RECONNECT_DELAY_SECS);
        Duration::from_secs(delay_secs)
    }

    // -----------------------------------------------------------------------
    // Error redaction
    // -----------------------------------------------------------------------

    /// Produce a safe log message for a WebSocket connection error.
    /// The tungstenite `Error` Debug representation may contain the full HTTP
    /// request including the `Authorization: Bearer <token>` header, so we
    /// must not log it verbatim.
    fn redact_ws_error(e: &tokio_tungstenite::tungstenite::Error) -> String {
        use tokio_tungstenite::tungstenite::Error as WsError;
        match e {
            WsError::ConnectionClosed => "connection closed".to_string(),
            WsError::AlreadyClosed => "already closed".to_string(),
            WsError::Io(io_err) => format!("IO error: {}", io_err.kind()),
            WsError::Tls(_) => "TLS error".to_string(),
            WsError::Capacity(msg) => format!("capacity: {}", msg),
            WsError::Protocol(p) => format!("protocol: {}", p),
            WsError::WriteBufferFull(_) => "write buffer full".to_string(),
            WsError::Utf8(_) => "UTF-8 error".to_string(),
            WsError::AttackAttempt => "attack attempt detected".to_string(),
            WsError::Url(u) => format!("URL error: {}", u),
            // Http variant may contain the full request with Authorization header.
            WsError::Http(resp) => format!("HTTP status {}", resp.status()),
            WsError::HttpFormat(_) => "HTTP format error".to_string(),
        }
    }

    // -----------------------------------------------------------------------
    // Bridge WebSocket loop
    // -----------------------------------------------------------------------

    /// Main bridge loop: connects via WebSocket, dispatches inbound messages,
    /// and sends outbound messages. Reconnects with exponential backoff.
    async fn run_bridge_loop(
        bridge_url: String,
        bridge_token: Option<String>,
        bus: Arc<MessageBus>,
        allowlist: Vec<String>,
        deny_by_default: bool,
        mut shutdown_rx: watch::Receiver<bool>,
        mut outbound_rx: mpsc::Receiver<BridgeSendMessage>,
    ) {
        let mut reconnect_attempt: u32 = 0;

        loop {
            // Check shutdown before each connection attempt.
            if *shutdown_rx.borrow() {
                info!("WhatsApp bridge loop shutdown requested");
                return;
            }

            // --- WebSocket connect ---
            let ws_stream = tokio::select! {
                _ = shutdown_rx.changed() => {
                    info!("WhatsApp bridge loop shutdown requested");
                    return;
                }
                result = async {
                    if let Some(ref token) = bridge_token {
                        // Build request with Authorization header.
                        let request = tokio_tungstenite::tungstenite::http::Request::builder()
                            .uri(&bridge_url)
                            .header("Authorization", format!("Bearer {}", token))
                            .header("Host", tokio_tungstenite::tungstenite::http::Uri::try_from(bridge_url.as_str())
                                .map(|u| u.host().unwrap_or("localhost").to_string())
                                .unwrap_or_else(|_| "localhost".to_string()))
                            .header("Connection", "Upgrade")
                            .header("Upgrade", "websocket")
                            .header("Sec-WebSocket-Version", "13")
                            .header("Sec-WebSocket-Key", tokio_tungstenite::tungstenite::handshake::client::generate_key())
                            .body(())
                            .expect("valid WebSocket request");
                        connect_async(request).await
                    } else {
                        connect_async(&bridge_url).await
                    }
                } => {
                    match result {
                        Ok((stream, _)) => stream,
                        Err(e) => {
                            // Redact the error to avoid leaking the bridge token.
                            // tungstenite may include the full HTTP request
                            // (with Authorization header) in error Debug output.
                            warn!("WhatsApp: bridge connect failed: {}", Self::redact_ws_error(&e));
                            let delay = Self::backoff_delay(reconnect_attempt);
                            reconnect_attempt =
                                (reconnect_attempt + 1).min(MAX_RECONNECT_ATTEMPTS);
                            tokio::select! {
                                _ = shutdown_rx.changed() => return,
                                _ = tokio::time::sleep(delay) => continue,
                            }
                        }
                    }
                }
            };

            info!("WhatsApp bridge WebSocket connected to {}", bridge_url);
            reconnect_attempt = 0;

            let (mut ws_writer, mut ws_reader) = ws_stream.split();

            // --- Main dispatch loop ---
            loop {
                tokio::select! {
                    _ = shutdown_rx.changed() => {
                        info!("WhatsApp bridge loop shutdown requested");
                        return;
                    }

                    // Forward outbound messages to bridge.
                    outbound = outbound_rx.recv() => {
                        match outbound {
                            Some(send_msg) => {
                                match serde_json::to_string(&send_msg) {
                                    Ok(json) => {
                                        if let Err(e) = ws_writer.send(WsMessage::Text(json.into())).await {
                                            warn!("WhatsApp: failed to send to bridge: {}", e);
                                            break;
                                        }
                                    }
                                    Err(e) => {
                                        error!("WhatsApp: failed to serialize outbound: {}", e);
                                    }
                                }
                            }
                            None => {
                                debug!("WhatsApp outbound channel closed");
                                break;
                            }
                        }
                    }

                    // Process incoming bridge events.
                    msg = ws_reader.next() => {
                        match msg {
                            Some(Ok(WsMessage::Text(raw))) => {
                                match serde_json::from_str::<BridgeMessage>(&raw) {
                                    Ok(bridge_msg) => {
                                        match bridge_msg.msg_type.as_str() {
                                            "message" => {
                                                if let Some(inbound) =
                                                    Self::parse_bridge_message(&bridge_msg, &allowlist, deny_by_default)
                                                {
                                                    if let Err(e) =
                                                        bus.publish_inbound(inbound).await
                                                    {
                                                        error!(
                                                            "Failed to publish WhatsApp inbound message: {}",
                                                            e
                                                        );
                                                    }
                                                }
                                            }
                                            "connected" => {
                                                info!("WhatsApp bridge: connected to WhatsApp");
                                            }
                                            "disconnected" => {
                                                let reason = bridge_msg
                                                    .reason
                                                    .as_deref()
                                                    .unwrap_or("unknown");
                                                warn!(
                                                    "WhatsApp bridge: disconnected (reason: {})",
                                                    reason
                                                );
                                                break; // Reconnect
                                            }
                                            "qr_code" => {
                                                info!(
                                                    "WhatsApp bridge: QR code received (display on bridge terminal)"
                                                );
                                            }
                                            other => {
                                                debug!(
                                                    "WhatsApp bridge: unknown message type '{}'",
                                                    other
                                                );
                                            }
                                        }
                                    }
                                    Err(e) => {
                                        debug!("WhatsApp: failed to parse bridge message: {}", e);
                                    }
                                }
                            }
                            Some(Ok(WsMessage::Ping(payload))) => {
                                if let Err(e) = ws_writer.send(WsMessage::Pong(payload)).await {
                                    warn!("WhatsApp: pong send failed: {}", e);
                                    break;
                                }
                            }
                            Some(Ok(WsMessage::Close(frame))) => {
                                info!("WhatsApp: bridge WebSocket closed: {:?}", frame);
                                break;
                            }
                            Some(Ok(_)) => {}
                            Some(Err(e)) => {
                                warn!("WhatsApp: bridge WebSocket error: {}", e);
                                break;
                            }
                            None => {
                                warn!("WhatsApp: bridge WebSocket stream ended");
                                break;
                            }
                        }
                    }
                }
            }

            // --- Wait before reconnecting ---
            let delay = Self::backoff_delay(reconnect_attempt);
            reconnect_attempt = (reconnect_attempt + 1).min(MAX_RECONNECT_ATTEMPTS);
            info!(
                "WhatsApp: reconnecting to bridge in {} seconds",
                delay.as_secs()
            );
            tokio::select! {
                _ = shutdown_rx.changed() => return,
                _ = tokio::time::sleep(delay) => {},
            }
        }
    }
}

// ---------------------------------------------------------------------------
// Channel trait implementation
// ---------------------------------------------------------------------------

#[async_trait]
impl Channel for WhatsAppChannel {
    fn name(&self) -> &str {
        "whatsapp"
    }

    async fn start(&mut self) -> Result<()> {
        if self.running.swap(true, Ordering::SeqCst) {
            info!("WhatsApp channel already running");
            return Ok(());
        }

        if !self.config.enabled {
            warn!("WhatsApp channel is disabled in configuration");
            self.running.store(false, Ordering::SeqCst);
            return Ok(());
        }

        let bridge_url = self.config.bridge_url.trim().to_string();
        if bridge_url.is_empty() {
            self.running.store(false, Ordering::SeqCst);
            return Err(ZeptoError::Config(
                "WhatsApp bridge URL is empty".to_string(),
            ));
        }

        let (shutdown_tx, shutdown_rx) = watch::channel(false);
        self.shutdown_tx = Some(shutdown_tx);

        let (outbound_tx, outbound_rx) = mpsc::channel(64);
        self.outbound_tx = Some(outbound_tx);

        info!("Starting WhatsApp channel with bridge at {}", bridge_url);
        let running_clone = Arc::clone(&self.running);
        let bridge_token = self.config.bridge_token.clone();
        let bus = Arc::clone(&self.bus);
        let allow_from = self.config.allow_from.clone();
        let deny_by_default = self.config.deny_by_default;
        tokio::spawn(async move {
            let task_result = std::panic::AssertUnwindSafe(async move {
                Self::run_bridge_loop(
                    bridge_url,
                    bridge_token,
                    bus,
                    allow_from,
                    deny_by_default,
                    shutdown_rx,
                    outbound_rx,
                )
                .await;
            })
            .catch_unwind()
            .await;
            if task_result.is_err() {
                error!("WhatsApp bridge task panicked");
            }
            running_clone.store(false, Ordering::SeqCst);
        });

        Ok(())
    }

    async fn stop(&mut self) -> Result<()> {
        if !self.running.swap(false, Ordering::SeqCst) {
            info!("WhatsApp channel already stopped");
            return Ok(());
        }

        if let Some(tx) = self.shutdown_tx.take() {
            let _ = tx.send(true);
        }
        self.outbound_tx = None;

        info!("WhatsApp channel stopped");
        Ok(())
    }

    async fn send(&self, msg: OutboundMessage) -> Result<()> {
        if !self.running.load(Ordering::SeqCst) {
            return Err(ZeptoError::Channel(
                "WhatsApp channel not running".to_string(),
            ));
        }

        let tx = self.outbound_tx.as_ref().ok_or_else(|| {
            ZeptoError::Channel("WhatsApp outbound channel not initialized".to_string())
        })?;

        let to = msg.chat_id.trim().to_string();
        if to.is_empty() {
            return Err(ZeptoError::Channel(
                "WhatsApp recipient chat ID cannot be empty".to_string(),
            ));
        }

        let send_msg = BridgeSendMessage {
            msg_type: "send".to_string(),
            to,
            content: msg.content.clone(),
            reply_to: msg.reply_to.clone(),
        };

        tx.send(send_msg).await.map_err(|e| {
            ZeptoError::Channel(format!("Failed to queue WhatsApp outbound message: {}", e))
        })?;

        info!("WhatsApp: message queued for sending");
        Ok(())
    }

    fn is_running(&self) -> bool {
        self.running.load(Ordering::SeqCst)
    }

    fn is_allowed(&self, user_id: &str) -> bool {
        self.base_config.is_allowed(user_id)
    }
}

impl HasDependencies for WhatsAppChannel {
    fn dependencies(&self) -> Vec<Dependency> {
        if !self.config.bridge_managed {
            return vec![];
        }

        vec![Dependency {
            name: "whatsmeow-bridge".to_string(),
            kind: DepKind::Binary {
                repo: "qhkm/whatsmeow-rs".to_string(),
                asset_pattern: "whatsmeow-bridge-{os}-{arch}".to_string(),
                version: String::new(), // latest
            },
            health_check: HealthCheck::WebSocket {
                url: self.config.bridge_url.clone(),
            },
            env: std::collections::HashMap::new(),
            args: vec![],
        }]
    }
}

// ===========================================================================
// Tests
// ===========================================================================

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

    fn test_bus() -> Arc<MessageBus> {
        Arc::new(MessageBus::new())
    }

    fn test_config() -> WhatsAppConfig {
        WhatsAppConfig {
            enabled: true,
            bridge_url: "ws://localhost:3001".to_string(),
            allow_from: vec!["60123456789".to_string()],
            bridge_managed: true,
            ..Default::default()
        }
    }

    // -----------------------------------------------------------------------
    // 1. Channel name
    // -----------------------------------------------------------------------
    #[test]
    fn test_channel_name() {
        let channel = WhatsAppChannel::new(test_config(), test_bus());
        assert_eq!(channel.name(), "whatsapp");
    }

    // -----------------------------------------------------------------------
    // 2. Config initialization
    // -----------------------------------------------------------------------
    #[test]
    fn test_config_initialization() {
        let config = WhatsAppConfig {
            enabled: true,
            bridge_url: "ws://bridge:3001".to_string(),
            allow_from: vec!["U1".to_string(), "U2".to_string()],
            bridge_managed: true,
            ..Default::default()
        };
        let channel = WhatsAppChannel::new(config, test_bus());

        assert!(channel.is_enabled());
        assert_eq!(channel.whatsapp_config().bridge_url, "ws://bridge:3001");
        assert_eq!(channel.whatsapp_config().allow_from.len(), 2);
        assert!(!channel.is_running());
    }

    // -----------------------------------------------------------------------
    // 3. is_allowed delegation
    // -----------------------------------------------------------------------
    #[test]
    fn test_is_allowed_delegation() {
        let channel = WhatsAppChannel::new(test_config(), test_bus());

        assert!(channel.is_allowed("60123456789"));
        assert!(!channel.is_allowed("999999999"));
    }

    #[test]
    fn test_is_allowed_empty_allowlist() {
        let config = WhatsAppConfig {
            enabled: true,
            bridge_url: "ws://localhost:3001".to_string(),
            allow_from: vec![],
            bridge_managed: true,
            ..Default::default()
        };
        let channel = WhatsAppChannel::new(config, test_bus());

        assert!(channel.is_allowed("anyone"));
        assert!(channel.is_allowed("literally_anyone"));
    }

    // -----------------------------------------------------------------------
    // 4. BridgeMessage deserialization
    // -----------------------------------------------------------------------
    #[test]
    fn test_bridge_message_deser_message_type() {
        let json = r#"{
            "type": "message",
            "from": "60123456789",
            "chat_id": "60123456789@s.whatsapp.net",
            "content": "Hello!",
            "message_id": "wamid.xyz",
            "timestamp": 1707900000,
            "sender_name": "John"
        }"#;
        let msg: BridgeMessage = serde_json::from_str(json).expect("should parse");

        assert_eq!(msg.msg_type, "message");
        assert_eq!(msg.from.as_deref(), Some("60123456789"));
        assert_eq!(msg.chat_id.as_deref(), Some("60123456789@s.whatsapp.net"));
        assert_eq!(msg.content.as_deref(), Some("Hello!"));
        assert_eq!(msg.message_id.as_deref(), Some("wamid.xyz"));
        assert_eq!(msg.timestamp, Some(1707900000));
        assert_eq!(msg.sender_name.as_deref(), Some("John"));
    }

    #[test]
    fn test_bridge_message_deser_connected() {
        let json = r#"{"type": "connected"}"#;
        let msg: BridgeMessage = serde_json::from_str(json).expect("should parse");
        assert_eq!(msg.msg_type, "connected");
        assert!(msg.from.is_none());
    }

    #[test]
    fn test_bridge_message_deser_disconnected() {
        let json = r#"{"type": "disconnected", "reason": "session expired"}"#;
        let msg: BridgeMessage = serde_json::from_str(json).expect("should parse");
        assert_eq!(msg.msg_type, "disconnected");
        assert_eq!(msg.reason.as_deref(), Some("session expired"));
    }

    #[test]
    fn test_bridge_message_deser_qr_code() {
        let json = r#"{"type": "qr_code", "data": "2@base64data"}"#;
        let msg: BridgeMessage = serde_json::from_str(json).expect("should parse");
        assert_eq!(msg.msg_type, "qr_code");
        assert_eq!(msg.data.as_deref(), Some("2@base64data"));
    }

    #[test]
    fn test_bridge_message_deser_unknown_type() {
        let json = r#"{"type": "future_event", "extra": true}"#;
        let msg: BridgeMessage = serde_json::from_str(json).expect("should parse");
        assert_eq!(msg.msg_type, "future_event");
    }

    // -----------------------------------------------------------------------
    // 5. parse_bridge_message
    // -----------------------------------------------------------------------
    #[test]
    fn test_parse_bridge_message_valid() {
        let msg = BridgeMessage {
            msg_type: "message".to_string(),
            from: Some("60123456789".to_string()),
            chat_id: Some("60123456789@s.whatsapp.net".to_string()),
            content: Some("Hello!".to_string()),
            message_id: Some("wamid.xyz".to_string()),
            timestamp: Some(1707900000),
            sender_name: Some("John".to_string()),
            reason: None,
            data: None,
            media_base64: None,
            media_mime_type: None,
        };

        let inbound = WhatsAppChannel::parse_bridge_message(&msg, &[], false);
        assert!(inbound.is_some());
        let inbound = inbound.unwrap();
        assert_eq!(inbound.channel, "whatsapp");
        assert_eq!(inbound.sender_id, "60123456789");
        assert_eq!(inbound.chat_id, "60123456789@s.whatsapp.net");
        assert_eq!(inbound.content, "Hello!");
        assert_eq!(
            inbound.metadata.get("whatsapp_message_id"),
            Some(&"wamid.xyz".to_string())
        );
        assert_eq!(
            inbound.metadata.get("timestamp"),
            Some(&"1707900000".to_string())
        );
        assert_eq!(
            inbound.metadata.get("sender_name"),
            Some(&"John".to_string())
        );
    }

    #[test]
    fn test_parse_bridge_message_allowlist_allowed() {
        let msg = BridgeMessage {
            msg_type: "message".to_string(),
            from: Some("60123456789".to_string()),
            chat_id: Some("60123456789@s.whatsapp.net".to_string()),
            content: Some("test".to_string()),
            message_id: None,
            timestamp: None,
            sender_name: None,
            reason: None,
            data: None,
            media_base64: None,
            media_mime_type: None,
        };

        let result =
            WhatsAppChannel::parse_bridge_message(&msg, &["60123456789".to_string()], false);
        assert!(result.is_some());
    }

    #[test]
    fn test_parse_bridge_message_allowlist_denied() {
        let msg = BridgeMessage {
            msg_type: "message".to_string(),
            from: Some("60123456789".to_string()),
            chat_id: Some("60123456789@s.whatsapp.net".to_string()),
            content: Some("test".to_string()),
            message_id: None,
            timestamp: None,
            sender_name: None,
            reason: None,
            data: None,
            media_base64: None,
            media_mime_type: None,
        };

        let result =
            WhatsAppChannel::parse_bridge_message(&msg, &["60999999999".to_string()], false);
        assert!(result.is_none());
    }

    #[test]
    fn test_parse_bridge_message_empty_content() {
        let msg = BridgeMessage {
            msg_type: "message".to_string(),
            from: Some("60123456789".to_string()),
            chat_id: Some("60123456789@s.whatsapp.net".to_string()),
            content: Some("   ".to_string()),
            message_id: None,
            timestamp: None,
            sender_name: None,
            reason: None,
            data: None,
            media_base64: None,
            media_mime_type: None,
        };

        let result = WhatsAppChannel::parse_bridge_message(&msg, &[], false);
        assert!(result.is_none());
    }

    #[test]
    fn test_parse_bridge_message_missing_from() {
        let msg = BridgeMessage {
            msg_type: "message".to_string(),
            from: None,
            chat_id: Some("60123456789@s.whatsapp.net".to_string()),
            content: Some("Hello".to_string()),
            message_id: None,
            timestamp: None,
            sender_name: None,
            reason: None,
            data: None,
            media_base64: None,
            media_mime_type: None,
        };

        let result = WhatsAppChannel::parse_bridge_message(&msg, &[], false);
        assert!(result.is_none());
    }

    #[test]
    fn test_parse_bridge_message_missing_chat_id() {
        let msg = BridgeMessage {
            msg_type: "message".to_string(),
            from: Some("60123456789".to_string()),
            chat_id: None,
            content: Some("Hello".to_string()),
            message_id: None,
            timestamp: None,
            sender_name: None,
            reason: None,
            data: None,
            media_base64: None,
            media_mime_type: None,
        };

        let result = WhatsAppChannel::parse_bridge_message(&msg, &[], false);
        assert!(result.is_none());
    }

    #[test]
    fn test_parse_bridge_message_content_trimmed() {
        let msg = BridgeMessage {
            msg_type: "message".to_string(),
            from: Some("60123456789".to_string()),
            chat_id: Some("60123456789@s.whatsapp.net".to_string()),
            content: Some("  padded message  ".to_string()),
            message_id: None,
            timestamp: None,
            sender_name: None,
            reason: None,
            data: None,
            media_base64: None,
            media_mime_type: None,
        };

        let inbound = WhatsAppChannel::parse_bridge_message(&msg, &[], false).unwrap();
        assert_eq!(inbound.content, "padded message");
    }

    #[test]
    fn test_parse_bridge_message_no_optional_metadata() {
        let msg = BridgeMessage {
            msg_type: "message".to_string(),
            from: Some("60123456789".to_string()),
            chat_id: Some("60123456789@s.whatsapp.net".to_string()),
            content: Some("Hello".to_string()),
            message_id: None,
            timestamp: None,
            sender_name: None,
            reason: None,
            data: None,
            media_base64: None,
            media_mime_type: None,
        };

        let inbound = WhatsAppChannel::parse_bridge_message(&msg, &[], false).unwrap();
        assert!(!inbound.metadata.contains_key("whatsapp_message_id"));
        assert!(!inbound.metadata.contains_key("timestamp"));
        assert!(!inbound.metadata.contains_key("sender_name"));
    }

    // -----------------------------------------------------------------------
    // 6. BridgeSendMessage serialization
    // -----------------------------------------------------------------------
    #[test]
    fn test_bridge_send_message_with_reply() {
        let msg = BridgeSendMessage {
            msg_type: "send".to_string(),
            to: "60123456789@s.whatsapp.net".to_string(),
            content: "Reply text".to_string(),
            reply_to: Some("wamid.xyz".to_string()),
        };
        let json = serde_json::to_value(&msg).expect("should serialize");

        assert_eq!(json["type"], "send");
        assert_eq!(json["to"], "60123456789@s.whatsapp.net");
        assert_eq!(json["content"], "Reply text");
        assert_eq!(json["reply_to"], "wamid.xyz");
    }

    #[test]
    fn test_bridge_send_message_without_reply() {
        let msg = BridgeSendMessage {
            msg_type: "send".to_string(),
            to: "60123456789@s.whatsapp.net".to_string(),
            content: "Hello!".to_string(),
            reply_to: None,
        };
        let json = serde_json::to_value(&msg).expect("should serialize");

        assert_eq!(json["type"], "send");
        assert_eq!(json["to"], "60123456789@s.whatsapp.net");
        assert_eq!(json["content"], "Hello!");
        assert!(json.get("reply_to").is_none()); // skip_serializing_if
    }

    #[test]
    fn test_bridge_send_message_roundtrip() {
        let msg = BridgeSendMessage {
            msg_type: "send".to_string(),
            to: "60123456789@s.whatsapp.net".to_string(),
            content: "Test message".to_string(),
            reply_to: Some("wamid.abc".to_string()),
        };
        let json_str = serde_json::to_string(&msg).expect("should serialize");
        assert!(json_str.contains(r#""type":"send""#));
        assert!(json_str.contains(r#""reply_to":"wamid.abc""#));
    }

    // -----------------------------------------------------------------------
    // 7. Running state management
    // -----------------------------------------------------------------------
    #[tokio::test]
    async fn test_running_state_default() {
        let channel = WhatsAppChannel::new(test_config(), test_bus());
        assert!(!channel.is_running());
    }

    #[tokio::test]
    async fn test_start_disabled_config() {
        let config = WhatsAppConfig {
            enabled: false,
            bridge_url: "ws://localhost:3001".to_string(),
            allow_from: vec![],
            bridge_managed: true,
            ..Default::default()
        };
        let mut channel = WhatsAppChannel::new(config, test_bus());

        let result = channel.start().await;
        assert!(result.is_ok());
        assert!(!channel.is_running());
    }

    #[tokio::test]
    async fn test_start_empty_bridge_url() {
        let config = WhatsAppConfig {
            enabled: true,
            bridge_url: String::new(),
            allow_from: vec![],
            bridge_managed: true,
            ..Default::default()
        };
        let mut channel = WhatsAppChannel::new(config, test_bus());

        let result = channel.start().await;
        assert!(result.is_err());
        assert!(!channel.is_running());
    }

    #[tokio::test]
    async fn test_stop_not_running() {
        let mut channel = WhatsAppChannel::new(test_config(), test_bus());
        let result = channel.stop().await;
        assert!(result.is_ok());
    }

    #[tokio::test]
    async fn test_send_not_running() {
        let channel = WhatsAppChannel::new(test_config(), test_bus());
        let msg = OutboundMessage::new("whatsapp", "60123456789@s.whatsapp.net", "Hello");
        let result = channel.send(msg).await;
        assert!(result.is_err());
    }

    #[tokio::test]
    async fn test_send_empty_chat_id() {
        // Start the channel so it's "running"
        let config = WhatsAppConfig {
            enabled: true,
            bridge_url: "ws://localhost:3001".to_string(),
            allow_from: vec![],
            bridge_managed: true,
            ..Default::default()
        };
        let mut channel = WhatsAppChannel::new(config, test_bus());
        // Manually set running + outbound channel (avoids actual WebSocket connect)
        channel.running.store(true, Ordering::SeqCst);
        let (tx, _rx) = mpsc::channel(64);
        channel.outbound_tx = Some(tx);

        let msg = OutboundMessage::new("whatsapp", "  ", "Hello");
        let result = channel.send(msg).await;
        assert!(result.is_err());
    }

    // -----------------------------------------------------------------------
    // 8. Backoff delay calculations
    // -----------------------------------------------------------------------
    #[test]
    fn test_backoff_delay_increases_exponentially() {
        let d0 = WhatsAppChannel::backoff_delay(0);
        let d1 = WhatsAppChannel::backoff_delay(1);
        let d2 = WhatsAppChannel::backoff_delay(2);
        let d3 = WhatsAppChannel::backoff_delay(3);

        assert_eq!(d0, Duration::from_secs(2)); // 2 * 2^0 = 2
        assert_eq!(d1, Duration::from_secs(4)); // 2 * 2^1 = 4
        assert_eq!(d2, Duration::from_secs(8)); // 2 * 2^2 = 8
        assert_eq!(d3, Duration::from_secs(16)); // 2 * 2^3 = 16
    }

    #[test]
    fn test_backoff_delay_caps_at_max() {
        let d_high = WhatsAppChannel::backoff_delay(20);
        assert_eq!(d_high, Duration::from_secs(MAX_RECONNECT_DELAY_SECS));
    }

    #[test]
    fn test_backoff_delay_does_not_overflow() {
        let d = WhatsAppChannel::backoff_delay(u32::MAX);
        assert_eq!(d, Duration::from_secs(MAX_RECONNECT_DELAY_SECS));
    }

    // -----------------------------------------------------------------------
    // 9. WhatsAppConfig serde defaults
    // -----------------------------------------------------------------------
    #[test]
    fn test_whatsapp_config_deserialize_defaults() {
        let json = r#"{}"#;
        let config: WhatsAppConfig = serde_json::from_str(json).expect("should parse");

        assert!(!config.enabled);
        assert_eq!(config.bridge_url, "ws://localhost:3001");
        assert!(config.allow_from.is_empty());
    }

    #[test]
    fn test_whatsapp_config_deserialize_full() {
        let json = r#"{
            "enabled": true,
            "bridge_url": "ws://remote:9000",
            "allow_from": ["601", "602", "603"]
        }"#;
        let config: WhatsAppConfig = serde_json::from_str(json).expect("should parse");

        assert!(config.enabled);
        assert_eq!(config.bridge_url, "ws://remote:9000");
        assert_eq!(config.allow_from, vec!["601", "602", "603"]);
    }

    #[test]
    fn test_whatsapp_config_default_trait() {
        let config = WhatsAppConfig::default();
        assert!(!config.enabled);
        assert_eq!(config.bridge_url, "ws://localhost:3001");
        assert!(config.allow_from.is_empty());
        assert!(config.bridge_managed);
    }

    // -----------------------------------------------------------------------
    // 10. bridge_managed config
    // -----------------------------------------------------------------------
    #[test]
    fn test_whatsapp_config_bridge_managed_default() {
        let json = r#"{}"#;
        let config: WhatsAppConfig = serde_json::from_str(json).expect("should parse");
        assert!(config.bridge_managed);
    }

    #[test]
    fn test_whatsapp_config_bridge_managed_false() {
        let json = r#"{"bridge_managed": false}"#;
        let config: WhatsAppConfig = serde_json::from_str(json).expect("should parse");
        assert!(!config.bridge_managed);
    }

    // -----------------------------------------------------------------------
    // 11. HasDependencies
    // -----------------------------------------------------------------------
    #[test]
    fn test_has_dependencies_managed() {
        let mut config = test_config();
        config.bridge_managed = true;
        let channel = WhatsAppChannel::new(config, test_bus());
        let deps = channel.dependencies();
        assert_eq!(deps.len(), 1);
        assert_eq!(deps[0].name, "whatsmeow-bridge");
    }

    #[test]
    fn test_has_dependencies_unmanaged() {
        let mut config = test_config();
        config.bridge_managed = false;
        let channel = WhatsAppChannel::new(config, test_bus());
        let deps = channel.dependencies();
        assert!(deps.is_empty());
    }

    // -----------------------------------------------------------------------
    // 12. Bridge token auth
    // -----------------------------------------------------------------------
    #[test]
    fn test_bridge_token_default_none() {
        let config = WhatsAppConfig::default();
        assert!(config.bridge_token.is_none());
    }

    #[test]
    fn test_bridge_token_deserialize_with_token() {
        let json = r#"{"bridge_token": "secret-tok-123"}"#;
        let config: WhatsAppConfig = serde_json::from_str(json).expect("should parse");
        assert_eq!(config.bridge_token.as_deref(), Some("secret-tok-123"));
    }

    #[test]
    fn test_bridge_token_serde_roundtrip() {
        let config = WhatsAppConfig {
            bridge_token: Some("my-token".to_string()),
            ..Default::default()
        };
        let json = serde_json::to_string(&config).expect("should serialize");
        let parsed: WhatsAppConfig = serde_json::from_str(&json).expect("should parse");
        assert_eq!(parsed.bridge_token.as_deref(), Some("my-token"));
    }

    #[test]
    fn test_bridge_token_env_override() {
        // Env override is tested in config module; here just verify the field is accessible.
        let mut config = WhatsAppConfig::default();
        config.bridge_token = Some("env-token".to_string());
        assert_eq!(config.bridge_token.as_deref(), Some("env-token"));
    }
}