rusmes-core 0.1.2

Mailet processing engine for RusMES — composable mail processing pipeline with matchers, mailets, DKIM/SPF/DMARC, spam filtering, and AI integration
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
//! OxiFY AI Mail Analysis mailet
//!
//! This mailet integrates with the OxiFY AI service to provide intelligent mail analysis:
//! - Sentiment analysis (positive/neutral/negative with confidence score)
//! - Category classification (work, personal, spam, urgent, newsletter, promotional)
//! - Priority scoring (1-10 scale based on sender, subject, urgency)
//! - Auto-tagging (AI-generated tags like #invoice, #meeting, #action-required)
//! - Smart folder routing based on classification
//!
//! Headers added:
//! - X-OxiFY-Sentiment: Sentiment classification
//! - X-OxiFY-Sentiment-Score: Confidence score (0.0-1.0)
//! - X-OxiFY-Categories: Comma-separated list of categories
//! - X-OxiFY-Priority: Priority score (1-10)
//! - X-OxiFY-Tags: Comma-separated list of tags

use crate::mailet::{Mailet, MailetAction, MailetConfig};
use async_trait::async_trait;
use rusmes_proto::Mail;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::sync::Arc;
use std::time::Duration;

/// Mail category classification
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum MailCategory {
    Work,
    Personal,
    Spam,
    Urgent,
    Newsletter,
    Promotional,
}

impl MailCategory {
    /// Convert to string
    pub fn as_str(&self) -> &str {
        match self {
            MailCategory::Work => "work",
            MailCategory::Personal => "personal",
            MailCategory::Spam => "spam",
            MailCategory::Urgent => "urgent",
            MailCategory::Newsletter => "newsletter",
            MailCategory::Promotional => "promotional",
        }
    }

    /// Parse from string
    pub fn parse(s: &str) -> Option<Self> {
        match s.to_lowercase().as_str() {
            "work" => Some(MailCategory::Work),
            "personal" => Some(MailCategory::Personal),
            "spam" => Some(MailCategory::Spam),
            "urgent" => Some(MailCategory::Urgent),
            "newsletter" => Some(MailCategory::Newsletter),
            "promotional" => Some(MailCategory::Promotional),
            _ => None,
        }
    }
}

/// Sentiment analysis result
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Sentiment {
    Positive,
    Negative,
    Neutral,
}

impl Sentiment {
    /// Convert to string
    pub fn as_str(&self) -> &str {
        match self {
            Sentiment::Positive => "positive",
            Sentiment::Negative => "negative",
            Sentiment::Neutral => "neutral",
        }
    }

    /// Parse from string
    pub fn parse(s: &str) -> Option<Self> {
        match s.to_lowercase().as_str() {
            "positive" => Some(Sentiment::Positive),
            "negative" => Some(Sentiment::Negative),
            "neutral" => Some(Sentiment::Neutral),
            _ => None,
        }
    }
}

/// OxiFY API request
#[derive(Debug, Clone, Serialize)]
pub struct AnalysisRequest {
    subject: String,
    from: String,
    to: Vec<String>,
    body: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    max_body_size: Option<usize>,
}

/// OxiFY API response
#[derive(Debug, Clone, Deserialize)]
pub struct AnalysisResponse {
    pub sentiment: Sentiment,
    pub sentiment_score: f64,
    pub categories: Vec<MailCategory>,
    pub priority: u8,
    pub tags: Vec<String>,
    #[serde(default)]
    pub folder: Option<String>,
}

/// OxiFY analysis result
#[derive(Debug, Clone)]
pub struct AnalysisResult {
    /// Sentiment classification
    pub sentiment: Sentiment,
    /// Sentiment confidence score (0.0 to 1.0)
    pub sentiment_score: f64,
    /// Mail categories (multi-label)
    pub categories: Vec<MailCategory>,
    /// Priority score (1-10)
    pub priority: u8,
    /// AI-generated tags
    pub tags: Vec<String>,
    /// Suggested folder for routing
    pub folder: Option<String>,
}

/// HTTP client trait for testability
#[async_trait]
pub trait HttpClient: Send + Sync {
    async fn post_analysis(
        &self,
        url: &str,
        api_key: &str,
        request: &AnalysisRequest,
        timeout_ms: u64,
    ) -> Result<AnalysisResponse, OxiFYError>;
}

/// Real HTTP client implementation
#[derive(Clone)]
pub struct ReqwestClient {
    client: reqwest::Client,
}

impl ReqwestClient {
    pub fn new() -> Self {
        Self {
            client: reqwest::Client::new(),
        }
    }
}

impl Default for ReqwestClient {
    fn default() -> Self {
        Self::new()
    }
}

#[async_trait]
impl HttpClient for ReqwestClient {
    async fn post_analysis(
        &self,
        url: &str,
        api_key: &str,
        request: &AnalysisRequest,
        timeout_ms: u64,
    ) -> Result<AnalysisResponse, OxiFYError> {
        let response = self
            .client
            .post(url)
            .header("Authorization", format!("Bearer {}", api_key))
            .header("Content-Type", "application/json")
            .timeout(Duration::from_millis(timeout_ms))
            .json(request)
            .send()
            .await
            .map_err(|e| {
                if e.is_timeout() {
                    OxiFYError::Timeout
                } else {
                    OxiFYError::NetworkError(e.to_string())
                }
            })?;

        let status = response.status();
        if status == 429 {
            return Err(OxiFYError::RateLimited);
        }

        if !status.is_success() {
            return Err(OxiFYError::ApiError(status.as_u16(), status.to_string()));
        }

        let analysis = response
            .json::<AnalysisResponse>()
            .await
            .map_err(|e| OxiFYError::ParseError(e.to_string()))?;

        Ok(analysis)
    }
}

/// OxiFY service errors
#[derive(Debug, Clone, thiserror::Error)]
pub enum OxiFYError {
    #[error("Network error: {0}")]
    NetworkError(String),
    #[error("API error: HTTP {0} - {1}")]
    ApiError(u16, String),
    #[error("Request timeout")]
    Timeout,
    #[error("Rate limited (HTTP 429)")]
    RateLimited,
    #[error("Parse error: {0}")]
    ParseError(String),
    #[error("Service disabled")]
    Disabled,
}

/// OxiFY AI service configuration
#[derive(Debug, Clone)]
pub struct OxiFYConfig {
    /// API endpoint URL
    pub api_url: String,
    /// API authentication key
    pub api_key: String,
    /// Enable/disable service globally
    pub enabled: bool,
    /// Request timeout in milliseconds
    pub timeout_ms: u64,
    /// Cache TTL in seconds (for future caching implementation)
    pub cache_ttl: u64,
    /// Maximum body size to analyze (bytes)
    pub max_body_size: usize,
    /// Category to folder mapping for routing
    pub folder_mapping: HashMap<String, String>,
}

impl Default for OxiFYConfig {
    fn default() -> Self {
        Self {
            api_url: "http://localhost:8080/api/v1/analyze".to_string(),
            api_key: String::new(),
            enabled: false,
            timeout_ms: 5000,
            cache_ttl: 3600,
            max_body_size: 50 * 1024, // 50KB
            folder_mapping: HashMap::new(),
        }
    }
}

/// OxiFY AI service
pub struct OxiFYService<C: HttpClient = ReqwestClient> {
    config: OxiFYConfig,
    client: Arc<C>,
}

impl OxiFYService<ReqwestClient> {
    /// Create a new OxiFY service with default HTTP client
    pub fn new(config: OxiFYConfig) -> Self {
        Self {
            config,
            client: Arc::new(ReqwestClient::new()),
        }
    }
}

impl<C: HttpClient> OxiFYService<C> {
    /// Create a new OxiFY service with custom HTTP client
    pub fn with_client(config: OxiFYConfig, client: C) -> Self {
        Self {
            config,
            client: Arc::new(client),
        }
    }

    /// Analyze a mail message
    pub async fn analyze(&self, mail: &Mail) -> Result<AnalysisResult, OxiFYError> {
        if !self.config.enabled {
            return Err(OxiFYError::Disabled);
        }

        // Extract mail attributes
        let subject = mail
            .get_attribute("header.Subject")
            .and_then(|v| v.as_str())
            .unwrap_or("")
            .to_string();

        let from = mail
            .get_attribute("header.From")
            .and_then(|v| v.as_str())
            .unwrap_or("")
            .to_string();

        let to = mail
            .get_attribute("header.To")
            .and_then(|v| v.as_str())
            .map(|s| vec![s.to_string()])
            .unwrap_or_default();

        let mut body = mail
            .get_attribute("message.body")
            .and_then(|v| v.as_str())
            .unwrap_or("")
            .to_string();

        // Limit body size
        if body.len() > self.config.max_body_size {
            body.truncate(self.config.max_body_size);
        }

        let request = AnalysisRequest {
            subject,
            from,
            to,
            body,
            max_body_size: Some(self.config.max_body_size),
        };

        // Call API
        let response = self
            .client
            .post_analysis(
                &self.config.api_url,
                &self.config.api_key,
                &request,
                self.config.timeout_ms,
            )
            .await?;

        // Validate priority range
        let priority = response.priority.clamp(1, 10);

        // Validate sentiment score range
        let sentiment_score = response.sentiment_score.clamp(0.0, 1.0);

        // Apply folder mapping if configured
        let folder = response.folder.or_else(|| {
            response.categories.first().and_then(|cat| {
                self.config
                    .folder_mapping
                    .get(cat.as_str())
                    .map(|f| f.to_string())
            })
        });

        Ok(AnalysisResult {
            sentiment: response.sentiment,
            sentiment_score,
            categories: response.categories,
            priority,
            tags: response.tags,
            folder,
        })
    }
}

/// OxiFY mailet - integrates OxiFY AI service
pub struct OxiFYMailet<C: HttpClient = ReqwestClient> {
    name: String,
    service: Option<OxiFYService<C>>,
}

impl OxiFYMailet<ReqwestClient> {
    /// Create a new OxiFY mailet (service will be created on init)
    pub fn new() -> Self {
        Self {
            name: "OxiFY".to_string(),
            service: Some(OxiFYService::new(OxiFYConfig::default())),
        }
    }
}

impl<C: HttpClient> OxiFYMailet<C> {
    /// Create a new OxiFY mailet with custom HTTP client
    pub fn with_client(client: C, config: OxiFYConfig) -> Self {
        Self {
            name: "OxiFY".to_string(),
            service: Some(OxiFYService::with_client(config, client)),
        }
    }

    /// Update configuration (for generic type parameter)
    pub fn update_config(&mut self, config: OxiFYConfig)
    where
        C: HttpClient + Default,
    {
        self.service = Some(OxiFYService::with_client(config, C::default()));
    }

    /// Apply analysis results to mail
    fn apply_analysis(&self, mail: &mut Mail, result: AnalysisResult) {
        // Add X-OxiFY-Sentiment header
        mail.set_attribute(
            "header.X-OxiFY-Sentiment",
            result.sentiment.as_str().to_string(),
        );

        // Add X-OxiFY-Sentiment-Score header
        mail.set_attribute(
            "header.X-OxiFY-Sentiment-Score",
            format!("{:.3}", result.sentiment_score),
        );

        // Add X-OxiFY-Categories header (comma-separated)
        let categories_str = result
            .categories
            .iter()
            .map(|c| c.as_str())
            .collect::<Vec<_>>()
            .join(",");
        mail.set_attribute("header.X-OxiFY-Categories", categories_str.clone());

        // Add X-OxiFY-Priority header
        mail.set_attribute("header.X-OxiFY-Priority", result.priority.to_string());

        // Add X-OxiFY-Tags header (comma-separated)
        let tags_str = result.tags.join(",");
        mail.set_attribute("header.X-OxiFY-Tags", tags_str.clone());

        // Set internal attributes for use by other mailets
        mail.set_attribute("oxify.sentiment", result.sentiment.as_str());
        mail.set_attribute("oxify.sentiment_score", result.sentiment_score);
        mail.set_attribute("oxify.categories", categories_str);
        mail.set_attribute("oxify.priority", result.priority as i64);
        mail.set_attribute("oxify.tags", tags_str);

        // Set folder for routing if available
        if let Some(folder) = result.folder {
            mail.set_attribute("oxify.folder", folder);
        }

        // Special handling for spam
        if result.categories.contains(&MailCategory::Spam) {
            mail.set_attribute("oxify.is_spam", true);
        }

        // Special handling for urgent
        if result.categories.contains(&MailCategory::Urgent) || result.priority >= 8 {
            mail.set_attribute("oxify.is_urgent", true);
        }
    }

    /// Process a mail message (public method for both trait impl and direct calls)
    pub async fn service(&self, mail: &mut Mail) -> anyhow::Result<MailetAction> {
        let service = self
            .service
            .as_ref()
            .ok_or_else(|| anyhow::anyhow!("OxiFY service not initialized"))?;

        tracing::debug!("Running OxiFY analysis on mail {}", mail.id());

        match service.analyze(mail).await {
            Ok(result) => {
                tracing::debug!(
                    "OxiFY analysis: sentiment={:?}, categories={:?}, priority={}",
                    result.sentiment,
                    result.categories,
                    result.priority
                );

                self.apply_analysis(mail, result);
                Ok(MailetAction::Continue)
            }
            Err(OxiFYError::Disabled) => {
                tracing::debug!("OxiFY service is disabled, skipping analysis");
                Ok(MailetAction::Continue)
            }
            Err(OxiFYError::Timeout) => {
                tracing::warn!("OxiFY analysis timeout for mail {}", mail.id());
                Ok(MailetAction::Continue)
            }
            Err(OxiFYError::RateLimited) => {
                tracing::warn!("OxiFY rate limited for mail {}", mail.id());
                Ok(MailetAction::Continue)
            }
            Err(OxiFYError::NetworkError(e)) => {
                tracing::error!("OxiFY network error for mail {}: {}", mail.id(), e);
                Ok(MailetAction::Continue)
            }
            Err(OxiFYError::ApiError(status, msg)) => {
                tracing::error!(
                    "OxiFY API error for mail {}: HTTP {} - {}",
                    mail.id(),
                    status,
                    msg
                );
                Ok(MailetAction::Continue)
            }
            Err(OxiFYError::ParseError(e)) => {
                tracing::error!("OxiFY parse error for mail {}: {}", mail.id(), e);
                Ok(MailetAction::Continue)
            }
        }
    }
}

impl Default for OxiFYMailet<ReqwestClient> {
    fn default() -> Self {
        Self::new()
    }
}

#[async_trait]
impl<C: HttpClient + Default + 'static> Mailet for OxiFYMailet<C> {
    async fn init(&mut self, config: MailetConfig) -> anyhow::Result<()> {
        // Build OxiFY configuration
        let mut oxify_config = OxiFYConfig::default();

        // API URL (required if enabled)
        if let Some(url) = config.get_param("api_url") {
            oxify_config.api_url = url.to_string();
        }

        // API key (required if enabled)
        if let Some(key) = config.get_param("api_key") {
            oxify_config.api_key = key.to_string();
        }

        // Enabled flag
        if let Some(enabled) = config.get_param("enabled") {
            oxify_config.enabled = enabled.parse().unwrap_or(false);
        }

        // Timeout
        if let Some(timeout) = config.get_param("timeout_ms") {
            oxify_config.timeout_ms = timeout.parse().unwrap_or(5000);
        }

        // Cache TTL
        if let Some(ttl) = config.get_param("cache_ttl") {
            oxify_config.cache_ttl = ttl.parse().unwrap_or(3600);
        }

        // Max body size
        if let Some(size) = config.get_param("max_body_size") {
            oxify_config.max_body_size = size.parse().unwrap_or(50 * 1024);
        }

        // Folder mapping
        for (key, value) in config.params.iter() {
            if let Some(category) = key.strip_prefix("folder_") {
                oxify_config
                    .folder_mapping
                    .insert(category.to_string(), value.clone());
            }
        }

        // Validate configuration if enabled
        if oxify_config.enabled && oxify_config.api_key.is_empty() {
            return Err(anyhow::anyhow!(
                "OxiFY API key is required when service is enabled"
            ));
        }

        // Update the service with new configuration
        self.update_config(oxify_config.clone());

        tracing::info!(
            "Initialized OxiFYMailet: enabled={}, api_url={}, timeout_ms={}",
            oxify_config.enabled,
            oxify_config.api_url,
            oxify_config.timeout_ms
        );

        Ok(())
    }

    async fn service(&self, mail: &mut Mail) -> anyhow::Result<MailetAction> {
        // Delegate to the public method in the generic impl
        OxiFYMailet::service(self, mail).await
    }

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

#[cfg(test)]
mod tests {
    use super::*;
    use bytes::Bytes;
    use rusmes_proto::{HeaderMap, MailAddress, MessageBody, MimeMessage};
    use std::str::FromStr;

    // Mock HTTP client for testing
    #[derive(Clone)]
    struct MockHttpClient {
        response: Arc<tokio::sync::Mutex<Option<MockResponse>>>,
    }

    #[derive(Clone)]
    enum MockResponse {
        Success(AnalysisResponse),
        Error(MockError),
    }

    #[derive(Clone)]
    enum MockError {
        Network(String),
        Timeout,
        RateLimited,
        Api(u16, String),
        Parse(String),
    }

    impl From<MockError> for OxiFYError {
        fn from(err: MockError) -> Self {
            match err {
                MockError::Network(msg) => OxiFYError::NetworkError(msg),
                MockError::Timeout => OxiFYError::Timeout,
                MockError::RateLimited => OxiFYError::RateLimited,
                MockError::Api(code, msg) => OxiFYError::ApiError(code, msg),
                MockError::Parse(msg) => OxiFYError::ParseError(msg),
            }
        }
    }

    impl MockHttpClient {
        #[allow(dead_code)]
        fn new() -> Self {
            Self {
                response: Arc::new(tokio::sync::Mutex::new(None)),
            }
        }

        fn with_success(response: AnalysisResponse) -> Self {
            Self {
                response: Arc::new(tokio::sync::Mutex::new(Some(MockResponse::Success(
                    response,
                )))),
            }
        }

        fn with_error(error: MockError) -> Self {
            Self {
                response: Arc::new(tokio::sync::Mutex::new(Some(MockResponse::Error(error)))),
            }
        }
    }

    #[async_trait]
    impl HttpClient for MockHttpClient {
        async fn post_analysis(
            &self,
            _url: &str,
            _api_key: &str,
            _request: &AnalysisRequest,
            _timeout_ms: u64,
        ) -> Result<AnalysisResponse, OxiFYError> {
            match self.response.lock().await.clone() {
                Some(MockResponse::Success(resp)) => Ok(resp),
                Some(MockResponse::Error(err)) => Err(err.into()),
                None => Err(OxiFYError::NetworkError("No response set".to_string())),
            }
        }
    }

    fn create_test_mail() -> Mail {
        Mail::new(
            Some(MailAddress::from_str("sender@test.com").unwrap()),
            vec![MailAddress::from_str("rcpt@test.com").unwrap()],
            MimeMessage::new(HeaderMap::new(), MessageBody::Small(Bytes::from("Test"))),
            None,
            None,
        )
    }

    fn create_success_response() -> AnalysisResponse {
        AnalysisResponse {
            sentiment: Sentiment::Neutral,
            sentiment_score: 0.5,
            categories: vec![MailCategory::Personal],
            priority: 5,
            tags: vec!["test".to_string()],
            folder: None,
        }
    }

    #[tokio::test]
    async fn test_oxify_mailet_init() {
        let mut mailet = OxiFYMailet::<ReqwestClient>::new();
        let config = MailetConfig::new("OxiFY")
            .with_param("enabled", "false")
            .with_param("api_url", "http://localhost:8080/api/v1/analyze")
            .with_param("api_key", "test_key");

        let result = mailet.init(config).await;
        assert!(result.is_ok());
        assert_eq!(mailet.name(), "OxiFY");
    }

    #[tokio::test]
    async fn test_oxify_mailet_init_missing_api_key_when_enabled() {
        let mut mailet = OxiFYMailet::<ReqwestClient>::new();
        let config = MailetConfig::new("OxiFY")
            .with_param("enabled", "true")
            .with_param("api_url", "http://localhost:8080/api/v1/analyze");

        let result = mailet.init(config).await;
        assert!(result.is_err());
    }

    #[tokio::test]
    async fn test_oxify_sentiment_positive() {
        let mock = MockHttpClient::with_success(AnalysisResponse {
            sentiment: Sentiment::Positive,
            sentiment_score: 0.95,
            categories: vec![MailCategory::Personal],
            priority: 5,
            tags: vec![],
            folder: None,
        });

        let config = OxiFYConfig {
            enabled: true,
            api_key: "test_key".to_string(),
            ..Default::default()
        };

        let mailet = OxiFYMailet::with_client(mock, config);
        let mut mail = create_test_mail();

        let result = mailet.service(&mut mail).await;
        assert!(result.is_ok());

        assert_eq!(
            mail.get_attribute("header.X-OxiFY-Sentiment")
                .and_then(|v| v.as_str()),
            Some("positive")
        );
        assert_eq!(
            mail.get_attribute("oxify.sentiment")
                .and_then(|v| v.as_str()),
            Some("positive")
        );
    }

    #[tokio::test]
    async fn test_oxify_sentiment_negative() {
        let mock = MockHttpClient::with_success(AnalysisResponse {
            sentiment: Sentiment::Negative,
            sentiment_score: 0.85,
            categories: vec![MailCategory::Personal],
            priority: 3,
            tags: vec![],
            folder: None,
        });

        let config = OxiFYConfig {
            enabled: true,
            api_key: "test_key".to_string(),
            ..Default::default()
        };

        let mailet = OxiFYMailet::with_client(mock, config);
        let mut mail = create_test_mail();

        mailet.service(&mut mail).await.unwrap();

        assert_eq!(
            mail.get_attribute("header.X-OxiFY-Sentiment")
                .and_then(|v| v.as_str()),
            Some("negative")
        );
    }

    #[tokio::test]
    async fn test_oxify_sentiment_neutral() {
        let mock = MockHttpClient::with_success(AnalysisResponse {
            sentiment: Sentiment::Neutral,
            sentiment_score: 0.5,
            categories: vec![MailCategory::Work],
            priority: 5,
            tags: vec![],
            folder: None,
        });

        let config = OxiFYConfig {
            enabled: true,
            api_key: "test_key".to_string(),
            ..Default::default()
        };

        let mailet = OxiFYMailet::with_client(mock, config);
        let mut mail = create_test_mail();

        mailet.service(&mut mail).await.unwrap();

        assert_eq!(
            mail.get_attribute("header.X-OxiFY-Sentiment")
                .and_then(|v| v.as_str()),
            Some("neutral")
        );
    }

    #[tokio::test]
    async fn test_oxify_category_work() {
        let mock = MockHttpClient::with_success(AnalysisResponse {
            sentiment: Sentiment::Neutral,
            sentiment_score: 0.5,
            categories: vec![MailCategory::Work],
            priority: 7,
            tags: vec!["meeting".to_string()],
            folder: None,
        });

        let config = OxiFYConfig {
            enabled: true,
            api_key: "test_key".to_string(),
            ..Default::default()
        };

        let mailet = OxiFYMailet::with_client(mock, config);
        let mut mail = create_test_mail();

        mailet.service(&mut mail).await.unwrap();

        assert_eq!(
            mail.get_attribute("header.X-OxiFY-Categories")
                .and_then(|v| v.as_str()),
            Some("work")
        );
    }

    #[tokio::test]
    async fn test_oxify_category_spam() {
        let mock = MockHttpClient::with_success(AnalysisResponse {
            sentiment: Sentiment::Negative,
            sentiment_score: 0.2,
            categories: vec![MailCategory::Spam],
            priority: 1,
            tags: vec![],
            folder: Some("Spam".to_string()),
        });

        let config = OxiFYConfig {
            enabled: true,
            api_key: "test_key".to_string(),
            ..Default::default()
        };

        let mailet = OxiFYMailet::with_client(mock, config);
        let mut mail = create_test_mail();

        mailet.service(&mut mail).await.unwrap();

        assert_eq!(
            mail.get_attribute("header.X-OxiFY-Categories")
                .and_then(|v| v.as_str()),
            Some("spam")
        );
        assert_eq!(
            mail.get_attribute("oxify.is_spam")
                .and_then(|v| v.as_bool()),
            Some(true)
        );
    }

    #[tokio::test]
    async fn test_oxify_category_urgent() {
        let mock = MockHttpClient::with_success(AnalysisResponse {
            sentiment: Sentiment::Neutral,
            sentiment_score: 0.5,
            categories: vec![MailCategory::Urgent, MailCategory::Work],
            priority: 9,
            tags: vec!["urgent".to_string()],
            folder: None,
        });

        let config = OxiFYConfig {
            enabled: true,
            api_key: "test_key".to_string(),
            ..Default::default()
        };

        let mailet = OxiFYMailet::with_client(mock, config);
        let mut mail = create_test_mail();

        mailet.service(&mut mail).await.unwrap();

        assert!(mail
            .get_attribute("header.X-OxiFY-Categories")
            .and_then(|v| v.as_str())
            .unwrap()
            .contains("urgent"));
        assert_eq!(
            mail.get_attribute("oxify.is_urgent")
                .and_then(|v| v.as_bool()),
            Some(true)
        );
    }

    #[tokio::test]
    async fn test_oxify_category_newsletter() {
        let mock = MockHttpClient::with_success(AnalysisResponse {
            sentiment: Sentiment::Neutral,
            sentiment_score: 0.5,
            categories: vec![MailCategory::Newsletter],
            priority: 3,
            tags: vec!["newsletter".to_string()],
            folder: None,
        });

        let config = OxiFYConfig {
            enabled: true,
            api_key: "test_key".to_string(),
            ..Default::default()
        };

        let mailet = OxiFYMailet::with_client(mock, config);
        let mut mail = create_test_mail();

        mailet.service(&mut mail).await.unwrap();

        assert_eq!(
            mail.get_attribute("header.X-OxiFY-Categories")
                .and_then(|v| v.as_str()),
            Some("newsletter")
        );
    }

    #[tokio::test]
    async fn test_oxify_category_promotional() {
        let mock = MockHttpClient::with_success(AnalysisResponse {
            sentiment: Sentiment::Positive,
            sentiment_score: 0.6,
            categories: vec![MailCategory::Promotional],
            priority: 2,
            tags: vec!["sale".to_string()],
            folder: None,
        });

        let config = OxiFYConfig {
            enabled: true,
            api_key: "test_key".to_string(),
            ..Default::default()
        };

        let mailet = OxiFYMailet::with_client(mock, config);
        let mut mail = create_test_mail();

        mailet.service(&mut mail).await.unwrap();

        assert_eq!(
            mail.get_attribute("header.X-OxiFY-Categories")
                .and_then(|v| v.as_str()),
            Some("promotional")
        );
    }

    #[tokio::test]
    async fn test_oxify_multi_category() {
        let mock = MockHttpClient::with_success(AnalysisResponse {
            sentiment: Sentiment::Neutral,
            sentiment_score: 0.5,
            categories: vec![MailCategory::Work, MailCategory::Urgent],
            priority: 8,
            tags: vec!["meeting".to_string(), "urgent".to_string()],
            folder: None,
        });

        let config = OxiFYConfig {
            enabled: true,
            api_key: "test_key".to_string(),
            ..Default::default()
        };

        let mailet = OxiFYMailet::with_client(mock, config);
        let mut mail = create_test_mail();

        mailet.service(&mut mail).await.unwrap();

        let categories = mail
            .get_attribute("header.X-OxiFY-Categories")
            .and_then(|v| v.as_str())
            .unwrap();
        assert!(categories.contains("work"));
        assert!(categories.contains("urgent"));
    }

    #[tokio::test]
    async fn test_oxify_priority_scoring() {
        let mock = MockHttpClient::with_success(AnalysisResponse {
            sentiment: Sentiment::Neutral,
            sentiment_score: 0.5,
            categories: vec![MailCategory::Urgent],
            priority: 10,
            tags: vec![],
            folder: None,
        });

        let config = OxiFYConfig {
            enabled: true,
            api_key: "test_key".to_string(),
            ..Default::default()
        };

        let mailet = OxiFYMailet::with_client(mock, config);
        let mut mail = create_test_mail();

        mailet.service(&mut mail).await.unwrap();

        assert_eq!(
            mail.get_attribute("header.X-OxiFY-Priority")
                .and_then(|v| v.as_str()),
            Some("10")
        );
        assert_eq!(
            mail.get_attribute("oxify.priority")
                .and_then(|v| v.as_i64()),
            Some(10)
        );
    }

    #[tokio::test]
    async fn test_oxify_priority_high_urgent() {
        let mock = MockHttpClient::with_success(AnalysisResponse {
            sentiment: Sentiment::Neutral,
            sentiment_score: 0.5,
            categories: vec![MailCategory::Work],
            priority: 9,
            tags: vec![],
            folder: None,
        });

        let config = OxiFYConfig {
            enabled: true,
            api_key: "test_key".to_string(),
            ..Default::default()
        };

        let mailet = OxiFYMailet::with_client(mock, config);
        let mut mail = create_test_mail();

        mailet.service(&mut mail).await.unwrap();

        assert_eq!(
            mail.get_attribute("oxify.is_urgent")
                .and_then(|v| v.as_bool()),
            Some(true)
        );
    }

    #[tokio::test]
    async fn test_oxify_auto_tagging() {
        let mock = MockHttpClient::with_success(AnalysisResponse {
            sentiment: Sentiment::Neutral,
            sentiment_score: 0.5,
            categories: vec![MailCategory::Work],
            priority: 5,
            tags: vec![
                "meeting".to_string(),
                "invoice".to_string(),
                "action-required".to_string(),
            ],
            folder: None,
        });

        let config = OxiFYConfig {
            enabled: true,
            api_key: "test_key".to_string(),
            ..Default::default()
        };

        let mailet = OxiFYMailet::with_client(mock, config);
        let mut mail = create_test_mail();

        mailet.service(&mut mail).await.unwrap();

        let tags = mail
            .get_attribute("header.X-OxiFY-Tags")
            .and_then(|v| v.as_str())
            .unwrap();
        assert!(tags.contains("meeting"));
        assert!(tags.contains("invoice"));
        assert!(tags.contains("action-required"));
    }

    #[tokio::test]
    async fn test_oxify_folder_routing() {
        let mock = MockHttpClient::with_success(AnalysisResponse {
            sentiment: Sentiment::Neutral,
            sentiment_score: 0.5,
            categories: vec![MailCategory::Newsletter],
            priority: 3,
            tags: vec![],
            folder: Some("Newsletters".to_string()),
        });

        let config = OxiFYConfig {
            enabled: true,
            api_key: "test_key".to_string(),
            ..Default::default()
        };

        let mailet = OxiFYMailet::with_client(mock, config);
        let mut mail = create_test_mail();

        mailet.service(&mut mail).await.unwrap();

        assert_eq!(
            mail.get_attribute("oxify.folder").and_then(|v| v.as_str()),
            Some("Newsletters")
        );
    }

    #[tokio::test]
    async fn test_oxify_folder_mapping() {
        let mock = MockHttpClient::with_success(AnalysisResponse {
            sentiment: Sentiment::Neutral,
            sentiment_score: 0.5,
            categories: vec![MailCategory::Work],
            priority: 5,
            tags: vec![],
            folder: None,
        });

        let mut folder_mapping = HashMap::new();
        folder_mapping.insert("work".to_string(), "Work".to_string());

        let config = OxiFYConfig {
            enabled: true,
            api_key: "test_key".to_string(),
            folder_mapping,
            ..Default::default()
        };

        let mailet = OxiFYMailet::with_client(mock, config);
        let mut mail = create_test_mail();

        mailet.service(&mut mail).await.unwrap();

        assert_eq!(
            mail.get_attribute("oxify.folder").and_then(|v| v.as_str()),
            Some("Work")
        );
    }

    #[tokio::test]
    async fn test_oxify_network_error() {
        let mock = MockHttpClient::with_error(MockError::Network("DNS failed".to_string()));

        let config = OxiFYConfig {
            enabled: true,
            api_key: "test_key".to_string(),
            ..Default::default()
        };

        let mailet = OxiFYMailet::with_client(mock, config);
        let mut mail = create_test_mail();

        // Should continue on network error
        let result = mailet.service(&mut mail).await;
        assert!(result.is_ok());
        assert!(matches!(result.unwrap(), MailetAction::Continue));
    }

    #[tokio::test]
    async fn test_oxify_timeout_error() {
        let mock = MockHttpClient::with_error(MockError::Timeout);

        let config = OxiFYConfig {
            enabled: true,
            api_key: "test_key".to_string(),
            ..Default::default()
        };

        let mailet = OxiFYMailet::with_client(mock, config);
        let mut mail = create_test_mail();

        // Should continue on timeout
        let result = mailet.service(&mut mail).await;
        assert!(result.is_ok());
        assert!(matches!(result.unwrap(), MailetAction::Continue));
    }

    #[tokio::test]
    async fn test_oxify_rate_limited() {
        let mock = MockHttpClient::with_error(MockError::RateLimited);

        let config = OxiFYConfig {
            enabled: true,
            api_key: "test_key".to_string(),
            ..Default::default()
        };

        let mailet = OxiFYMailet::with_client(mock, config);
        let mut mail = create_test_mail();

        // Should continue on rate limit
        let result = mailet.service(&mut mail).await;
        assert!(result.is_ok());
        assert!(matches!(result.unwrap(), MailetAction::Continue));
    }

    #[tokio::test]
    async fn test_oxify_api_error() {
        let mock =
            MockHttpClient::with_error(MockError::Api(500, "Internal Server Error".to_string()));

        let config = OxiFYConfig {
            enabled: true,
            api_key: "test_key".to_string(),
            ..Default::default()
        };

        let mailet = OxiFYMailet::with_client(mock, config);
        let mut mail = create_test_mail();

        // Should continue on API error
        let result = mailet.service(&mut mail).await;
        assert!(result.is_ok());
        assert!(matches!(result.unwrap(), MailetAction::Continue));
    }

    #[tokio::test]
    async fn test_oxify_parse_error() {
        let mock = MockHttpClient::with_error(MockError::Parse("Invalid JSON".to_string()));

        let config = OxiFYConfig {
            enabled: true,
            api_key: "test_key".to_string(),
            ..Default::default()
        };

        let mailet = OxiFYMailet::with_client(mock, config);
        let mut mail = create_test_mail();

        // Should continue on parse error
        let result = mailet.service(&mut mail).await;
        assert!(result.is_ok());
        assert!(matches!(result.unwrap(), MailetAction::Continue));
    }

    #[tokio::test]
    async fn test_oxify_disabled() {
        let mock = MockHttpClient::with_success(create_success_response());

        let config = OxiFYConfig {
            enabled: false,
            api_key: "test_key".to_string(),
            ..Default::default()
        };

        let mailet = OxiFYMailet::with_client(mock, config);
        let mut mail = create_test_mail();

        // Should continue when disabled
        let result = mailet.service(&mut mail).await;
        assert!(result.is_ok());
        assert!(matches!(result.unwrap(), MailetAction::Continue));

        // Should not add any headers
        assert!(mail.get_attribute("header.X-OxiFY-Sentiment").is_none());
    }

    #[tokio::test]
    async fn test_oxify_config_timeout() {
        let mut mailet = OxiFYMailet::<ReqwestClient>::new();
        let config = MailetConfig::new("OxiFY")
            .with_param("enabled", "false")
            .with_param("api_url", "http://localhost:8080/api/v1/analyze")
            .with_param("api_key", "test_key")
            .with_param("timeout_ms", "10000");

        mailet.init(config).await.unwrap();
    }

    #[tokio::test]
    async fn test_oxify_config_cache_ttl() {
        let mut mailet = OxiFYMailet::<ReqwestClient>::new();
        let config = MailetConfig::new("OxiFY")
            .with_param("enabled", "false")
            .with_param("api_url", "http://localhost:8080/api/v1/analyze")
            .with_param("api_key", "test_key")
            .with_param("cache_ttl", "7200");

        mailet.init(config).await.unwrap();
    }

    #[tokio::test]
    async fn test_oxify_config_max_body_size() {
        let mut mailet = OxiFYMailet::<ReqwestClient>::new();
        let config = MailetConfig::new("OxiFY")
            .with_param("enabled", "false")
            .with_param("api_url", "http://localhost:8080/api/v1/analyze")
            .with_param("api_key", "test_key")
            .with_param("max_body_size", "102400");

        mailet.init(config).await.unwrap();
    }

    #[tokio::test]
    async fn test_mail_category_from_str() {
        assert_eq!(MailCategory::parse("work"), Some(MailCategory::Work));
        assert_eq!(MailCategory::parse("SPAM"), Some(MailCategory::Spam));
        assert_eq!(MailCategory::parse("urgent"), Some(MailCategory::Urgent));
        assert_eq!(MailCategory::parse("invalid"), None);
    }

    #[tokio::test]
    async fn test_mail_category_as_str() {
        assert_eq!(MailCategory::Work.as_str(), "work");
        assert_eq!(MailCategory::Spam.as_str(), "spam");
        assert_eq!(MailCategory::Urgent.as_str(), "urgent");
    }

    #[tokio::test]
    async fn test_sentiment_from_str() {
        assert_eq!(Sentiment::parse("positive"), Some(Sentiment::Positive));
        assert_eq!(Sentiment::parse("NEGATIVE"), Some(Sentiment::Negative));
        assert_eq!(Sentiment::parse("neutral"), Some(Sentiment::Neutral));
        assert_eq!(Sentiment::parse("invalid"), None);
    }

    #[tokio::test]
    async fn test_sentiment_as_str() {
        assert_eq!(Sentiment::Positive.as_str(), "positive");
        assert_eq!(Sentiment::Negative.as_str(), "negative");
        assert_eq!(Sentiment::Neutral.as_str(), "neutral");
    }

    #[tokio::test]
    async fn test_oxify_sentiment_score_validation() {
        let mock = MockHttpClient::with_success(AnalysisResponse {
            sentiment: Sentiment::Positive,
            sentiment_score: 1.5, // Out of range, should be clamped
            categories: vec![MailCategory::Personal],
            priority: 5,
            tags: vec![],
            folder: None,
        });

        let config = OxiFYConfig {
            enabled: true,
            api_key: "test_key".to_string(),
            ..Default::default()
        };

        let service = OxiFYService::with_client(config, mock);
        let mail = create_test_mail();

        let result = service.analyze(&mail).await.unwrap();
        assert_eq!(result.sentiment_score, 1.0); // Clamped to 1.0
    }

    #[tokio::test]
    async fn test_oxify_priority_validation() {
        let mock = MockHttpClient::with_success(AnalysisResponse {
            sentiment: Sentiment::Neutral,
            sentiment_score: 0.5,
            categories: vec![MailCategory::Work],
            priority: 15, // Out of range, should be clamped
            tags: vec![],
            folder: None,
        });

        let config = OxiFYConfig {
            enabled: true,
            api_key: "test_key".to_string(),
            ..Default::default()
        };

        let service = OxiFYService::with_client(config, mock);
        let mail = create_test_mail();

        let result = service.analyze(&mail).await.unwrap();
        assert_eq!(result.priority, 10); // Clamped to 10
    }

    #[tokio::test]
    async fn test_oxify_empty_mail() {
        let mock = MockHttpClient::with_success(AnalysisResponse {
            sentiment: Sentiment::Neutral,
            sentiment_score: 0.5,
            categories: vec![MailCategory::Personal],
            priority: 5,
            tags: vec![],
            folder: None,
        });

        let config = OxiFYConfig {
            enabled: true,
            api_key: "test_key".to_string(),
            ..Default::default()
        };

        let mailet = OxiFYMailet::with_client(mock, config);
        let mut mail = create_test_mail();

        // Should process without errors
        let result = mailet.service(&mut mail).await;
        assert!(result.is_ok());
    }

    #[tokio::test]
    async fn test_oxify_default() {
        let mailet = OxiFYMailet::<ReqwestClient>::default();
        assert_eq!(mailet.name(), "OxiFY");
    }
}