himalaya 2.2.1

CLI to manage emails
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
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
//! # Configuration
//!
//! The TOML schema: a global block plus named account blocks, each
//! carrying the optional per-backend sub-blocks its protocols need.
//!
//! Backend defaults are duplicated here rather than read from the io-*
//! crates, so the schema compiles under any feature subset, none included.

use std::{collections::HashMap, path::PathBuf};

use anyhow::{Error, Result, anyhow, bail};
use crossterm::style::Color;
use io_sasl::{
    login::SaslLoginCreds, mechanism::Sasl, rfc4505::anonymous::SaslAnonymousCreds,
    rfc4616::plain::SaslPlainCreds, rfc5801::SaslGs2ChannelBinding, rfc5802::SaslScramCreds,
    rfc7628::oauthbearer::SaslOauthbearerCreds, xoauth2::SaslXoauth2Creds,
};
use pimalaya_cli::table::ContentArrangement;
use pimalaya_config::{
    secret::{Secret, SecretResolver},
    toml::{TomlConfig, shell_expanded_path, shell_expanded_string},
};
use pimalaya_stream::{
    proxy::{Proxy, ProxyAuth},
    tls::{Rustls, RustlsCrypto, Tls, TlsProvider},
};
use secrecy::SecretString;
use serde::{Deserialize, Deserializer, Serialize, de::IgnoredAny};
use url::Url;

use crate::backend::Backend;

/// Skips a field equal to its type's default, so a wizard-generated
/// configuration omits defaulted scalars.
fn is_default<T: Default + PartialEq>(value: &T) -> bool {
    *value == T::default()
}

/// Expands a leading tilde and any shell variable in an optional path,
/// as [`shell_expanded_path`] does for a mandatory one.
///
/// TODO: drop this for `pimalaya_config::toml::opt_shell_expanded_path`
/// once pimalaya-config ships an optional variant.
fn opt_shell_expanded_path<'de, D: Deserializer<'de>>(de: D) -> Result<Option<PathBuf>, D::Error> {
    shell_expanded_path(de).map(Some)
}

fn is_default_imap_alpn(alpn: &[String]) -> bool {
    alpn == default_imap_alpn().as_slice()
}

fn is_default_smtp_alpn(alpn: &[String]) -> bool {
    alpn == default_smtp_alpn().as_slice()
}

fn is_default_sieve_alpn(alpn: &[String]) -> bool {
    alpn.is_empty()
}

fn is_default_jmap_alpn(alpn: &[String]) -> bool {
    alpn == default_jmap_alpn().as_slice()
}

// NOTE: these mirror the io-* crates' own `default_alpn()`, kept local so
// the schema depends on no backend crate.
pub(crate) fn default_imap_alpn() -> Vec<String> {
    vec![String::from("imap")]
}

pub(crate) fn default_smtp_alpn() -> Vec<String> {
    vec![String::from("smtp")]
}

pub(crate) fn default_sieve_alpn() -> Vec<String> {
    Vec::new()
}

pub(crate) fn default_jmap_alpn() -> Vec<String> {
    vec![String::from("http/1.1")]
}

fn is_default_gmail_alpn(alpn: &[String]) -> bool {
    alpn == default_gmail_alpn().as_slice()
}

fn is_default_msgraph_alpn(alpn: &[String]) -> bool {
    alpn == default_msgraph_alpn().as_slice()
}

/// The whole TOML configuration file.
///
/// `deny_unknown_fields` is omitted so one file can be shared with
/// himalaya-tui, whose own top-level fields are ignored here.
#[derive(Debug, Default, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case")]
pub struct Config {
    /// Fallback for [`AccountConfig::display_name`].
    #[serde(alias = "from-name")]
    pub display_name: Option<String>,
    /// Fallback for [`AccountConfig::signature`].
    pub signature: Option<String>,
    /// Fallback for [`AccountConfig::signature_delim`].
    pub signature_delim: Option<String>,
    /// Directory attachments are downloaded to.
    #[serde(default, deserialize_with = "opt_shell_expanded_path")]
    pub downloads_dir: Option<PathBuf>,
    /// Table rendering quirks shared by every listing.
    #[serde(default)]
    pub table: TableConfig,
    /// `envelope list` rendering options.
    #[serde(default)]
    pub envelope: EnvelopeConfig,
    /// Mailbox aliases and `mailbox list` rendering options.
    #[serde(default)]
    pub mailbox: MailboxConfig,
    /// `attachment list` rendering options.
    #[serde(default)]
    pub attachment: AttachmentConfig,
    /// Fallback for [`AccountConfig::message`].
    #[serde(default)]
    pub message: MessageConfig,
    /// `account list` rendering options, global only: the listing of
    /// accounts belongs to no account, so nothing overrides it.
    #[serde(default)]
    pub account: AccountListingConfig,
    /// The named `[accounts.<name>]` blocks.
    pub accounts: HashMap<String, AccountConfig>,
}

impl TomlConfig for Config {
    type Account = AccountConfig;

    fn project_name() -> &'static str {
        env!("CARGO_PKG_NAME")
    }

    fn take_named_account(&mut self, name: &str) -> Option<(String, Self::Account)> {
        let (name, mut account) = self.accounts.remove_entry(name)?;
        account.inherit_proxy();
        Some((name, account))
    }

    fn take_default_account(&mut self) -> Option<(String, Self::Account)> {
        let name = self
            .accounts
            .iter()
            .find_map(|(name, account)| account.default.then(|| name.clone()))?;

        self.take_named_account(&name)
    }
}

/// The order a rendered account groups its keys in, most defining first.
///
/// A key outside this list still renders, after the listed ones, so a
/// field added to [`AccountConfig`] can never go missing from a generated
/// document just because nobody updated this table.
const RENDER_ORDER: [&str; 21] = [
    "default",
    "email",
    "display-name",
    "signature",
    "signature-delim",
    "proxy",
    "imap",
    "jmap",
    "gmail",
    "msgraph",
    "maildir",
    "m2dir",
    "mbox",
    "pimdir",
    "smtp",
    "sieve",
    "mailbox",
    "envelope",
    "attachment",
    "message",
    "table",
];

impl AccountConfig {
    /// Hands the account proxy to every network backend naming none of
    /// its own.
    fn inherit_proxy(&mut self) {
        let Some(proxy) = &self.proxy else {
            return;
        };

        let slots = [
            self.imap.as_mut().map(|c| &mut c.proxy),
            self.jmap.as_mut().map(|c| &mut c.proxy),
            self.gmail.as_mut().map(|c| &mut c.proxy),
            self.msgraph.as_mut().map(|c| &mut c.proxy),
            self.smtp.as_mut().map(|c| &mut c.proxy),
            self.sieve.as_mut().map(|c| &mut c.proxy),
        ];

        for slot in slots.into_iter().flatten() {
            slot.get_or_insert_with(|| proxy.clone());
        }
    }

    /// The error of account `name` where nothing matches `backend`, the
    /// caller being able to use `supported` alone.
    ///
    /// Names the v1 `backend` table when present, it being the likely
    /// cause.
    pub fn no_backend_error(&self, name: &str, backend: Backend, supported: &[Backend]) -> Error {
        let reason = match backend {
            Backend::Auto => {
                let supported: Vec<String> = supported.iter().map(|b| format!("`{b}`")).collect();
                let supported = supported.join(", ");
                format!("Account `{name}` configures no supported backend ({supported})")
            }
            backend if !supported.contains(&backend) => {
                format!("Backend `{backend}` is not supported by this command or build")
            }
            backend => format!("Account `{name}` has no `{backend}` block"),
        };

        if self.backend.is_some() {
            anyhow!("{reason}: its v1 `backend` table is ignored since v2, see MIGRATION.md")
        } else {
            anyhow!(reason)
        }
    }

    /// Renders this account as an `[accounts.<name>]` block.
    ///
    /// What this adds over the serializer is reading order: dotted keys
    /// come out alphabetically, burying `imap.server` under the
    /// credentials authenticating against it. Groups are reordered and
    /// each endpoint lifted to the top of its own.
    pub fn render(&self, name: &str) -> Result<String> {
        // NOTE: borrowed rather than built into a `Config`, which would
        // mean cloning the account, and so deriving `Clone` down every
        // backend config, to render it.
        #[derive(Serialize)]
        struct AccountDocument<'a> {
            accounts: HashMap<&'a str, &'a AccountConfig>,
        }

        let document = AccountDocument {
            accounts: HashMap::from([(name, self)]),
        };
        let rendered = pimalaya_config::toml::to_string(&document)?;

        let (header, body) = match rendered.split_once('\n') {
            Some((header, body)) => (header, body),
            None => return Ok(rendered),
        };

        let mut groups: Vec<(String, Vec<&str>)> = Vec::new();

        for line in body.lines().filter(|line| !line.trim().is_empty()) {
            let key = line.split(['.', ' ']).next().unwrap_or(line).to_string();

            match groups.iter_mut().find(|(name, _)| *name == key) {
                Some((_, lines)) => lines.push(line),
                None => groups.push((key, vec![line])),
            }
        }

        groups.sort_by_key(|(key, _)| {
            RENDER_ORDER
                .iter()
                .position(|known| known == key)
                .unwrap_or(RENDER_ORDER.len())
        });

        let mut document = format!("{header}\n");

        for (index, (key, mut lines)) in groups.into_iter().enumerate() {
            if index > 0 {
                document.push('\n');
            }

            // NOTE: the endpoint is what the group is about, so it reads
            // first, the credentials and the quirks qualifying it.
            let server = format!("{key}.server ");
            lines.sort_by_key(|line| !line.starts_with(&server));

            for line in lines {
                document.push_str(line);
                document.push('\n');
            }
        }

        Ok(document)
    }
}

/// One `[accounts.<name>]` block.
///
/// `deny_unknown_fields` is omitted so a block written for one binary
/// loads in the other: the CLI-only sub-blocks have to be tolerated by
/// himalaya-tui, which models the rest.
#[derive(Debug, Default, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case")]
pub struct AccountConfig {
    /// Whether a command with no `-a/--account` runs against this one.
    #[serde(default, skip_serializing_if = "is_default")]
    pub default: bool,
    /// Address this account sends as, absent `--from`.
    ///
    /// Neither validated nor required, an account that never composes
    /// having no use for it. Aliased to `from`, the spelling himalaya-tui
    /// writes, the two binaries sharing one file.
    #[serde(alias = "from")]
    pub email: Option<String>,
    /// Name the `From` address carries, falling back to the global one.
    ///
    /// Quoting and encoding are the MIME builder's business, so write the
    /// name as it should read. Aliased to `from-name`, the spelling
    /// himalaya-tui writes.
    #[serde(alias = "from-name")]
    pub display_name: Option<String>,
    /// Signature appended to a composed message, falling back to the
    /// global one.
    ///
    /// The value is the signature alone, the separator before it being
    /// `signature-delim`'s business, so one written for either binary
    /// reads the same in the other.
    pub signature: Option<String>,
    /// Separator written before the signature, defaulting to the RFC 3676
    /// section 4.3 `"-- \n"`.
    ///
    /// Written verbatim, so a value meant to stand on its own line carries
    /// its own trailing newline.
    pub signature_delim: Option<String>,
    /// Directory attachments are downloaded to.
    #[serde(default, deserialize_with = "opt_shell_expanded_path")]
    pub downloads_dir: Option<PathBuf>,
    /// Table rendering quirks shared by every listing.
    #[serde(default)]
    pub table: TableConfig,
    /// `envelope list` rendering options.
    #[serde(default)]
    pub envelope: EnvelopeConfig,
    /// Mailbox aliases and `mailbox list` rendering options.
    #[serde(default)]
    pub mailbox: MailboxConfig,
    /// `attachment list` rendering options.
    #[serde(default)]
    pub attachment: AttachmentConfig,
    /// Message sending options.
    #[serde(default)]
    pub message: MessageConfig,
    /// Proxy every network backend of this account goes through, unless
    /// its own block names one.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub proxy: Option<ProxyConfig>,
    /// The IMAP backend of this account.
    #[allow(unused)]
    pub imap: Option<ImapConfig>,
    /// The JMAP backend of this account.
    #[allow(unused)]
    pub jmap: Option<JmapConfig>,
    /// The Gmail backend of this account.
    #[allow(unused)]
    pub gmail: Option<GmailConfig>,
    /// The Microsoft Graph backend of this account.
    #[allow(unused)]
    pub msgraph: Option<MsgraphConfig>,
    /// The Maildir backend of this account.
    #[allow(unused)]
    pub maildir: Option<MaildirConfig>,
    /// The m2dir backend of this account.
    #[allow(unused)]
    pub m2dir: Option<M2dirConfig>,
    /// The mbox backend of this account.
    #[allow(unused)]
    pub mbox: Option<MboxConfig>,
    /// The pimdir backend of this account.
    #[allow(unused)]
    pub pimdir: Option<PimdirConfig>,
    /// The SMTP transport of this account.
    #[allow(unused)]
    pub smtp: Option<SmtpConfig>,
    /// The ManageSieve endpoint of this account.
    #[allow(unused)]
    pub sieve: Option<SieveConfig>,
    /// The v1 `backend` table, kept only to point at MIGRATION.md.
    #[serde(default, skip_serializing)]
    pub backend: Option<IgnoredAny>,
}

/// Envelope-level rendering options.
#[derive(Clone, Debug, Default, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case", deny_unknown_fields)]
pub struct EnvelopeConfig {
    /// `envelope list` rendering options.
    #[serde(default)]
    pub list: EnvelopeListConfig,
}

/// Mailbox aliases and `mailbox list` rendering options.
#[derive(Clone, Debug, Default, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case", deny_unknown_fields)]
pub struct MailboxConfig {
    /// Friendly names mapped to backend-native mailbox ids, resolved
    /// case-insensitively.
    ///
    /// An alias named after a mailbox role overrides the role the backend
    /// reports, the `inbox` one being the default mailbox of a shared
    /// command omitting `-m/--mailbox`.
    #[serde(default, rename = "alias", alias = "aliases")]
    pub aliases: HashMap<String, String>,
    /// `mailbox list` rendering options.
    #[serde(default)]
    pub list: MailboxListConfig,
}

/// `mailbox list` rendering options under `mailbox.list.*`.
#[derive(Clone, Debug, Default, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case", deny_unknown_fields)]
pub struct MailboxListConfig {
    /// Per-column colors of the rendered table.
    #[serde(default)]
    pub table: MailboxListTableConfig,
}

/// Per-column color overrides for the `mailbox list` table.
#[derive(Clone, Debug, Default, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case", deny_unknown_fields)]
pub struct MailboxListTableConfig {
    /// Color of the ID column.
    pub id_color: Option<Color>,
    /// Color of the NAME column.
    pub name_color: Option<Color>,
    /// Color of the ROLE column.
    pub role_color: Option<Color>,
    /// Color of the TOTAL column.
    pub total_color: Option<Color>,
    /// Color of the UNREAD column.
    pub unread_color: Option<Color>,
}

/// Message options under `message.*`.
///
/// Unknown keys are accepted rather than denied, so the rest of a v1
/// `[message]` table (`read`, `write`, `delete`...) keeps loading.
#[derive(Clone, Debug, Default, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case")]
pub struct MessageConfig {
    /// Sending options.
    #[serde(default)]
    pub send: MessageSendConfig,
}

/// Sending options under `message.send.*`.
#[derive(Clone, Debug, Default, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case")]
pub struct MessageSendConfig {
    /// Mailbox a sent message is copied to when `--save` is not passed.
    ///
    /// Leave it unset on Gmail and Microsoft Graph, which file the sent
    /// message themselves.
    pub save_copy: Option<SaveCopyConfig>,
}

/// The `message.send.save-copy` value.
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(untagged)]
pub enum SaveCopyConfig {
    /// `true` for the `sent` mailbox, `false` for no copy, the v1 form.
    Enabled(bool),
    /// A mailbox name, alias or role.
    Mailbox(String),
}

/// `attachment list` rendering options.
#[derive(Clone, Debug, Default, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case", deny_unknown_fields)]
pub struct AttachmentConfig {
    /// `attachment list` rendering options.
    #[serde(default)]
    pub list: AttachmentListConfig,
}

/// `attachment list` rendering options under `attachment.list.*`.
#[derive(Clone, Debug, Default, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case", deny_unknown_fields)]
pub struct AttachmentListConfig {
    /// Per-column colors of the rendered table.
    #[serde(default)]
    pub table: AttachmentListTableConfig,
}

/// Per-column color overrides for the `attachment list` table.
#[derive(Clone, Debug, Default, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case", deny_unknown_fields)]
pub struct AttachmentListTableConfig {
    /// Color of the ID column.
    pub id_color: Option<Color>,
    /// Color of the FILENAME column.
    pub filename_color: Option<Color>,
    /// Color of the TYPE column.
    pub type_color: Option<Color>,
    /// Color of the SIZE column.
    pub size_color: Option<Color>,
    /// Color of the INLINE column.
    pub inline_color: Option<Color>,
    /// Color of the PATH column.
    pub path_color: Option<Color>,
}

/// `account list` rendering options, top-level only.
#[derive(Clone, Debug, Default, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case", deny_unknown_fields)]
pub struct AccountListingConfig {
    /// `account list` rendering options.
    #[serde(default)]
    pub list: AccountListingListConfig,
}

/// `account list` rendering options under `account.list.*`.
#[derive(Clone, Debug, Default, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case", deny_unknown_fields)]
pub struct AccountListingListConfig {
    /// Per-column colors of the rendered table.
    #[serde(default)]
    pub table: AccountListingTableConfig,
}

/// Per-column color overrides for the `account list` table.
#[derive(Clone, Debug, Default, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case", deny_unknown_fields)]
pub struct AccountListingTableConfig {
    /// Color of the NAME column.
    pub name_color: Option<Color>,
    /// Color of the BACKENDS column.
    pub backends_color: Option<Color>,
    /// Color of the DEFAULT column.
    pub default_color: Option<Color>,
}

/// `envelope list` rendering options under `envelope.list.*`.
#[derive(Clone, Debug, Default, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case", deny_unknown_fields)]
pub struct EnvelopeListConfig {
    /// chrono `strftime` format of the DATE column, defaulting to
    /// `"%F %R%:z"`.
    pub datetime_fmt: Option<String>,
    /// Whether the `Date:` offset is converted to the local timezone
    /// before formatting, the default `false` keeping the wire offset.
    pub datetime_local_tz: Option<bool>,
    /// Whether a recent date renders relative to today in the local
    /// timezone (time of day, `yesterday`, weekday), an older one falling
    /// back to `datetime-fmt`, the default `false` never doing so.
    pub datetime_relative: Option<bool>,
    /// Default `-s/--page-size`, the flag winning when passed and 25
    /// being the hard fallback.
    pub page_size: Option<u32>,
    /// Per-column colors and flag glyphs of the rendered table.
    ///
    /// A color is a named [crossterm color], or an `{ Rgb = { r, g, b } }`
    /// or `{ AnsiValue = N }` table.
    ///
    /// [crossterm color]: https://docs.rs/crossterm/latest/crossterm/style/enum.Color.html
    #[serde(default)]
    pub table: EnvelopeListTableConfig,
}

/// Per-column color and flag glyph overrides for the envelopes table.
#[derive(Clone, Debug, Default, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case", deny_unknown_fields)]
pub struct EnvelopeListTableConfig {
    /// FLAGS glyph of a message lacking `\Seen`, defaulting to `*`.
    pub unseen_char: Option<char>,
    /// FLAGS glyph of a message carrying `\Answered`, defaulting to `R`.
    pub replied_char: Option<char>,
    /// FLAGS glyph of a message carrying `\Flagged`, defaulting to `!`.
    pub flagged_char: Option<char>,
    /// ATT glyph of a message with an attachment, defaulting to `@`.
    pub attachment_char: Option<char>,
    /// Color of the ID column.
    pub id_color: Option<Color>,
    /// Color of the FLAGS column.
    pub flags_color: Option<Color>,
    /// Color of the ATT column.
    pub att_color: Option<Color>,
    /// Color of the SUBJECT column.
    pub subject_color: Option<Color>,
    /// Color of the FROM column.
    pub from_color: Option<Color>,
    /// Color of the TO column.
    pub to_color: Option<Color>,
    /// Color of the DATE column.
    pub date_color: Option<Color>,
    /// Color of the SIZE column.
    pub size_color: Option<Color>,
}

/// Table rendering quirks shared by every listing.
///
/// The per-column colors live under `*.list.table.*-color` instead, one
/// block per listing.
#[derive(Clone, Debug, Default, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case", deny_unknown_fields)]
pub struct TableConfig {
    /// One character per table component, a space skipping it,
    /// defaulting to `UTF8_FULL_CONDENSED`.
    ///
    /// [`style_from_preset`] documents the component order.
    ///
    /// [`style_from_preset`]: crate::shared::table::style_from_preset
    pub preset: Option<String>,
    /// Column-arrangement strategy, defaulting to `dynamic`.
    pub arrangement: Option<TableArrangementConfig>,
}

/// Column-arrangement strategy for rendered tables.
#[derive(Clone, Debug, Default, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case", deny_unknown_fields)]
pub enum TableArrangementConfig {
    /// Fit the columns to the terminal width.
    #[default]
    Dynamic,
    /// Fit the columns to the terminal width, always filling it.
    DynamicFullWidth,
    /// Let each column take the width of its widest cell.
    Disabled,
}

impl From<TableArrangementConfig> for ContentArrangement {
    fn from(arrangement: TableArrangementConfig) -> Self {
        match arrangement {
            TableArrangementConfig::Dynamic => ContentArrangement::Dynamic,
            TableArrangementConfig::DynamicFullWidth => ContentArrangement::DynamicFullWidth,
            TableArrangementConfig::Disabled => ContentArrangement::Disabled,
        }
    }
}

/// Parses a backend `server` string into a [`Url`].
///
/// A full URL, a bare authority or a bare host, the two bare forms taking
/// the default scheme. Absence of `://` is what detects them, the parser
/// otherwise reading `mail.example.com:993` as a scheme.
pub fn parse_server(server: &str, default_scheme: &str, allowed: &[&str]) -> Result<Url> {
    let url = if server.contains("://") {
        Url::parse(server)?
    } else {
        Url::parse(&format!("{default_scheme}://{server}"))?
    };

    let scheme = url.scheme();

    if !allowed.contains(&scheme) {
        bail!("Invalid server scheme `{scheme}`: expected one of {allowed:?}");
    }

    Ok(url)
}

/// IMAP configuration.
#[allow(unused)]
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case", deny_unknown_fields)]
pub struct ImapConfig {
    /// IMAP server address, a bare authority or a full URL.
    ///
    /// A bare authority takes `imaps://`, implicit TLS. A full URL is used
    /// verbatim, `imap://` being cleartext with an optional STARTTLS
    /// upgrade. Mirrors [`JmapConfig::server`].
    pub server: String,
    /// TLS provider and custom certificate used by the connection.
    #[serde(default)]
    pub tls: TlsConfig,
    /// Proxy the connection goes through, falling back to the account one
    /// and then to the `all_proxy`/`https_proxy` environment variables.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub proxy: Option<ProxyConfig>,
    /// Whether to upgrade the connection with `STARTTLS` after the
    /// greeting, valid only for an `imap://` server.
    #[serde(default, skip_serializing_if = "is_default")]
    pub starttls: bool,
    /// ALPN identifiers offered during the TLS handshake, defaulting to
    /// the RFC 7595 registered `["imap"]`.
    ///
    /// An empty list skips ALPN negotiation. Only rustls reads it,
    /// `native-tls` ignoring ALPN.
    #[serde(
        default = "default_imap_alpn",
        skip_serializing_if = "is_default_imap_alpn"
    )]
    pub alpn: Vec<String>,
    /// SASL credentials, omitted to skip authentication entirely.
    ///
    /// No `AUTHENTICATE` command is then sent at all. Advertising the
    /// ANONYMOUS mechanism is `sasl.anonymous = {}` instead.
    pub sasl: Option<SaslConfig>,
    /// RFC 4959 SASL-IR quirk, unset following the advertised capability.
    ///
    /// `false` waits for the server's continuation request rather than
    /// inlining the credentials, which Coremail (126.com, 163.com) needs:
    /// it advertises SASL-IR falsely.
    #[serde(default, skip_serializing_if = "is_default")]
    pub sasl_ir: Option<bool>,
    /// RFC 2971 `ID` extension quirks.
    ///
    /// Some providers, notably mail.qq.com and fastmail, want an `ID`
    /// exchange straight after authentication: `id.auto = true` opts in.
    #[serde(default)]
    pub id: ImapIdConfig,
    /// RFC 5256 `SORT` extension options.
    #[serde(default)]
    pub sort: ImapSortConfig,
}

/// Per-account `imap.sort.*` options.
#[derive(Clone, Debug, Default, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case", deny_unknown_fields)]
pub struct ImapSortConfig {
    /// Forces the client-side sort fallback on or off.
    ///
    /// On, the client sorts with SEARCH and FETCH; off, it always issues a
    /// server `SORT`. Unset, the fallback runs only when the server lacks
    /// the SORT capability.
    pub fallback: Option<bool>,
}

/// Per-account `imap.id.*` quirks.
#[derive(Clone, Debug, Default, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case", deny_unknown_fields)]
pub struct ImapIdConfig {
    /// Whether the auth coroutine chains an `ID` round-trip after the
    /// tagged auth response, default `false` skipping it.
    #[serde(default, skip_serializing_if = "is_default")]
    pub auto: bool,
    /// Parameters sent with the auto-`ID` command, empty sending `ID NIL`.
    ///
    /// `true` substitutes himalaya's canned value for a well-known key
    /// (`name`, `version`, `vendor`, `support-url`) and `NIL` otherwise,
    /// `false` always sends `NIL`, and an absent key is not transmitted.
    #[serde(default, skip_serializing_if = "HashMap::is_empty")]
    pub fields: HashMap<String, bool>,
}

/// Header carrying custom keywords inline with a message body.
///
/// Mirrors io-maildir's `KeywordHeader`, kept local so the config
/// schema does not depend on any backend crate.
#[derive(Clone, Copy, Debug, Deserialize, PartialEq, Serialize)]
#[serde(rename_all = "kebab-case")]
pub enum MaildirKeywordHeaderConfig {
    /// `X-Keywords`, comma-separated (OfflineIMAP, mbsync).
    XKeywords,
    /// `X-Label`, space-separated (mutt, notmuch).
    XLabel,
}

/// Per-account `maildir.keywords.*` options, both unset reading none.
#[derive(Clone, Debug, Default, Deserialize, PartialEq, Serialize)]
#[serde(rename_all = "kebab-case", deny_unknown_fields)]
pub struct MaildirKeywordsConfig {
    /// Whether keywords are resolved through each mailbox's own
    /// dovecot-keywords file, which maps a lowercase info-section letter
    /// to a keyword, default `false` leaving those letters unread.
    #[serde(default, skip_serializing_if = "is_default")]
    pub dovecot: bool,
    /// The body header keywords are read from, unset reading none.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub header: Option<MaildirKeywordHeaderConfig>,
}

/// Maildir configuration.
#[allow(unused)]
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case", deny_unknown_fields)]
pub struct MaildirConfig {
    /// The Maildir root, one directory per mailbox below it.
    #[serde(deserialize_with = "shell_expanded_path")]
    pub root: PathBuf,
    /// How custom, non-IANA keywords are read, if at all.
    #[serde(default)]
    pub keywords: MaildirKeywordsConfig,
}

/// m2dir configuration.
#[allow(unused)]
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case", deny_unknown_fields)]
pub struct M2dirConfig {
    /// The m2dir root, one directory per mailbox below it.
    #[serde(deserialize_with = "shell_expanded_path")]
    pub root: PathBuf,
}

/// mbox configuration: a directory of mbox files, plus the spool.
#[allow(unused)]
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case", deny_unknown_fields)]
pub struct MboxConfig {
    /// The directory holding the mbox files, one file per mailbox,
    /// walked recursively.
    #[serde(deserialize_with = "shell_expanded_path")]
    pub root: PathBuf,
    /// The spool surfaced as the `INBOX` mailbox, typically `$MAIL`,
    /// wherever it lives.
    #[serde(
        default,
        deserialize_with = "opt_shell_expanded_path",
        skip_serializing_if = "Option::is_none"
    )]
    pub inbox: Option<PathBuf>,
    /// The variant new messages are written in, and whose quoting reads
    /// undo.
    #[serde(default, skip_serializing_if = "is_default")]
    pub format: MboxFormatConfig,
    /// Whether the children of mailbox `a` live in `a.sbd`, as
    /// Thunderbird lays them out, rather than in `a`.
    #[serde(default, skip_serializing_if = "is_default")]
    pub thunderbird: bool,
    /// The locks every write takes.
    #[serde(default, skip_serializing_if = "is_default")]
    pub lock: MboxLockConfig,
}

/// One of the four mbox variants.
///
/// Mirrors io-mbox's `MboxFormat`, kept local so the config schema does
/// not depend on any backend crate.
#[derive(Clone, Copy, Debug, Default, Deserialize, PartialEq, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum MboxFormatConfig {
    /// `From ` lines quoted with one `>`, lossy.
    Mboxo,
    /// Reversible quoting of `>*From ` lines.
    #[default]
    Mboxrd,
    /// mboxo quoting plus a `Content-Length` header.
    Mboxcl,
    /// No quoting, a `Content-Length` header delimits the body.
    Mboxcl2,
}

/// Per-account `mbox.lock.*` options, both locks taken by default.
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
#[serde(rename_all = "kebab-case", deny_unknown_fields)]
pub struct MboxLockConfig {
    /// Whether to take the `<mbox>.lock` dotlock, which a spool
    /// directory the user cannot write to refuses.
    #[serde(default = "default_true")]
    pub dotlock: bool,
    /// Whether to take the fcntl lock.
    #[serde(default = "default_true")]
    pub fcntl: bool,
    /// Seconds to wait for a lock another process holds, 10 when
    /// unset.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub timeout: Option<u64>,
}

impl Default for MboxLockConfig {
    fn default() -> Self {
        Self {
            dotlock: true,
            fcntl: true,
            timeout: None,
        }
    }
}

fn default_true() -> bool {
    true
}

/// pimdir configuration, a local store read as an offline cache.
///
/// The store is a SQLite index beside content-addressed blobs, populated
/// by the Neverest sync engine.
#[allow(unused)]
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case", deny_unknown_fields)]
pub struct PimdirConfig {
    /// The store directory, holding `pimdir.db` and `objects/`.
    #[serde(deserialize_with = "shell_expanded_path")]
    pub root: PathBuf,
    /// The sync engine account whose collections this client reads,
    /// per pimdir SPEC section 9.2.
    ///
    /// Usually left unset, a store synced by one account being read as
    /// that one. Set it for a store several accounts share, where guessing
    /// would show the wrong mailbox set.
    #[serde(default)]
    pub account: Option<String>,
}

/// SMTP configuration.
#[allow(unused)]
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case", deny_unknown_fields)]
pub struct SmtpConfig {
    /// SMTP server address, a bare authority or a full URL.
    ///
    /// A bare authority takes `smtps://`, implicit TLS. A full URL is used
    /// verbatim, `smtp://` being cleartext with an optional STARTTLS
    /// upgrade. Mirrors [`JmapConfig::server`].
    pub server: String,
    /// TLS provider and custom certificate used by the connection.
    #[serde(default)]
    pub tls: TlsConfig,
    /// Proxy the connection goes through, falling back to the account one
    /// and then to the `all_proxy`/`https_proxy` environment variables.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub proxy: Option<ProxyConfig>,
    /// Whether to upgrade the connection with `STARTTLS` after the
    /// greeting, valid only for an `smtp://` server.
    #[serde(default, skip_serializing_if = "is_default")]
    pub starttls: bool,
    /// ALPN identifiers offered during the TLS handshake, defaulting to
    /// the RFC 7595 registered `["smtp"]`.
    ///
    /// An empty list skips ALPN negotiation. Only rustls reads it,
    /// `native-tls` ignoring ALPN.
    #[serde(
        default = "default_smtp_alpn",
        skip_serializing_if = "is_default_smtp_alpn"
    )]
    pub alpn: Vec<String>,
    /// SASL credentials, see [`ImapConfig::sasl`].
    pub sasl: Option<SaslConfig>,
}

/// ManageSieve configuration.
#[allow(unused)]
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case", deny_unknown_fields)]
pub struct SieveConfig {
    /// ManageSieve server address, a bare authority or a full URL.
    ///
    /// RFC 5804 registers one port and reaches TLS on it through STARTTLS,
    /// so a bare authority takes `sieve://` unlike the IMAP and SMTP ones.
    /// `sieves://` is for the deployments the specification does not
    /// define, listening for a handshake straight away.
    pub server: String,
    /// TLS provider and custom certificate used by the connection.
    #[serde(default)]
    pub tls: TlsConfig,
    /// Proxy the connection goes through, falling back to the account one
    /// and then to the `all_proxy`/`https_proxy` environment variables.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub proxy: Option<ProxyConfig>,
    /// Whether to upgrade the connection with `STARTTLS` after the
    /// greeting, unset following the scheme.
    ///
    /// On for `sieve://`, the only upgrade path RFC 5804 defines, off for
    /// `sieves://` and `unix://`. Setting it on `sieves://` is an error,
    /// TLS being already up.
    #[serde(default, skip_serializing_if = "is_default")]
    pub starttls: Option<bool>,
    /// ALPN identifiers offered during the TLS handshake, defaulting to
    /// none since ManageSieve registers none.
    #[serde(
        default = "default_sieve_alpn",
        skip_serializing_if = "is_default_sieve_alpn"
    )]
    pub alpn: Vec<String>,
    /// Whether a mechanism disclosing a reusable credential may run over a
    /// cleartext connection.
    ///
    /// `plain`, `login`, `oauthbearer` and `xoauth2` hand a passive
    /// observer something it can replay, so they are refused unless the
    /// connection is encrypted. Set this for a trusted local link.
    #[serde(default, skip_serializing_if = "is_default")]
    pub allow_cleartext_auth: bool,
    /// SASL credentials, see [`ImapConfig::sasl`].
    pub sasl: Option<SaslConfig>,
}

/// Proxy configuration.
///
/// `url` is a `socks5://`, `socks5h://` or `http://` proxy URL. Its user
/// info authenticates too, but `username` and `password` keep the secret
/// out of the URL.
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case", deny_unknown_fields)]
pub struct ProxyConfig {
    /// The proxy URL.
    pub url: String,
    /// The proxy username, required by `password`.
    pub username: Option<String>,
    /// The proxy password.
    pub password: Option<Secret>,
}

impl ProxyConfig {
    /// Resolves an optional configuration, an absent one reading the
    /// environment at connect time.
    pub fn resolve(config: Option<Self>, resolver: &mut SecretResolver) -> Result<Proxy> {
        match config {
            Some(config) => config.try_into_proxy(resolver),
            None => Ok(Proxy::System),
        }
    }

    /// Resolves the configuration into a runtime [`Proxy`], the password
    /// going through `resolver`.
    pub fn try_into_proxy(self, resolver: &mut SecretResolver) -> Result<Proxy> {
        let mut proxy = Proxy::from_url(&self.url)?;

        let auth = match (self.username, self.password) {
            (None, None) => return Ok(proxy),
            (None, Some(_)) => bail!("Proxy password requires a username"),
            (Some(user), pass) => ProxyAuth {
                user,
                pass: match pass {
                    Some(pass) => resolver.resolve(pass)?,
                    None => SecretString::default(),
                },
            },
        };

        match &mut proxy {
            Proxy::Socks5 { auth: slot, .. } | Proxy::Http { auth: slot, .. } => {
                *slot = Some(auth);
            }
            Proxy::None | Proxy::System => {}
        }

        Ok(proxy)
    }
}

/// SSL/TLS configuration.
#[derive(Clone, Debug, Default, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case", deny_unknown_fields)]
pub struct TlsConfig {
    /// The TLS implementation, defaulting to rustls.
    pub provider: Option<TlsProviderConfig>,
    /// Rustls-only options.
    #[serde(default)]
    pub rustls: RustlsConfig,
    /// A custom certificate to trust, in PEM format.
    #[serde(default, deserialize_with = "opt_shell_expanded_path")]
    pub cert: Option<PathBuf>,
}

/// SSL/TLS provider configuration.
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case", deny_unknown_fields)]
pub enum TlsProviderConfig {
    /// The pure-Rust rustls stack.
    Rustls,
    /// The platform's own TLS stack.
    NativeTls,
}

/// Rustls configuration.
#[derive(Clone, Debug, Default, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case", deny_unknown_fields)]
pub struct RustlsConfig {
    /// The cryptographic provider rustls runs on.
    pub crypto: Option<RustlsCryptoConfig>,
}

/// Rustls crypto provider configuration.
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case", deny_unknown_fields)]
pub enum RustlsCryptoConfig {
    /// aws-lc-rs.
    Aws,
    /// ring.
    Ring,
}

impl TlsConfig {
    /// Builds the runtime [`Tls`] handle the connect helpers expect,
    /// folding in the protocol-level `alpn` list.
    ///
    /// The TOML schema never exposes `tls.rustls.alpn` directly, the
    /// per-protocol `*.alpn` field standing for it. An empty list skips
    /// ALPN.
    pub fn into_tls(self, alpn: Vec<String>) -> Tls {
        Tls {
            provider: self.provider.map(|p| match p {
                TlsProviderConfig::Rustls => TlsProvider::Rustls,
                TlsProviderConfig::NativeTls => TlsProvider::NativeTls,
            }),
            rustls: Rustls {
                crypto: self.rustls.crypto.map(|c| match c {
                    RustlsCryptoConfig::Aws => RustlsCrypto::Aws,
                    RustlsCryptoConfig::Ring => RustlsCrypto::Ring,
                }),
                alpn,
            },
            cert: self.cert,
        }
    }
}

/// SASL configuration, exactly one mechanism per `[*.sasl]` block.
///
/// Each variant carries only what its mechanism transmits, and serde picks
/// it from the field name.
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case", deny_unknown_fields)]
pub enum SaslConfig {
    /// The ANONYMOUS mechanism.
    Anonymous(SaslAnonymousConfig),
    /// The LOGIN mechanism.
    Login(SaslLoginConfig),
    /// The PLAIN mechanism.
    Plain(SaslPlainConfig),
    /// The OAUTHBEARER mechanism.
    Oauthbearer(SaslOauthbearerConfig),
    /// The XOAUTH2 mechanism.
    Xoauth2(SaslXoauth2Config),
    /// The SCRAM-SHA-256 mechanism.
    #[serde(rename = "scram-sha-256")]
    ScramSha256(SaslScramSha256Config),
}

/// SASL ANONYMOUS configuration <sup>[rfc4505]</sup>.
///
/// [rfc4505]: https://www.iana.org/go/rfc4505
#[derive(Clone, Debug, Default, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case", deny_unknown_fields)]
pub struct SaslAnonymousConfig {
    /// The optional trace message handed to the server.
    pub message: Option<String>,
}

/// SASL LOGIN configuration <sup>[draft]</sup>.
///
/// [draft]: https://datatracker.ietf.org/doc/html/draft-murchison-sasl-login-00
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case", deny_unknown_fields)]
pub struct SaslLoginConfig {
    /// The account to authenticate as.
    #[serde(deserialize_with = "shell_expanded_string")]
    pub username: String,
    /// Its password.
    pub password: Secret,
}

/// SASL PLAIN configuration <sup>[rfc4616]</sup>.
///
/// [rfc4616]: https://www.iana.org/go/rfc4616
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case", deny_unknown_fields)]
pub struct SaslPlainConfig {
    /// The identity to act as, when it differs from the authenticated one.
    pub authzid: Option<String>,
    /// The account to authenticate as.
    #[serde(deserialize_with = "shell_expanded_string")]
    #[serde(alias = "username")]
    pub authcid: String,
    /// Its password.
    #[serde(alias = "password")]
    pub passwd: Secret,
}

/// SASL OAUTHBEARER configuration <sup>[rfc7628]</sup>.
///
/// The host and port echoed in the GS2 header come from the live server
/// URL at connect time, so neither is configured here.
///
/// [rfc7628]: https://www.iana.org/go/rfc7628
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case", deny_unknown_fields)]
pub struct SaslOauthbearerConfig {
    /// The account to authenticate as.
    #[serde(deserialize_with = "shell_expanded_string")]
    pub username: String,
    /// Its OAuth 2.0 access token.
    pub token: Secret,
}

/// SASL XOAUTH2 configuration, [Google's pre-standard scheme][xoauth2].
///
/// [xoauth2]: https://developers.google.com/gmail/imap/xoauth2-protocol
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case", deny_unknown_fields)]
pub struct SaslXoauth2Config {
    /// The account to authenticate as.
    #[serde(deserialize_with = "shell_expanded_string")]
    pub username: String,
    /// Its OAuth 2.0 access token.
    pub token: Secret,
}

/// SASL SCRAM-SHA-256 configuration <sup>[rfc7677]</sup>.
///
/// [rfc7677]: https://www.iana.org/go/rfc7677
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case", deny_unknown_fields)]
pub struct SaslScramSha256Config {
    /// The account to authenticate as.
    #[serde(deserialize_with = "shell_expanded_string")]
    pub username: String,
    /// Its password.
    pub password: Secret,
}

impl SaslConfig {
    /// Resolves the configuration into a runtime [`Sasl`].
    ///
    /// The host and port come from the live server URL. OAUTHBEARER alone
    /// reads them, echoing them in its GS2 header.
    ///
    /// The credential goes through `resolver`, so an account whose IMAP,
    /// SMTP and ManageSieve blocks name one command spawns it once.
    pub fn try_into_sasl(
        self,
        host: impl ToString,
        port: u16,
        resolver: &mut SecretResolver,
    ) -> Result<Sasl> {
        Ok(match self {
            SaslConfig::Anonymous(c) => Sasl::Anonymous(SaslAnonymousCreds { message: c.message }),
            SaslConfig::Login(c) => Sasl::Login(SaslLoginCreds {
                username: c.username,
                password: resolver.resolve(c.password)?,
            }),
            SaslConfig::Plain(c) => Sasl::Plain(SaslPlainCreds {
                authzid: c.authzid,
                authcid: c.authcid,
                passwd: resolver.resolve(c.passwd)?,
            }),
            SaslConfig::Oauthbearer(c) => Sasl::Oauthbearer(SaslOauthbearerCreds {
                username: c.username,
                host: host.to_string(),
                port,
                token: resolver.resolve(c.token)?,
            }),
            SaslConfig::Xoauth2(c) => Sasl::Xoauth2(SaslXoauth2Creds {
                username: c.username,
                token: resolver.resolve(c.token)?,
            }),
            // NOTE: an empty nonce means draw one for me: the client fills
            // it in, an I/O-free coroutine having no randomness of its own.
            SaslConfig::ScramSha256(c) => Sasl::ScramSha256(SaslScramCreds {
                username: c.username,
                password: resolver.resolve(c.password)?,
                nonce: Vec::new(),
                channel_binding: SaslGs2ChannelBinding::Unsupported,
            }),
        })
    }
}

/// JMAP configuration.
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case", deny_unknown_fields)]
pub struct JmapConfig {
    /// The JMAP server address, a bare authority or a full URL.
    ///
    /// A bare authority is discovered through `GET /.well-known/jmap`,
    /// a full URL reaching the session endpoint directly. The schemes are
    /// `http`, `https`, `jmap` and `jmaps`.
    pub server: String,
    /// TLS provider and custom certificate used by the connection.
    #[serde(default)]
    pub tls: TlsConfig,
    /// Proxy the connection goes through, falling back to the account one
    /// and then to the `all_proxy`/`https_proxy` environment variables.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub proxy: Option<ProxyConfig>,
    /// ALPN identifiers offered during the TLS handshake, defaulting to
    /// `["http/1.1"]`, JMAP riding on HTTP/1.1.
    ///
    /// An empty list skips ALPN negotiation. Only rustls reads it,
    /// `native-tls` ignoring ALPN.
    #[serde(
        default = "default_jmap_alpn",
        skip_serializing_if = "is_default_jmap_alpn"
    )]
    pub alpn: Vec<String>,
    /// Authentication configuration.
    pub auth: JmapAuthConfig,
    /// Identity id `message send` submits under, required for JMAP send
    /// alone and discoverable with `himalaya jmap identity get`.
    pub identity_id: Option<String>,
    /// Mailbox id `message send` stages a message in before submitting it.
    ///
    /// Required for JMAP send alone, and discoverable with `himalaya jmap
    /// mailbox query --role drafts`.
    pub drafts_mailbox_id: Option<String>,
    /// Mailbox id a sent message is moved to once submitted, defaulting
    /// to the `sent`-role mailbox.
    ///
    /// Discoverable with `himalaya jmap mailbox query --role sent`.
    pub sent_mailbox_id: Option<String>,
}

/// JMAP authentication configuration.
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case", deny_unknown_fields)]
pub enum JmapAuthConfig {
    /// A full `Authorization` header value, sent verbatim.
    Header(Secret),
    /// An OAuth 2.0 bearer token.
    Bearer {
        /// The access token.
        token: Secret,
    },
    /// HTTP Basic authentication.
    Basic {
        /// The account to authenticate as.
        #[serde(deserialize_with = "shell_expanded_string")]
        username: String,
        /// Its password.
        password: Secret,
    },
}

/// Gmail REST API configuration.
///
/// Gmail has no per-account server address, the client always talking to
/// gmail.googleapis.com, so only the mailbox owner, TLS and the OAuth 2.0
/// credential are configured.
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case", deny_unknown_fields)]
pub struct GmailConfig {
    /// The mailbox owner, defaulting to `me`, the authenticated user.
    #[serde(default = "default_gmail_user_id")]
    pub user_id: String,
    /// TLS provider and custom certificate used by the connection.
    #[serde(default)]
    pub tls: TlsConfig,
    /// Proxy the connection goes through, falling back to the account one
    /// and then to the `all_proxy`/`https_proxy` environment variables.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub proxy: Option<ProxyConfig>,
    /// ALPN identifiers offered during the TLS handshake, defaulting to
    /// `["http/1.1"]`, the REST API riding on HTTP/1.1.
    ///
    /// An empty list skips ALPN negotiation. Only rustls reads it,
    /// `native-tls` ignoring ALPN.
    #[serde(
        default = "default_gmail_alpn",
        skip_serializing_if = "is_default_gmail_alpn"
    )]
    pub alpn: Vec<String>,
    /// Authentication configuration.
    pub auth: GmailAuthConfig,
}

fn default_gmail_user_id() -> String {
    String::from("me")
}

fn default_gmail_alpn() -> Vec<String> {
    vec![String::from("http/1.1")]
}

/// Gmail authentication configuration.
///
/// Gmail accepts OAuth 2.0 bearer tokens alone, so this is a short-lived
/// access token an external helper such as ortie mints. Refreshing it is
/// the caller's business.
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case", deny_unknown_fields)]
pub struct GmailAuthConfig {
    /// The access token, sent as `Bearer <token>`.
    pub token: Secret,
}

/// Microsoft Graph API configuration.
///
/// Graph has no per-account server address, the client always talking to
/// graph.microsoft.com, so only the mailbox owner, TLS and the OAuth 2.0
/// credential are configured.
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case", deny_unknown_fields)]
pub struct MsgraphConfig {
    /// The mailbox owner, defaulting to `me`, the authenticated user.
    ///
    /// Set it to a user id or a principal name to target another mailbox.
    #[serde(default = "default_msgraph_user_id")]
    pub user_id: String,
    /// TLS provider and custom certificate used by the connection.
    #[serde(default)]
    pub tls: TlsConfig,
    /// Proxy the connection goes through, falling back to the account one
    /// and then to the `all_proxy`/`https_proxy` environment variables.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub proxy: Option<ProxyConfig>,
    /// ALPN identifiers offered during the TLS handshake, defaulting to
    /// `["http/1.1"]`, the Graph API riding on HTTP/1.1.
    ///
    /// An empty list skips ALPN negotiation. Only rustls reads it,
    /// `native-tls` ignoring ALPN.
    #[serde(
        default = "default_msgraph_alpn",
        skip_serializing_if = "is_default_msgraph_alpn"
    )]
    pub alpn: Vec<String>,
    /// Authentication configuration.
    pub auth: MsgraphAuthConfig,
}

fn default_msgraph_user_id() -> String {
    String::from("me")
}

fn default_msgraph_alpn() -> Vec<String> {
    vec![String::from("http/1.1")]
}

/// Microsoft Graph authentication configuration.
///
/// Graph accepts OAuth 2.0 bearer tokens alone, so this is a short-lived
/// access token an external helper such as ortie mints. Refreshing it is
/// the caller's business.
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case", deny_unknown_fields)]
pub struct MsgraphAuthConfig {
    /// The access token, sent as `Bearer <token>`.
    pub token: Secret,
}

#[cfg(test)]
mod tests {
    use std::env::var;

    use super::*;

    const IMAP: &[&str] = &["imap", "imaps"];

    #[test]
    fn maildir_root_alone_keeps_keywords_off() {
        let config: MaildirConfig = toml::from_str(r#"root = "/tmp/mail""#).unwrap();
        assert!(!config.keywords.dovecot);
        assert_eq!(config.keywords.header, None);
    }

    #[test]
    fn maildir_keyword_options_parse() {
        let config: MaildirConfig = toml::from_str(
            r#"
                root = "/tmp/mail"
                keywords.dovecot = true
                keywords.header = "x-label"
            "#,
        )
        .unwrap();

        assert!(config.keywords.dovecot);
        assert_eq!(
            config.keywords.header,
            Some(MaildirKeywordHeaderConfig::XLabel)
        );
    }

    #[test]
    fn mbox_root_alone_takes_both_locks_and_writes_mboxrd() {
        let config: MboxConfig = toml::from_str(r#"root = "/tmp/mail""#).unwrap();

        assert_eq!(config.inbox, None);
        assert_eq!(config.format, MboxFormatConfig::Mboxrd);
        assert!(!config.thunderbird);
        assert_eq!(config.lock, MboxLockConfig::default());
        assert!(config.lock.dotlock && config.lock.fcntl);
    }

    #[test]
    fn mbox_options_parse() {
        let config: MboxConfig = toml::from_str(
            r#"
                root = "/tmp/mail"
                inbox = "/var/mail/me"
                format = "mboxcl2"
                thunderbird = true
                lock.dotlock = false
                lock.timeout = 30
            "#,
        )
        .unwrap();

        assert_eq!(config.inbox, Some(PathBuf::from("/var/mail/me")));
        assert_eq!(config.format, MboxFormatConfig::Mboxcl2);
        assert!(config.thunderbird);
        assert!(!config.lock.dotlock && config.lock.fcntl);
        assert_eq!(config.lock.timeout, Some(30));
    }

    #[test]
    fn sieve_config_defaults_to_no_alpn_and_refuses_cleartext_auth() {
        let config: SieveConfig = toml::from_str(
            r#"
                server = "sieve.example.com:4190"
            "#,
        )
        .unwrap();

        assert_eq!(config.server, "sieve.example.com:4190");
        assert_eq!(config.starttls, None);
        assert!(config.alpn.is_empty());
        assert!(!config.allow_cleartext_auth);
        assert!(config.sasl.is_none());
    }

    #[test]
    fn bare_host_defaults_to_secure_scheme() {
        let url = parse_server("mail.example.com", "imaps", IMAP).unwrap();
        assert_eq!(url.scheme(), "imaps");
        assert_eq!(url.host_str(), Some("mail.example.com"));
        // NOTE: with no explicit port, the backend client applies the
        // protocol default rather than this parser.
        assert_eq!(url.port(), None);
    }

    #[test]
    fn bare_host_port_keeps_port_and_secure_scheme() {
        let url = parse_server("mail.example.com:1993", "imaps", IMAP).unwrap();
        assert_eq!(url.scheme(), "imaps");
        assert_eq!(url.host_str(), Some("mail.example.com"));
        assert_eq!(url.port(), Some(1993));
    }

    #[test]
    fn full_url_scheme_host_port_is_kept_verbatim() {
        let url = parse_server("imap://mail.example.com:143", "imaps", IMAP).unwrap();
        assert_eq!(url.scheme(), "imap");
        assert_eq!(url.host_str(), Some("mail.example.com"));
        assert_eq!(url.port(), Some(143));
    }

    #[test]
    fn unknown_scheme_is_rejected() {
        let err = parse_server("ftp://mail.example.com", "imaps", IMAP).unwrap_err();
        assert!(err.to_string().contains("Invalid server scheme `ftp`"));
    }

    /// himalaya-tui spells the identity `from` and `from-name`, and one
    /// file backs both binaries, so a config it wrote must reach the same
    /// fields the composers read.
    #[test]
    fn the_composing_config_reads_under_the_tui_spelling() {
        let config: Config = toml::from_str(
            r#"
            from-name = "Alice"
            signature = "Alice"

            [accounts.example]
            from = "alice@example.org"
            from-name = "Alice at work"
            signature-delim = "~~~\n"
            "#,
        )
        .expect("the himalaya-tui spelling must deserialize");

        let account = config.accounts.get("example").expect("the example account");

        assert_eq!(config.display_name.as_deref(), Some("Alice"));
        assert_eq!(config.signature.as_deref(), Some("Alice"));
        assert_eq!(account.email.as_deref(), Some("alice@example.org"));
        assert_eq!(account.display_name.as_deref(), Some("Alice at work"));
        assert_eq!(account.signature_delim.as_deref(), Some("~~~\n"));
    }

    #[test]
    fn backends_inherit_the_account_proxy_unless_they_name_one() {
        let mut config: Config = toml::from_str(
            r#"
            [accounts.example]
            proxy.url = "socks5h://account:1080"
            imap.server = "imap.example.org"
            smtp.server = "smtp.example.org"
            smtp.proxy.url = "http://smtp:3128"
            "#,
        )
        .expect("the proxy blocks must deserialize");

        let (_, account) = config.take_named_account("example").unwrap();
        let proxy = |proxy: Option<ProxyConfig>| proxy.map(|proxy| proxy.url);

        assert_eq!(
            proxy(account.imap.unwrap().proxy).as_deref(),
            Some("socks5h://account:1080")
        );
        assert_eq!(
            proxy(account.smtp.unwrap().proxy).as_deref(),
            Some("http://smtp:3128")
        );
    }

    #[test]
    fn local_roots_expand_the_leading_tilde() {
        let home = PathBuf::from(var("HOME").expect("HOME must be set"));

        let maildir: MaildirConfig = toml::from_str(r#"root = "~/Mail""#).unwrap();
        let m2dir: M2dirConfig = toml::from_str(r#"root = "~/Mail""#).unwrap();
        let pimdir: PimdirConfig = toml::from_str(r#"root = "~/Mail""#).unwrap();
        let mbox: MboxConfig = toml::from_str(
            r#"root = "~/Mail"
inbox = "~/spool""#,
        )
        .unwrap();

        assert_eq!(maildir.root, home.join("Mail"));
        assert_eq!(m2dir.root, home.join("Mail"));
        assert_eq!(pimdir.root, home.join("Mail"));
        assert_eq!(mbox.root, home.join("Mail"));
        assert_eq!(mbox.inbox, Some(home.join("spool")));
    }

    #[test]
    fn optional_paths_expand_the_leading_tilde_and_stay_absent() {
        let home = PathBuf::from(var("HOME").expect("HOME must be set"));

        let tls: TlsConfig = toml::from_str(r#"cert = "~/ca.pem""#).unwrap();
        assert_eq!(tls.cert, Some(home.join("ca.pem")));

        let tls: TlsConfig = toml::from_str("").unwrap();
        assert_eq!(tls.cert, None);
    }

    #[test]
    fn path_is_preserved_for_full_url() {
        let url = parse_server("https://example.com/jmap/session", "https", &["https"]).unwrap();
        assert_eq!(url.scheme(), "https");
        assert_eq!(url.path(), "/jmap/session");
    }
}