cull-gmail 0.1.8

Cull emails from a gmail account using the gmail API
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
//! Rules management for Gmail message retention and cleanup.
//!
//! This module provides the [`Rules`] struct which manages a collection of end-of-life (EOL)
//! rules for automatically processing Gmail messages. Rules define when and how messages
//! should be processed based on their age and labels.
//!
//! # Overview
//!
//! The rules system allows you to:
//! - Create rules with specific retention periods (days, weeks, months, years)
//! - Target specific Gmail labels or apply rules globally
//! - Choose between moving to trash or permanent deletion
//! - Save and load rule configurations from disk
//! - Manage rules individually by ID or label
//!
//! # Usage
//!
//! ```
//! use cull_gmail::{Rules, Retention, MessageAge, EolAction};
//!
//! // Create a new rule set
//! let mut rules = Rules::new();
//!
//! // Add a rule to delete old newsletters after 6 months
//! let newsletter_retention = Retention::new(MessageAge::Months(6), true);
//! rules.add_rule(newsletter_retention, Some("newsletter"), true);
//!
//! // Add a rule to trash spam after 30 days
//! let spam_retention = Retention::new(MessageAge::Days(30), false);
//! rules.add_rule(spam_retention, Some("spam"), false);
//!
//! // Save the rules to disk
//! rules.save().expect("Failed to save rules");
//!
//! // List all configured rules
//! rules.list_rules().expect("Failed to list rules");
//! ```
//!
//! # Persistence
//!
//! Rules are automatically saved to `~/.cull-gmail/rules.toml` and can be loaded
//! using [`Rules::load()`]. The configuration uses TOML format for human readability.

use std::{
    collections::BTreeMap,
    env, fmt,
    fs::{self, read_to_string},
    path::Path,
};

use serde::{Deserialize, Serialize};

mod eol_rule;

pub use eol_rule::EolRule;

use crate::{EolAction, Error, MessageAge, Result, Retention};

/// A collection of end-of-life rules for Gmail message processing.
///
/// `Rules` manages a set of end-of-life rule instances that define how Gmail messages
/// should be processed based on their age and labels. Rules can move messages to
/// trash or delete them permanently when they exceed specified retention periods.
///
/// # Structure
///
/// Each rule has:
/// - A unique ID for identification
/// - A retention period (age threshold)
/// - Optional target labels
/// - An action (trash or delete)
///
/// # Default Rules
///
/// When created with [`Rules::new()`] or [`Rules::default()`], the following
/// default rules are automatically added:
/// - 1 year retention with auto-generated label
/// - 1 week retention with auto-generated label  
/// - 1 month retention with auto-generated label
/// - 5 year retention with auto-generated label
///
/// # Examples
///
/// ```
/// use cull_gmail::{Rules, Retention, MessageAge};
///
/// let rules = Rules::new();
/// // Default rules are automatically created
/// assert!(!rules.labels().is_empty());
/// ```
///
/// # Serialization
///
/// Rules can be serialized to and from TOML format for persistence.
#[derive(Debug, Serialize, Deserialize)]
pub struct Rules {
    rules: BTreeMap<String, EolRule>,
}

impl Default for Rules {
    fn default() -> Self {
        let rules = BTreeMap::new();

        let mut cfg = Self { rules };

        cfg.add_rule(Retention::new(MessageAge::Years(1), true), None, false)
            .add_rule(Retention::new(MessageAge::Weeks(1), true), None, false)
            .add_rule(Retention::new(MessageAge::Months(1), true), None, false)
            .add_rule(Retention::new(MessageAge::Years(5), true), None, false);

        cfg
    }
}

impl Rules {
    /// Creates a new Rules instance with default retention rules.
    ///
    /// This creates the same configuration as [`Rules::default()`], including
    /// several pre-configured rules with common retention periods.
    ///
    /// # Examples
    ///
    /// ```
    /// use cull_gmail::Rules;
    ///
    /// let rules = Rules::new();
    /// // Default rules are automatically created
    /// let labels = rules.labels();
    /// assert!(!labels.is_empty());
    /// ```
    pub fn new() -> Self {
        Rules::default()
    }

    /// Retrieves a rule by its unique ID.
    ///
    /// Returns a cloned copy of the rule if found, or `None` if no rule
    /// exists with the specified ID.
    ///
    /// # Arguments
    ///
    /// * `id` - The unique identifier of the rule to retrieve
    ///
    /// # Examples
    ///
    /// ```
    /// use cull_gmail::{Rules, Retention, MessageAge};
    ///
    /// let mut rules = Rules::new();
    /// let retention = Retention::new(MessageAge::Days(30), false);
    /// rules.add_rule(retention, None, false);
    ///
    /// // Retrieve a rule (exact ID depends on existing rules)
    /// if let Some(rule) = rules.get_rule(1) {
    ///     println!("Found rule: {}", rule.describe());
    /// }
    /// ```
    pub fn get_rule(&self, id: usize) -> Option<EolRule> {
        self.rules.get(&id.to_string()).cloned()
    }

    /// Adds a new rule to the rule set with the specified retention settings.
    ///
    /// Creates a new rule with an automatically assigned unique ID. If a label
    /// is specified and another rule already targets that label, a warning is
    /// logged and the rule is not added.
    ///
    /// # Arguments
    ///
    /// * `retention` - The retention configuration (age and label generation)
    /// * `label` - Optional label that this rule should target
    /// * `delete` - If `true`, messages are permanently deleted; if `false`, moved to trash
    ///
    /// # Returns
    ///
    /// Returns a mutable reference to self for method chaining.
    ///
    /// # Examples
    ///
    /// ```
    /// use cull_gmail::{Rules, Retention, MessageAge, EolAction};
    ///
    /// let mut rules = Rules::new();
    ///
    /// // Add a rule to trash newsletters after 3 months
    /// let retention = Retention::new(MessageAge::Months(3), false);
    /// rules.add_rule(retention, Some("newsletter"), false);
    ///
    /// // Add a rule to delete spam after 7 days
    /// let spam_retention = Retention::new(MessageAge::Days(7), false);
    /// rules.add_rule(spam_retention, Some("spam"), true);
    /// ```
    pub fn add_rule(
        &mut self,
        retention: Retention,
        label: Option<&str>,
        delete: bool,
    ) -> &mut Self {
        let current_labels: Vec<String> =
            self.rules.values().flat_map(|rule| rule.labels()).collect();

        if let Some(label_ref) = label
            && current_labels.iter().any(|l| l == label_ref)
        {
            log::warn!("a rule already applies to label {label_ref}");
            return self;
        }

        let id = if let Some((_, max)) = self.rules.iter().max_by_key(|(_, r)| r.id()) {
            max.id() + 1
        } else {
            1
        };

        let mut rule = EolRule::new(id);
        rule.set_retention(retention);
        if let Some(l) = label {
            rule.add_label(l);
        }
        if delete {
            rule.set_action(&EolAction::Delete);
        }
        log::info!("added rule: {rule}");
        self.rules.insert(rule.id().to_string(), rule);
        self
    }

    /// Returns all labels targeted by the current rules.
    ///
    /// This method collects labels from all rules in the set and returns
    /// them as a single vector. Duplicate labels are not removed.
    ///
    /// # Examples
    ///
    /// ```
    /// use cull_gmail::{Rules, Retention, MessageAge};
    ///
    /// let mut rules = Rules::new();
    /// let retention = Retention::new(MessageAge::Days(30), false);
    /// rules.add_rule(retention, Some("test-label"), false);
    ///
    /// let labels = rules.labels();
    /// assert!(labels.len() > 0);
    /// println!("Configured labels: {:?}", labels);
    /// ```
    pub fn labels(&self) -> Vec<String> {
        self.rules.values().flat_map(|rule| rule.labels()).collect()
    }

    /// Find the ids of the rules that contains a label
    ///
    /// A label may have a `trash` and `delete` rule applied to return a
    /// maximum of two rules.
    ///
    /// If a label has more than one `trash` or `delete` rules only the id
    /// for the last rule will be returned.
    fn find_label(&self, label: &str) -> Vec<usize> {
        let mut rwl = Vec::new();

        if let Some(t) = self.find_label_for_action(label, EolAction::Trash) {
            rwl.push(t);
        }

        if let Some(d) = self.find_label_for_action(label, EolAction::Delete) {
            rwl.push(d);
        }

        rwl
    }

    /// Find the id of the rule that contains a label
    fn find_label_for_action(&self, label: &str, action: EolAction) -> Option<usize> {
        let rules_by_label = self.get_rules_by_label_for_action(action);

        rules_by_label.get(label).map(|r| r.id())
    }

    /// Removes a rule from the set by its unique ID.
    ///
    /// If the rule exists, it is removed and a confirmation message is printed.
    /// If the rule doesn't exist, the operation completes successfully without error.
    ///
    /// # Arguments
    ///
    /// * `id` - The unique identifier of the rule to remove
    ///
    /// # Examples
    ///
    /// ```
    /// use cull_gmail::{Rules, Retention, MessageAge};
    ///
    /// let mut rules = Rules::new();
    /// // Assume rule ID 1 exists from defaults
    /// rules.remove_rule_by_id(1).expect("Failed to remove rule");
    /// ```
    ///
    /// # Errors
    ///
    /// This method currently always returns `Ok(())`, but the return type
    /// is `Result<()>` for future extensibility.
    pub fn remove_rule_by_id(&mut self, id: usize) -> crate::Result<()> {
        self.rules.remove(&id.to_string());
        println!("Rule `{id}` has been removed.");
        Ok(())
    }

    /// Removes a rule from the set by targeting one of its labels.
    ///
    /// Finds the rule that contains the specified label and removes it.
    /// If multiple rules target the same label, only one is removed.
    ///
    /// # Arguments
    ///
    /// * `label` - The label to search for in existing rules
    ///
    /// # Examples
    ///
    /// ```ignore
    /// use cull_gmail::{Rules, Retention, MessageAge};
    ///
    /// let mut rules = Rules::new();
    /// let retention = Retention::new(MessageAge::Days(30), false);
    /// rules.add_rule(retention, Some("newsletter"), false);
    ///
    /// // Remove the rule targeting the newsletter label
    /// rules.remove_rule_by_label("newsletter")
    ///      .expect("Failed to remove rule");
    /// ```
    ///
    /// # Errors
    ///
    /// * [`Error::LabelNotFoundInRules`] if no rule contains the specified label
    /// * [`Error::NoRuleFoundForLabel`] if the label exists but no rule is found
    ///   (should not happen under normal conditions)
    pub fn remove_rule_by_label(&mut self, label: &str) -> crate::Result<()> {
        let labels = self.labels();

        if !labels.iter().any(|l| l == label) {
            return Err(Error::LabelNotFoundInRules(label.to_string()));
        }

        let rule_ids = self.find_label(label);
        if rule_ids.is_empty() {
            return Err(Error::NoRuleFoundForLabel(label.to_string()));
        }

        for id in rule_ids {
            self.rules.remove(&id.to_string());
        }

        log::info!("Rule containing the label `{label}` has been removed.");
        Ok(())
    }

    /// Returns a mapping from labels to rules that target them.
    ///
    /// Creates a `BTreeMap` where each key is a label and each value is a cloned
    /// copy of the rule that targets that label. If multiple rules target the
    /// same label, only one will be present in the result (the last one processed).
    ///
    /// # Examples
    ///
    /// ```
    /// use cull_gmail::{Rules, Retention, MessageAge, EolAction};
    ///
    /// let mut rules = Rules::new();
    /// let retention = Retention::new(MessageAge::Days(30), false);
    /// rules.add_rule(retention, Some("test"), false);
    ///
    /// let label_map = rules.get_rules_by_label_for_action(EolAction::Trash);
    /// if let Some(rule) = label_map.get("test") {
    ///     println!("Rule for 'test' label: {}", rule.describe());
    /// }
    /// ```
    pub fn get_rules_by_label_for_action(&self, action: EolAction) -> BTreeMap<String, EolRule> {
        let mut rbl = BTreeMap::new();

        for rule in self.rules.values() {
            if rule.action() == Some(action) {
                for label in rule.labels() {
                    rbl.insert(label, rule.clone());
                }
            }
        }

        rbl
    }

    /// Adds a label to an existing rule and saves the configuration.
    ///
    /// Finds the rule with the specified ID and adds the given label to it.
    /// The configuration is automatically saved to disk after the change.
    ///
    /// # Arguments
    ///
    /// * `id` - The unique identifier of the rule to modify
    /// * `label` - The label to add to the rule
    ///
    /// # Examples
    ///
    /// ```ignore
    /// use cull_gmail::Rules;
    ///
    /// let mut rules = Rules::load().expect("Failed to load rules");
    /// rules.add_label_to_rule(1, "new-label")
    ///      .expect("Failed to add label");
    /// ```
    ///
    /// # Errors
    ///
    /// * [`Error::RuleNotFound`] if no rule exists with the specified ID
    /// * IO errors from saving the configuration file
    pub fn add_label_to_rule(&mut self, id: usize, label: &str) -> Result<()> {
        let Some(rule) = self.rules.get_mut(id.to_string().as_str()) else {
            return Err(Error::RuleNotFound(id));
        };
        rule.add_label(label);
        self.save()?;
        println!("Label `{label}` added to rule `#{id}`");

        Ok(())
    }

    /// Removes a label from an existing rule and saves the configuration.
    ///
    /// Finds the rule with the specified ID and removes the given label from it.
    /// The configuration is automatically saved to disk after the change.
    ///
    /// # Arguments
    ///
    /// * `id` - The unique identifier of the rule to modify
    /// * `label` - The label to remove from the rule
    ///
    /// # Examples
    ///
    /// ```ignore
    /// use cull_gmail::Rules;
    ///
    /// let mut rules = Rules::load().expect("Failed to load rules");
    /// rules.remove_label_from_rule(1, "old-label")
    ///      .expect("Failed to remove label");
    /// ```
    ///
    /// # Errors
    ///
    /// * [`Error::RuleNotFound`] if no rule exists with the specified ID
    /// * IO errors from saving the configuration file
    pub fn remove_label_from_rule(&mut self, id: usize, label: &str) -> Result<()> {
        let Some(rule) = self.rules.get_mut(id.to_string().as_str()) else {
            return Err(Error::RuleNotFound(id));
        };
        rule.remove_label(label);
        self.save()?;
        println!("Label `{label}` removed from rule `#{id}`");

        Ok(())
    }

    /// Sets the action for an existing rule and saves the configuration.
    ///
    /// Finds the rule with the specified ID and updates its action (trash or delete).
    /// The configuration is automatically saved to disk after the change.
    ///
    /// # Arguments
    ///
    /// * `id` - The unique identifier of the rule to modify
    /// * `action` - The new action to set (`Trash` or `Delete`)
    ///
    /// # Examples
    ///
    /// ```ignore
    /// use cull_gmail::{Rules, EolAction};
    ///
    /// let mut rules = Rules::load().expect("Failed to load rules");
    /// rules.set_action_on_rule(1, &EolAction::Delete)
    ///      .expect("Failed to set action");
    /// ```
    ///
    /// # Errors
    ///
    /// * [`Error::RuleNotFound`] if no rule exists with the specified ID
    /// * IO errors from saving the configuration file
    pub fn set_action_on_rule(&mut self, id: usize, action: &EolAction) -> Result<()> {
        let Some(rule) = self.rules.get_mut(id.to_string().as_str()) else {
            return Err(Error::RuleNotFound(id));
        };
        rule.set_action(action);
        self.save()?;
        println!("Action set to `{action}` on rule `#{id}`");

        Ok(())
    }

    /// Saves the current rule configuration to disk.
    ///
    /// The configuration is saved as TOML format to `~/.cull-gmail/rules.toml`.
    /// The directory is created if it doesn't exist.
    ///
    /// # Examples
    ///
    /// ```ignore
    /// use cull_gmail::{Rules, Retention, MessageAge};
    ///
    /// let mut rules = Rules::new();
    /// let retention = Retention::new(MessageAge::Days(30), false);
    /// rules.add_rule(retention, Some("test"), false);
    ///
    /// rules.save().expect("Failed to save configuration");
    /// ```
    ///
    /// # Errors
    ///
    /// * TOML serialization errors
    /// * IO errors when writing to the file system
    /// * File system permission errors
    pub fn save(&self) -> Result<()> {
        self.save_to(None)
    }

    /// Saves the current rule configuration to a specified path.
    ///
    /// If no path is provided, defaults to `~/.cull-gmail/rules.toml`.
    /// The directory is created if it doesn't exist.
    ///
    /// # Arguments
    ///
    /// * `path` - Optional path where the rules should be saved
    ///
    /// # Examples
    ///
    /// ```ignore
    /// use cull_gmail::Rules;
    /// use std::path::Path;
    ///
    /// let rules = Rules::new();
    /// rules.save_to(Some(Path::new("/custom/path/rules.toml")))
    ///      .expect("Failed to save");
    /// ```
    ///
    /// # Errors
    ///
    /// * TOML serialization errors
    /// * IO errors when writing to the file system
    /// * File system permission errors
    pub fn save_to(&self, path: Option<&Path>) -> Result<()> {
        let save_path = if let Some(p) = path {
            p.to_path_buf()
        } else {
            let home_dir = env::home_dir().ok_or_else(|| {
                Error::HomeExpansionFailed("~/.cull-gmail/rules.toml".to_string())
            })?;
            home_dir.join(".cull-gmail/rules.toml")
        };

        // Ensure directory exists
        if let Some(parent) = save_path.parent() {
            fs::create_dir_all(parent)?;
        }

        let res = toml::to_string(self);
        log::trace!("toml conversion result: {res:#?}");

        if let Ok(output) = res {
            fs::write(&save_path, output)?;
            log::trace!("Config saved to {}", save_path.display());
        }

        Ok(())
    }

    /// Loads rule configuration from disk.
    ///
    /// Reads the configuration from `~/.cull-gmail/rules.toml` and deserializes
    /// it into a `Rules` instance.
    ///
    /// # Examples
    ///
    /// ```ignore
    /// use cull_gmail::Rules;
    ///
    /// match Rules::load() {
    ///     Ok(rules) => {
    ///         println!("Loaded {} rules", rules.labels().len());
    ///         rules.list_rules().expect("Failed to list rules");
    ///     }
    ///     Err(e) => println!("Failed to load rules: {}", e),
    /// }
    /// ```
    ///
    /// # Errors
    ///
    /// * IO errors when reading from the file system
    /// * TOML parsing errors if the file is malformed
    /// * File not found errors if the configuration doesn't exist
    pub fn load() -> Result<Rules> {
        Self::load_from(None)
    }

    /// Loads rule configuration from a specified path.
    ///
    /// If no path is provided, defaults to `~/.cull-gmail/rules.toml`.
    ///
    /// # Arguments
    ///
    /// * `path` - Optional path to load rules from
    ///
    /// # Examples
    ///
    /// ```ignore
    /// use cull_gmail::Rules;
    /// use std::path::Path;
    ///
    /// let rules = Rules::load_from(Some(Path::new("/custom/path/rules.toml")))
    ///     .expect("Failed to load rules");
    /// ```
    ///
    /// # Errors
    ///
    /// * IO errors when reading from the file system
    /// * TOML parsing errors if the file is malformed
    /// * File not found errors if the configuration doesn't exist
    pub fn load_from(path: Option<&Path>) -> Result<Rules> {
        let load_path = if let Some(p) = path {
            p.to_path_buf()
        } else {
            let home_dir = env::home_dir().ok_or_else(|| {
                Error::HomeExpansionFailed("~/.cull-gmail/rules.toml".to_string())
            })?;
            home_dir.join(".cull-gmail/rules.toml")
        };

        log::trace!("Loading config from {}", load_path.display());

        let input = read_to_string(load_path)?;
        let config = toml::from_str::<Rules>(&input)?;
        Ok(config)
    }

    /// Prints all configured rules to standard output.
    ///
    /// Each rule is printed on a separate line with its description,
    /// including the rule ID, action, and age criteria.
    ///
    /// # Examples
    ///
    /// ```ignore
    /// use cull_gmail::Rules;
    ///
    /// let rules = Rules::new();
    /// rules.list_rules().expect("Failed to list rules");
    /// // Output:
    /// // Rule #1 is active on `retention/1-years` to move the message to trash if it is more than 1 years old.
    /// // Rule #2 is active on `retention/1-weeks` to move the message to trash if it is more than 1 weeks old.
    /// // ...
    /// ```
    ///
    /// # Errors
    ///
    /// This method currently always returns `Ok(())`, but the return type
    /// is `Result<()>` for consistency with other methods and future extensibility.
    pub fn list_rules(&self) -> Result<()> {
        for rule in self.rules.values() {
            println!("{rule}");
        }
        Ok(())
    }

    /// Validates all rules in the set and returns a list of issues found.
    ///
    /// Checks each rule for:
    /// - Non-empty label set
    /// - Valid retention period string (parseable as a `MessageAge`)
    /// - Valid action string (parseable as an `EolAction`)
    ///
    /// Also checks across rules for duplicate labels (the same label appearing
    /// in more than one rule).
    ///
    /// Returns an empty `Vec` if all rules are valid.
    ///
    /// # Examples
    ///
    /// ```
    /// use cull_gmail::Rules;
    ///
    /// let rules = Rules::new();
    /// let issues = rules.validate();
    /// assert!(issues.is_empty(), "Default rules should all be valid");
    /// ```
    pub fn validate(&self) -> Vec<ValidationIssue> {
        let mut issues = Vec::new();
        // Key: (label, action_str) — the same label in a Trash and a Delete rule is
        // intentional two-stage processing and must not be flagged as a duplicate.
        let mut seen_label_actions: BTreeMap<(String, String), usize> = BTreeMap::new();

        for rule in self.rules.values() {
            let id = rule.id();

            if rule.labels().is_empty() {
                issues.push(ValidationIssue::EmptyLabels { rule_id: id });
            }

            if MessageAge::parse(rule.retention()).is_none() {
                issues.push(ValidationIssue::InvalidRetention {
                    rule_id: id,
                    retention: rule.retention().to_string(),
                });
            }

            if rule.action().is_none() {
                issues.push(ValidationIssue::InvalidAction {
                    rule_id: id,
                    action: rule.action_str().to_string(),
                });
            }

            for label in rule.labels() {
                let key = (label.clone(), rule.action_str().to_lowercase());
                if let Some(&other_id) = seen_label_actions.get(&key) {
                    if other_id != id {
                        issues.push(ValidationIssue::DuplicateLabel {
                            label: label.clone(),
                        });
                    }
                } else {
                    seen_label_actions.insert(key, id);
                }
            }
        }

        issues
    }
}

/// An issue found during rules validation.
#[derive(Debug, PartialEq)]
pub enum ValidationIssue {
    /// A rule has no labels configured.
    EmptyLabels {
        /// The ID of the offending rule.
        rule_id: usize,
    },
    /// A rule has a retention string that cannot be parsed as a `MessageAge`.
    InvalidRetention {
        /// The ID of the offending rule.
        rule_id: usize,
        /// The unparseable retention string.
        retention: String,
    },
    /// A rule has an action string that cannot be parsed as an `EolAction`.
    InvalidAction {
        /// The ID of the offending rule.
        rule_id: usize,
        /// The unparseable action string.
        action: String,
    },
    /// The same label appears in more than one rule.
    DuplicateLabel {
        /// The duplicated label.
        label: String,
    },
}

impl fmt::Display for ValidationIssue {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            ValidationIssue::EmptyLabels { rule_id } => {
                write!(f, "Rule #{rule_id}: no labels configured")
            }
            ValidationIssue::InvalidRetention { rule_id, retention } => {
                write!(f, "Rule #{rule_id}: invalid retention '{retention}'")
            }
            ValidationIssue::InvalidAction { rule_id, action } => {
                write!(f, "Rule #{rule_id}: invalid action '{action}'")
            }
            ValidationIssue::DuplicateLabel { label } => {
                write!(f, "Label '{label}' is used in multiple rules")
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::test_utils::get_test_logger;
    use std::fs;

    fn setup_test_environment() {
        get_test_logger();
        // Clean up any existing test files
        let Some(home_dir) = env::home_dir() else {
            // Skip cleanup if home directory cannot be determined
            return;
        };
        let test_config_dir = home_dir.join(".cull-gmail");
        let test_rules_file = test_config_dir.join("rules.toml");
        if test_rules_file.exists() {
            let _ = fs::remove_file(&test_rules_file);
        }
    }

    #[test]
    fn test_rules_new_creates_default_rules() {
        setup_test_environment();

        let rules = Rules::new();

        // Should have some default rules
        let labels = rules.labels();
        assert!(
            !labels.is_empty(),
            "Default rules should create some labels"
        );

        // Should contain the expected retention labels
        assert!(labels.iter().any(|l| l.contains("retention/1-years")));
        assert!(labels.iter().any(|l| l.contains("retention/1-weeks")));
        assert!(labels.iter().any(|l| l.contains("retention/1-months")));
        assert!(labels.iter().any(|l| l.contains("retention/5-years")));
    }

    #[test]
    fn test_rules_default_same_as_new() {
        setup_test_environment();

        let rules_new = Rules::new();
        let rules_default = Rules::default();

        // Both should have the same number of rules
        assert_eq!(rules_new.labels().len(), rules_default.labels().len());
    }

    #[test]
    fn test_add_rule_with_label() {
        setup_test_environment();

        let mut rules = Rules::new();
        let initial_label_count = rules.labels().len();

        let retention = Retention::new(MessageAge::Days(30), false);
        rules.add_rule(retention, Some("test-label"), false);

        let labels = rules.labels();
        assert!(labels.contains(&"test-label".to_string()));
        assert_eq!(labels.len(), initial_label_count + 1);
    }

    #[test]
    fn test_add_rule_without_label() {
        setup_test_environment();

        let mut rules = Rules::new();
        let initial_label_count = rules.labels().len();

        let retention = Retention::new(MessageAge::Days(30), false);
        rules.add_rule(retention, None, false);

        // Should not add any new labels since no label specified and generate_label is false
        let labels = rules.labels();
        assert_eq!(labels.len(), initial_label_count);
    }

    #[test]
    fn test_add_rule_with_delete_action() {
        setup_test_environment();

        let mut rules = Rules::new();
        let retention = Retention::new(MessageAge::Days(7), false);
        rules.add_rule(retention, Some("delete-test"), true);

        let rules_by_label = rules.get_rules_by_label_for_action(EolAction::Delete);
        let rule = rules_by_label.get("delete-test").unwrap();
        assert_eq!(rule.action(), Some(EolAction::Delete));
    }

    #[test]
    fn test_add_duplicate_label_warns_and_skips() {
        setup_test_environment();

        let mut rules = Rules::new();
        let retention1 = Retention::new(MessageAge::Days(30), false);
        let retention2 = Retention::new(MessageAge::Days(60), false);

        rules.add_rule(retention1, Some("duplicate"), false);
        let initial_count = rules.labels().len();

        // Try to add another rule with the same label
        rules.add_rule(retention2, Some("duplicate"), false);

        // Should not increase the count of labels
        assert_eq!(rules.labels().len(), initial_count);
    }

    #[test]
    fn test_get_rule_existing() {
        setup_test_environment();

        let rules = Rules::new();

        // Default rules should have ID 1
        let rule = rules.get_rule(1);
        assert!(rule.is_some());
        assert_eq!(rule.unwrap().id(), 1);
    }

    #[test]
    fn test_get_rule_nonexistent() {
        setup_test_environment();

        let rules = Rules::new();

        // ID 999 should not exist
        let rule = rules.get_rule(999);
        assert!(rule.is_none());
    }

    #[test]
    fn test_labels_returns_all_labels() {
        setup_test_environment();

        let mut rules = Rules::new();
        let retention = Retention::new(MessageAge::Days(30), false);
        rules.add_rule(retention, Some("custom-label"), false);

        let labels = rules.labels();
        assert!(labels.contains(&"custom-label".to_string()));
    }

    #[test]
    fn test_get_rules_by_label() {
        setup_test_environment();

        let mut rules = Rules::new();
        let retention = Retention::new(MessageAge::Days(30), false);
        rules.add_rule(retention, Some("mapped-label"), false);

        let label_map = rules.get_rules_by_label_for_action(EolAction::Trash);
        let rule = label_map.get("mapped-label");
        assert!(rule.is_some());
        assert!(rule.unwrap().labels().contains(&"mapped-label".to_string()));
    }

    #[test]
    fn test_remove_rule_by_id_existing() {
        setup_test_environment();

        let mut rules = Rules::new();

        // Remove a default rule (assuming ID 1 exists)
        let result = rules.remove_rule_by_id(1);
        assert!(result.is_ok());

        // Rule should no longer exist
        assert!(rules.get_rule(1).is_none());
    }

    #[test]
    fn test_remove_rule_by_id_nonexistent() {
        setup_test_environment();

        let mut rules = Rules::new();

        // Removing non-existent rule should still succeed
        let result = rules.remove_rule_by_id(999);
        assert!(result.is_ok());
    }

    #[test]
    fn test_remove_rule_by_label_existing() {
        setup_test_environment();

        let mut rules = Rules::new();
        let retention = Retention::new(MessageAge::Days(30), false);
        rules.add_rule(retention, Some("remove-me"), false);

        let result = rules.remove_rule_by_label("remove-me");
        assert!(result.is_ok());

        // Label should no longer exist
        let labels = rules.labels();
        assert!(!labels.contains(&"remove-me".to_string()));
    }

    #[test]
    fn test_remove_rule_by_label_nonexistent() {
        setup_test_environment();

        let mut rules = Rules::new();

        let result = rules.remove_rule_by_label("nonexistent-label");
        assert!(result.is_err());

        match result.unwrap_err() {
            Error::LabelNotFoundInRules(label) => {
                assert_eq!(label, "nonexistent-label");
            }
            _ => panic!("Expected LabelNotFoundInRules error"),
        }
    }

    #[test]
    fn test_add_label_to_rule_existing_rule() {
        setup_test_environment();

        let mut rules = Rules::new();

        // Add label to existing rule (ID 1)
        let result = rules.add_label_to_rule(1, "new-label");
        assert!(result.is_ok());

        let rule = rules.get_rule(1).unwrap();
        assert!(rule.labels().contains(&"new-label".to_string()));
    }

    #[test]
    fn test_add_label_to_rule_nonexistent_rule() {
        setup_test_environment();

        let mut rules = Rules::new();

        let result = rules.add_label_to_rule(999, "new-label");
        assert!(result.is_err());

        match result.unwrap_err() {
            Error::RuleNotFound(id) => {
                assert_eq!(id, 999);
            }
            _ => panic!("Expected RuleNotFound error"),
        }
    }

    #[test]
    fn test_remove_label_from_rule_existing() {
        setup_test_environment();

        let mut rules = Rules::new();

        // First add a label
        let result = rules.add_label_to_rule(1, "temp-label");
        assert!(result.is_ok());

        // Then remove it
        let result = rules.remove_label_from_rule(1, "temp-label");
        assert!(result.is_ok());

        let rule = rules.get_rule(1).unwrap();
        assert!(!rule.labels().contains(&"temp-label".to_string()));
    }

    #[test]
    fn test_remove_label_from_rule_nonexistent_rule() {
        setup_test_environment();

        let mut rules = Rules::new();

        let result = rules.remove_label_from_rule(999, "any-label");
        assert!(result.is_err());

        match result.unwrap_err() {
            Error::RuleNotFound(id) => {
                assert_eq!(id, 999);
            }
            _ => panic!("Expected RuleNotFound error"),
        }
    }

    #[test]
    fn test_set_action_on_rule_existing() {
        setup_test_environment();

        let mut rules = Rules::new();

        // Set action to Delete
        let result = rules.set_action_on_rule(1, &EolAction::Delete);
        assert!(result.is_ok());

        let rule = rules.get_rule(1).unwrap();
        assert_eq!(rule.action(), Some(EolAction::Delete));
    }

    #[test]
    fn test_set_action_on_rule_nonexistent() {
        setup_test_environment();

        let mut rules = Rules::new();

        let result = rules.set_action_on_rule(999, &EolAction::Delete);
        assert!(result.is_err());

        match result.unwrap_err() {
            Error::RuleNotFound(id) => {
                assert_eq!(id, 999);
            }
            _ => panic!("Expected RuleNotFound error"),
        }
    }

    #[test]
    fn test_list_rules_succeeds() {
        setup_test_environment();

        let rules = Rules::new();

        // Should not panic or return error
        let result = rules.list_rules();
        assert!(result.is_ok());
    }

    // --- validate() tests ---

    #[test]
    fn test_validate_default_rules_are_valid() {
        setup_test_environment();
        let rules = Rules::new();
        let issues = rules.validate();
        assert!(
            issues.is_empty(),
            "Default rules should be valid, got: {issues:?}"
        );
    }

    #[test]
    fn test_validate_empty_labels_reported() {
        setup_test_environment();
        let toml_str = r#"
[rules."1"]
id = 1
retention = "d:30"
labels = []
action = "Trash"
"#;
        let rules: Rules = toml::from_str(toml_str).unwrap();
        let issues = rules.validate();
        assert!(
            issues
                .iter()
                .any(|i| matches!(i, ValidationIssue::EmptyLabels { rule_id: 1 })),
            "Expected EmptyLabels for rule #1, got: {issues:?}"
        );
    }

    #[test]
    fn test_validate_invalid_retention_reported() {
        setup_test_environment();
        let toml_str = r#"
[rules."1"]
id = 1
retention = "invalid"
labels = ["some-label"]
action = "Trash"
"#;
        let rules: Rules = toml::from_str(toml_str).unwrap();
        let issues = rules.validate();
        assert!(
            issues
                .iter()
                .any(|i| matches!(i, ValidationIssue::InvalidRetention { rule_id: 1, .. })),
            "Expected InvalidRetention for rule #1, got: {issues:?}"
        );
    }

    #[test]
    fn test_validate_empty_retention_reported() {
        setup_test_environment();
        let toml_str = r#"
[rules."1"]
id = 1
retention = ""
labels = ["some-label"]
action = "Trash"
"#;
        let rules: Rules = toml::from_str(toml_str).unwrap();
        let issues = rules.validate();
        assert!(
            issues
                .iter()
                .any(|i| matches!(i, ValidationIssue::InvalidRetention { rule_id: 1, .. })),
            "Expected InvalidRetention for empty retention in rule #1, got: {issues:?}"
        );
    }

    #[test]
    fn test_validate_invalid_action_reported() {
        setup_test_environment();
        let toml_str = r#"
[rules."1"]
id = 1
retention = "d:30"
labels = ["some-label"]
action = "invalid-action"
"#;
        let rules: Rules = toml::from_str(toml_str).unwrap();
        let issues = rules.validate();
        assert!(
            issues
                .iter()
                .any(|i| matches!(i, ValidationIssue::InvalidAction { rule_id: 1, .. })),
            "Expected InvalidAction for rule #1, got: {issues:?}"
        );
    }

    #[test]
    fn test_validate_duplicate_label_reported() {
        setup_test_environment();
        let toml_str = r#"
[rules."1"]
id = 1
retention = "d:30"
labels = ["shared-label"]
action = "Trash"

[rules."2"]
id = 2
retention = "d:60"
labels = ["shared-label"]
action = "Trash"
"#;
        let rules: Rules = toml::from_str(toml_str).unwrap();
        let issues = rules.validate();
        assert!(
            issues.iter().any(|i| matches!(
                i,
                ValidationIssue::DuplicateLabel { label }
                if label == "shared-label"
            )),
            "Expected DuplicateLabel for 'shared-label', got: {issues:?}"
        );
    }

    #[test]
    fn test_validate_same_label_different_actions_not_duplicate() {
        setup_test_environment();
        // A label in a Trash rule AND a Delete rule is intentional two-stage processing.
        let toml_str = r#"
[rules."1"]
id = 1
retention = "w:1"
labels = ["Development/Notifications"]
action = "Trash"

[rules."2"]
id = 2
retention = "w:2"
labels = ["Development/Notifications"]
action = "Delete"
"#;
        let rules: Rules = toml::from_str(toml_str).unwrap();
        let issues = rules.validate();
        assert!(
            !issues
                .iter()
                .any(|i| matches!(i, ValidationIssue::DuplicateLabel { .. })),
            "Same label with different actions should NOT be flagged as duplicate, got: {issues:?}"
        );
    }

    #[test]
    fn test_validate_multiple_issues_collected() {
        setup_test_environment();
        let toml_str = r#"
[rules."1"]
id = 1
retention = ""
labels = []
action = "bad"
"#;
        let rules: Rules = toml::from_str(toml_str).unwrap();
        let issues = rules.validate();
        // All three issues should be present for the one rule
        assert!(
            issues
                .iter()
                .any(|i| matches!(i, ValidationIssue::EmptyLabels { .. })),
            "Expected EmptyLabels"
        );
        assert!(
            issues
                .iter()
                .any(|i| matches!(i, ValidationIssue::InvalidRetention { .. })),
            "Expected InvalidRetention"
        );
        assert!(
            issues
                .iter()
                .any(|i| matches!(i, ValidationIssue::InvalidAction { .. })),
            "Expected InvalidAction"
        );
    }

    // Integration tests for save/load would require file system setup
    // These are marked as ignore to avoid interference with actual config files
    #[test]
    #[ignore = "Integration test that modifies file system"]
    fn test_save_and_load_roundtrip() {
        setup_test_environment();

        let mut rules = Rules::new();
        let retention = Retention::new(MessageAge::Days(30), false);
        rules.add_rule(retention, Some("save-test"), false);

        // Save to disk
        let save_result = rules.save();
        assert!(save_result.is_ok());

        // Load from disk
        let loaded_rules = Rules::load();
        assert!(loaded_rules.is_ok());

        let loaded_rules = loaded_rules.unwrap();
        let labels = loaded_rules.labels();
        assert!(labels.contains(&"save-test".to_string()));
    }
}