vta-cli-common 0.74.0

Shared CLI command handlers and rendering helpers for VTA CLIs
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
//! `pnm calendar connect` — a guided way to connect a calendar (VTI-CAL-119 – 125).
//!
//! It asks the VTA which providers it offers and by which ways in
//! (`vta/calendar/connectors/providers/list/0.2`), offers only those — Apple iCloud, Google,
//! Microsoft, busy time from a private iCal address, or another CalDAV server — in the order
//! the VTA recommends them, and then connects with the defaults most people want: write busy
//! time (no titles) and read busy time back. Every question has a flag, so it runs without a
//! terminal too: `pnm calendar connect --provider microsoft --context work`.
//!
//! It signs in once and then offers the other trust contexts the principal has standing in:
//! each one added is written into a calendar of its own at the provider, with its own mode,
//! calendar name and whether busy time counts there (VTI-CAL-127). Before the first is added it
//! says what one account holding several contexts means (VTI-CAL-131). What the VTA does not
//! offer is answered with why (VTI-CAL-132), and `--help-operator` prints the operator's exact
//! fix ([`super::calendar_connector_help`]).
//!
//! The decisions ([`plan`]) are kept apart from the terminal ([`Ask`]) so they are tested with
//! scripted answers; secrets (a password, an iCal address) are read without echo, or from stdin
//! when piped, and sealed to the VTA before anything is sent (VTI-CAL-106, 124).

use std::io::IsTerminal;

use serde_json::{Value, json};
use vta_sdk::prelude::*;
use vta_sdk::trust_tasks as tt;

use super::calendar_connector_help::{self as help, offer_help, operator_guide, operator_help};
use super::calendar_connectors::{
    Loopback, SHARED_ACCOUNT_NOTICE, busy_choice, call_newest, device_outcome, device_wait, done,
    grant, read_secret, seal_ics_address, seal_password,
};
use crate::render::{DIM, GREEN, RESET, YELLOW, is_json_output, print_json};

type CmdResult = Result<(), Box<dyn std::error::Error>>;

/// Apple's CalDAV server.
pub const ICLOUD_CALDAV: &str = "https://caldav.icloud.com/";

/// What `pnm calendar connect` was given on the command line. Anything left `None` is asked
/// for — or, without a terminal, refused with the flag that gives it.
#[derive(Debug, Default, Clone)]
#[non_exhaustive]
pub struct ConnectOptions {
    /// `apple`, `google`, `microsoft`, `ics-busy` or `caldav`.
    pub provider: Option<String>,
    pub context: Option<String>,
    pub label: Option<String>,
    /// `busy` (default), `titles` or `off`.
    pub write: Option<String>,
    /// Do not read busy time back.
    pub no_busy: bool,
    /// `device-code` or `authorization-code` (Google and Microsoft).
    pub flow: Option<String>,
    /// CalDAV: the account (an Apple ID for iCloud).
    pub username: Option<String>,
    /// CalDAV (another server): its HTTPS address.
    pub endpoint: Option<String>,
    /// Ask nothing: every value comes from a flag or a default.
    pub non_interactive: bool,
    /// More trust contexts the connector serves, each written as `write` into a calendar of its
    /// own (VTI-CAL-127).
    pub also_contexts: Vec<String>,
    /// The name of the first context's calendar at the provider; default `VTI — <context>`.
    pub calendar_name: Option<String>,
    /// Print what this VTA does not offer and the operator's exact fix for each, and stop.
    pub help_operator: bool,
}

impl ConnectOptions {
    /// Options with nothing given: everything is asked.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }
}

/// The questions the wizard asks, so tests can answer them.
pub trait Ask {
    /// Choose one of `items`; `default` is pre-selected.
    fn select(&mut self, prompt: &str, items: &[String], default: usize) -> Result<usize, String>;
    /// A line of text; `default` is offered.
    fn input(&mut self, prompt: &str, default: Option<&str>) -> Result<String, String>;
    /// Yes or no.
    fn confirm(&mut self, prompt: &str, default: bool) -> Result<bool, String>;
    /// Tell the principal something before the next question.
    fn say(&mut self, _text: &str) {}
}

/// The terminal.
struct Terminal;

impl Ask for Terminal {
    fn select(&mut self, prompt: &str, items: &[String], default: usize) -> Result<usize, String> {
        dialoguer::Select::new()
            .with_prompt(prompt)
            .items(items)
            .default(default)
            .interact()
            .map_err(|e| e.to_string())
    }

    fn input(&mut self, prompt: &str, default: Option<&str>) -> Result<String, String> {
        let mut i = dialoguer::Input::<String>::new().with_prompt(prompt);
        if let Some(d) = default {
            i = i.default(d.to_string());
        }
        i.interact_text().map_err(|e| e.to_string())
    }

    fn confirm(&mut self, prompt: &str, default: bool) -> Result<bool, String> {
        dialoguer::Confirm::new()
            .with_prompt(prompt)
            .default(default)
            .interact()
            .map_err(|e| e.to_string())
    }

    fn say(&mut self, text: &str) {
        println!("{YELLOW}{text}{RESET}");
    }
}

/// A calendar the wizard can connect.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Choice {
    Apple,
    Google,
    Microsoft,
    IcsBusy,
    Caldav,
}

impl Choice {
    const ALL: [Self; 5] = [
        Self::Apple,
        Self::Google,
        Self::Microsoft,
        Self::IcsBusy,
        Self::Caldav,
    ];

    fn flag(self) -> &'static str {
        match self {
            Self::Apple => "apple",
            Self::Google => "google",
            Self::Microsoft => "microsoft",
            Self::IcsBusy => "ics-busy",
            Self::Caldav => "caldav",
        }
    }

    fn menu(self) -> &'static str {
        match self {
            Self::Apple => "Apple iCloud",
            Self::Google => "Google Calendar",
            Self::Microsoft => "Microsoft (Outlook.com, Microsoft 365)",
            Self::IcsBusy => "Busy time only, from a private iCal address (any calendar)",
            Self::Caldav => "Another CalDAV server (Fastmail, Nextcloud, …)",
        }
    }

    fn label(self) -> &'static str {
        match self {
            Self::Apple => "iCloud",
            Self::Google => "Google Calendar",
            Self::Microsoft => "Outlook",
            Self::IcsBusy => "Busy time",
            Self::Caldav => "Calendar",
        }
    }

    /// The provider as the VTA names it.
    fn provider(self) -> &'static str {
        match self {
            Self::Apple | Self::Caldav => "caldav",
            Self::Google => "google",
            Self::Microsoft => "microsoft",
            Self::IcsBusy => "icsBusy",
        }
    }

    fn parse(s: &str) -> Option<Self> {
        Self::ALL
            .into_iter()
            .find(|c| c.flag() == s || (s == "icloud" && *c == Self::Apple))
    }
}

/// What the wizard decided.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Plan {
    pub choice: Choice,
    pub context: String,
    pub label: String,
    /// `None` for busy time only (`icsBusy` writes nothing).
    pub write: Option<String>,
    pub busy: bool,
    /// `deviceCode` or `authorizationCode`, for Google and Microsoft.
    pub flow: Option<&'static str>,
    pub endpoint: Option<String>,
    pub username: Option<String>,
    /// The first context's calendar name; `None`: `VTI — <context>`.
    pub calendar_name: Option<String>,
    /// The first context's community overrides, as `(community DID, mode)`.
    pub communities: Vec<(String, String)>,
    /// The other contexts the connector serves (VTI-CAL-127).
    pub also: Vec<AlsoContext>,
    /// Where busy time read back counts; empty: the first context alone.
    pub busy_contexts: Vec<String>,
}

/// Another trust context a connector serves, with a calendar of its own.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AlsoContext {
    pub context: String,
    pub write: String,
    pub calendar_name: Option<String>,
    pub communities: Vec<(String, String)>,
}

impl Plan {
    /// The `coverage` a create sends (VTI-CAL-127). `None` for busy time only.
    #[must_use]
    pub fn coverage(&self) -> Option<Value> {
        let write = self.write.as_ref()?;
        let one = |ctx: &str, w: &str, name: &Option<String>, comm: &[(String, String)]| {
            let mut v = json!({ "contextId": ctx, "write": w });
            if let Some(n) = name {
                v["calendarName"] = json!(n);
            }
            if !comm.is_empty() {
                v["communities"] = json!(
                    comm.iter()
                        .map(|(c, m)| json!({ "community": c, "write": m }))
                        .collect::<Vec<_>>()
                );
            }
            v
        };
        let mut out = vec![one(
            &self.context,
            write,
            &self.calendar_name,
            &self.communities,
        )];
        out.extend(
            self.also
                .iter()
                .map(|a| one(&a.context, &a.write, &a.calendar_name, &a.communities)),
        );
        Some(json!(out))
    }
}

/// What a context is called in the picker: its name, and its id where they differ.
fn context_item(contexts: &[(String, String)], id: &str) -> String {
    match contexts.iter().find(|(i, _)| i == id) {
        Some((_, name)) if !name.is_empty() && name != id => format!("{name} ({id})"),
        _ => id.to_string(),
    }
}

/// `VTI — <name>`, the default a calendar is named by (VTI-CAL-127).
fn default_calendar_name(contexts: &[(String, String)], id: &str) -> String {
    let name = contexts
        .iter()
        .find(|(i, _)| i == id)
        .map_or(id, |(_, n)| if n.is_empty() { id } else { n.as_str() });
    format!("VTI \u{2014} {name}")
}

const MODES: [&str; 3] = ["busy", "titles", "off"];

fn mode_items() -> [String; 3] {
    [
        "Busy — each event's times, no titles (recommended)".to_string(),
        "Titles — each event's title and times".to_string(),
        "Nothing — only read my busy time".to_string(),
    ]
}

/// A context's calendar name and community overrides, asked (VTI-CAL-103, 127).
fn ask_calendar(
    a: &mut dyn Ask,
    contexts: &[(String, String)],
    ctx: &str,
) -> Result<(Option<String>, Vec<(String, String)>), String> {
    let default = default_calendar_name(contexts, ctx);
    let name = a.input(
        &format!(
            "Name of {}'s calendar at the provider",
            context_item(contexts, ctx)
        ),
        Some(&default),
    )?;
    let name = (name.trim() != default && !name.trim().is_empty()).then(|| name.trim().to_string());
    let mut communities = Vec::new();
    while a.confirm(
        &format!(
            "Write a different mode for one community in {}?",
            context_item(contexts, ctx)
        ),
        false,
    )? {
        let did = a.input("The community's DID", None)?;
        if did.trim().is_empty() {
            break;
        }
        let m = MODES[a.select("What should be written for it?", &mode_items(), 0)?];
        communities.push((did.trim().to_string(), m.to_string()));
    }
    Ok((name, communities))
}

fn offer<'a>(offers: &'a Value, provider: &str) -> Option<&'a Value> {
    offers["providers"]
        .as_array()?
        .iter()
        .find(|o| o["provider"] == provider)
}

/// The ways in this command can complete, in the VTA's order: a device code, and an
/// authorization code caught on a loopback port here.
fn flows_here(o: &Value) -> Vec<&'static str> {
    o["flows"]
        .as_array()
        .into_iter()
        .flatten()
        .filter_map(|f| match f["flow"].as_str() {
            Some("deviceCode") => Some("deviceCode"),
            Some("authorizationCode")
                if f["redirectKinds"]
                    .as_array()
                    .is_some_and(|k| k.iter().any(|k| k == "loopback")) =>
            {
                Some("authorizationCode")
            }
            _ => None,
        })
        .collect()
}

/// Why `c` cannot be connected through this VTA, or `None` when it can.
fn unavailable(offers: &Value, c: Choice) -> Option<String> {
    let Some(o) = offer(offers, c.provider()) else {
        return Some("this VTA does not know it".into());
    };
    if o["available"] != true {
        // `reason` (providers/list 0.2, VTI-CAL-132), else 0.1's `unavailableBecause`.
        let why = o["reason"]
            .as_str()
            .or_else(|| o["unavailableBecause"].as_str());
        return Some(match why {
            Some("disabledByOperator") => "its operator turned it off".into(),
            Some("unreachable") => "the VTA cannot reach it".into(),
            Some("builtinOff") => "its operator turned the built-in clients off and registered \
                                   no app of its own"
                .into(),
            Some("redirectNotRegistered") => "no app its operator registered admits a \
                                              redirect this command can catch"
                .into(),
            _ => "its operator has not registered an app for it".into(),
        });
    }
    match c {
        Choice::Google | Choice::Microsoft if flows_here(o).is_empty() => Some(
            "its operator registered no app this command can sign in through (a loopback \
             redirect, or for Microsoft a device code)"
                .into(),
        ),
        Choice::Apple
            if o["caldavHosts"]
                .as_array()
                .is_some_and(|h| !h.iter().any(|h| h.as_str() == Some("caldav.icloud.com"))) =>
        {
            Some("its operator does not let the VTA reach caldav.icloud.com".into())
        }
        _ => None,
    }
}

fn missing(flag: &str, why: &str) -> String {
    format!(
        "{why}: give {flag}, or run `pnm calendar connect` in a terminal to be asked.\n  e.g.  \
         pnm calendar connect --provider microsoft --context <id>"
    )
}

/// Decide what to connect, from the flags, the VTA's offers and — where `ask` is given —
/// the principal's answers. Without `ask`, anything not given takes its default or is refused
/// with the flag that gives it.
///
/// # Errors
/// A choice this VTA cannot complete, or a value that is needed and not given; each names the
/// fix.
pub fn plan(
    mut ask: Option<&mut dyn Ask>,
    offers: &Value,
    contexts: &[(String, String)],
    opts: &ConnectOptions,
) -> Result<Plan, String> {
    // Which calendar.
    let choice = match &opts.provider {
        Some(p) => {
            let c = Choice::parse(p).ok_or_else(|| {
                format!(
                    "unknown provider {p:?}: give --provider apple, google, microsoft, \
                     ics-busy or caldav"
                )
            })?;
            if let Some(why) = unavailable(offers, c) {
                let others: Vec<&str> = Choice::ALL
                    .into_iter()
                    .filter(|o| unavailable(offers, *o).is_none())
                    .map(Choice::flag)
                    .collect();
                let fix = offer(offers, c.provider())
                    .map(offer_help)
                    .unwrap_or_default()
                    .join("\n\n");
                return Err(format!(
                    "{} cannot be connected through this VTA: {why}.\n  It offers: {}.\n  \
                     e.g.  pnm calendar connect --provider {} --context <id>{}",
                    c.menu(),
                    if others.is_empty() {
                        "nothing".to_string()
                    } else {
                        others.join(", ")
                    },
                    others.first().copied().unwrap_or("ics-busy"),
                    if fix.is_empty() {
                        String::new()
                    } else {
                        format!("\n\nWhat the VTA's operator can do:\n\n{fix}")
                    },
                ));
            }
            c
        }
        None => {
            let offered: Vec<Choice> = Choice::ALL
                .into_iter()
                .filter(|c| unavailable(offers, *c).is_none())
                .collect();
            if offered.is_empty() {
                return Err(
                    "this VTA offers no calendar provider; its operator configures them \
                            under [calendar.connectors] (docs/02-vta/calendar.md)"
                        .into(),
                );
            }
            let Some(a) = ask.as_deref_mut() else {
                return Err(missing("--provider", "which calendar to connect"));
            };
            let items: Vec<String> = offered.iter().map(|c| c.menu().to_string()).collect();
            offered[a.select("Which calendar?", &items, 0)?]
        }
    };
    let o = offer(offers, choice.provider())
        .cloned()
        .unwrap_or(Value::Null);

    // How to sign in (VTI-CAL-119: only the ways the VTA offers, in its order).
    let flow = match choice {
        Choice::Google | Choice::Microsoft => {
            let here = flows_here(&o);
            Some(match opts.flow.as_deref() {
                Some("device-code") if here.contains(&"deviceCode") => "deviceCode",
                Some("device-code") => {
                    return Err(format!(
                        "{} cannot be signed in to with a code here{}.\n  Sign in through \
                         the browser:  pnm calendar connect --provider {} --flow \
                         authorization-code",
                        choice.menu(),
                        if choice == Choice::Google {
                            " — Google has no device code for calendars"
                        } else {
                            " — the VTA's Microsoft app does not allow public client flows"
                        },
                        choice.flag()
                    ));
                }
                Some("authorization-code") if here.contains(&"authorizationCode") => {
                    "authorizationCode"
                }
                Some("authorization-code") => {
                    return Err(format!(
                        "this VTA has no {} app that redirects to this machine; sign in with \
                         a code:  pnm calendar connect --provider {} --flow device-code",
                        choice.menu(),
                        choice.flag()
                    ));
                }
                Some(f) => {
                    return Err(format!(
                        "unknown flow {f:?}: give --flow device-code or authorization-code"
                    ));
                }
                None => match (here.as_slice(), ask.as_deref_mut()) {
                    ([only], _) | ([only, ..], None) => only,
                    (several, Some(a)) => {
                        let items: Vec<String> = several
                            .iter()
                            .enumerate()
                            .map(|(i, f)| {
                                let s = if *f == "deviceCode" {
                                    "Enter a code at the provider, on any device"
                                } else {
                                    "Sign in through a browser on this machine"
                                };
                                if i == 0 {
                                    format!("{s} (recommended)")
                                } else {
                                    s.to_string()
                                }
                            })
                            .collect();
                        several[a.select("How do you want to sign in?", &items, 0)?]
                    }
                    ([], _) => unreachable!("an offered choice has a way in"),
                },
            })
        }
        _ => {
            if opts.flow.is_some() {
                return Err(format!(
                    "--flow is for Google and Microsoft; {} takes a password or an address",
                    choice.menu()
                ));
            }
            None
        }
    };

    // Where it counts.
    let context = match (&opts.context, ask.as_deref_mut()) {
        (Some(c), _) => c.clone(),
        // The contexts the principal has standing in (VTI-CAL-100, 128).
        (None, Some(a)) if !contexts.is_empty() => {
            let items: Vec<String> = contexts
                .iter()
                .map(|(id, _)| context_item(contexts, id))
                .collect();
            contexts[a.select("Trust context for this calendar", &items, 0)?]
                .0
                .clone()
        }
        (None, Some(a)) => a.input("Trust context for this calendar", None)?,
        (None, None) => return Err(missing("--context <id>", "which trust context it is for")),
    };
    if context.trim().is_empty() {
        return Err(missing("--context <id>", "a trust context is needed"));
    }

    // The account, for CalDAV.
    let (endpoint, username) = match choice {
        Choice::Apple | Choice::Caldav => {
            let endpoint = match (choice, &opts.endpoint, ask.as_deref_mut()) {
                (Choice::Apple, _, _) => ICLOUD_CALDAV.to_string(),
                (_, Some(e), _) => e.clone(),
                (_, None, Some(a)) => a.input("CalDAV server address (https://…)", None)?,
                (_, None, None) => {
                    return Err(missing(
                        "--endpoint https://…",
                        "the CalDAV server is needed",
                    ));
                }
            };
            let prompt = if choice == Choice::Apple {
                "Apple ID (the email you sign in to iCloud with)"
            } else {
                "User name at that server"
            };
            let username = match (&opts.username, ask.as_deref_mut()) {
                (Some(u), _) => u.clone(),
                (None, Some(a)) => a.input(prompt, None)?,
                (None, None) => return Err(missing("--username", "the account is needed")),
            };
            (Some(endpoint), Some(username))
        }
        _ => (None, None),
    };

    // What it writes: busy time, no titles, by default (VTI-CAL-103).
    let write = if choice == Choice::IcsBusy {
        if opts.write.is_some() {
            return Err(
                "a private iCal address is read for busy time only; it writes \
                        nothing, so --write does not apply"
                    .into(),
            );
        }
        None
    } else {
        Some(match (&opts.write, ask.as_deref_mut()) {
            (Some(w), _) if ["busy", "titles", "off"].contains(&w.as_str()) => w.clone(),
            (Some(w), _) => {
                return Err(format!(
                    "unknown write mode {w:?}: give --write busy, titles or off"
                ));
            }
            (None, Some(a)) => {
                MODES[a.select("What should the VTA write into it?", &mode_items(), 0)?].to_string()
            }
            (None, None) => "busy".to_string(),
        })
    };

    // Whether busy time is read back: on by default, and the whole point of `icsBusy`.
    let busy = match choice {
        Choice::IcsBusy => {
            if opts.no_busy {
                return Err(
                    "a private iCal address is read for busy time; --no-busy leaves \
                            it nothing to do"
                        .into(),
                );
            }
            true
        }
        _ if opts.no_busy => false,
        _ => match ask.as_deref_mut() {
            Some(a) => a.confirm(
                "Read your busy time back, so polls and find-a-time count it?",
                true,
            )?,
            None => true,
        },
    };
    if write.as_deref() == Some("off") && !busy {
        return Err(
            "with nothing written and nothing read the connector would do nothing: \
                    drop --no-busy or give --write busy"
                .into(),
        );
    }

    let label = match (&opts.label, ask.as_deref_mut()) {
        (Some(l), _) => l.clone(),
        (None, Some(a)) => a.input("A name for it (only you see this)", Some(choice.label()))?,
        (None, None) => choice.label().to_string(),
    };

    // The first context's calendar (VTI-CAL-127).
    let writes = write.as_deref().is_some_and(|w| w != "off");
    let (mut calendar_name, mut communities) = (opts.calendar_name.clone(), Vec::new());
    if let (true, None, Some(a)) = (writes, &calendar_name, ask.as_deref_mut()) {
        (calendar_name, communities) = ask_calendar(a, contexts, &context)?;
    }

    // Other contexts, signed in once (VTI-CAL-127 – 131). Busy time only writes nothing, so
    // has no calendar to add.
    let mut also: Vec<AlsoContext> = Vec::new();
    let mut busy_contexts: Vec<String> = Vec::new();
    if choice != Choice::IcsBusy {
        for ctx in &opts.also_contexts {
            if *ctx == context || also.iter().any(|x| x.context == *ctx) {
                return Err(format!("{ctx} is named twice"));
            }
            also.push(AlsoContext {
                context: ctx.clone(),
                write: write.clone().unwrap_or_else(|| "busy".into()),
                calendar_name: None,
                communities: Vec::new(),
            });
        }
        if let Some(a) = ask.as_deref_mut() {
            let mut told = !also.is_empty();
            loop {
                let left: Vec<&(String, String)> = contexts
                    .iter()
                    .filter(|(id, _)| *id != context && !also.iter().any(|x| x.context == *id))
                    .collect();
                if left.is_empty() {
                    break;
                }
                if !told {
                    // VTI-CAL-131: before the first context is added.
                    a.say(SHARED_ACCOUNT_NOTICE);
                    told = true;
                }
                if !a.confirm(
                    "Add another trust context to this connector (same sign-in)?",
                    false,
                )? {
                    break;
                }
                let items: Vec<String> = left
                    .iter()
                    .map(|(id, _)| context_item(contexts, id))
                    .collect();
                let ctx = left[a.select("Which trust context?", &items, 0)?].0.clone();
                let w = MODES[a.select(
                    &format!(
                        "What should be written for {}?",
                        context_item(contexts, &ctx)
                    ),
                    &mode_items()[..2],
                    0,
                )?]
                .to_string();
                let (calendar_name, communities) = ask_calendar(a, contexts, &ctx)?;
                also.push(AlsoContext {
                    context: ctx,
                    write: w,
                    calendar_name,
                    communities,
                });
            }
        }
        // Where busy time counts: every context served, unless the principal says not.
        if busy && !also.is_empty() {
            busy_contexts.push(context.clone());
            for x in &also {
                let counts = match ask.as_deref_mut() {
                    Some(a) => a.confirm(
                        &format!(
                            "Count busy time read back in {} too?",
                            context_item(contexts, &x.context)
                        ),
                        true,
                    )?,
                    None => true,
                };
                if counts {
                    busy_contexts.push(x.context.clone());
                }
            }
            if busy_contexts.len() == 1 {
                busy_contexts.clear();
            }
        }
    } else if !opts.also_contexts.is_empty() {
        return Err(
            "busy time only writes nothing: it serves one context; choose where it \
                    counts with --busy-context on `pnm calendar connectors create`"
                .into(),
        );
    }

    Ok(Plan {
        choice,
        context,
        label,
        write,
        busy,
        flow,
        endpoint,
        username,
        calendar_name,
        communities,
        also,
        busy_contexts,
    })
}

/// `pnm calendar connect`.
///
/// # Errors
/// A refusal from the VTA (with the command that fixes it), or a value that is needed.
pub async fn cmd_calendar_connect(client: &VtaClient, opts: &ConnectOptions) -> CmdResult {
    let mut req = json!({});
    if let Some(c) = &opts.context {
        req["contextId"] = json!(c);
    }
    let offers = match call_newest(
        client,
        tt::TASK_VTA_CALENDAR_CONNECTORS_PROVIDERS_LIST_0_2,
        Some(tt::TASK_VTA_CALENDAR_CONNECTORS_PROVIDERS_LIST_0_1),
        req,
        None,
    )
    .await
    {
        Ok(o) => o,
        Err(e) if opts.help_operator => {
            println!(
                "Could not read what this VTA offers ({e}); every provider's setup follows.\n"
            );
            println!("{}", operator_guide());
            return Ok(());
        }
        Err(e) => return Err(e),
    };
    if opts.help_operator {
        return print_operator_help(&offers);
    }
    let interactive = !opts.non_interactive && !is_json_output() && std::io::stdin().is_terminal();
    // The contexts the principal has standing in, for the picker (VTI-CAL-100, 128).
    let contexts: Vec<(String, String)> = if interactive {
        client
            .list_contexts()
            .await
            .map(|r| r.contexts.into_iter().map(|c| (c.id, c.name)).collect())
            .unwrap_or_default()
    } else {
        Vec::new()
    };
    let mut term = Terminal;
    let p = plan(
        if interactive {
            Some(&mut term as &mut dyn Ask)
        } else {
            None
        },
        &offers,
        &contexts,
        opts,
    )?;
    if !interactive && !p.also.is_empty() && !is_json_output() {
        println!("{YELLOW}{SHARED_ACCOUNT_NOTICE}{RESET}");
    }
    if let (Some(held), Some(limit)) = (
        offers["connectorsHeld"].as_u64(),
        offers["connectorLimit"].as_u64(),
    ) && held >= limit
    {
        return Err(format!(
            "this VTA holds {held} of at most {limit} connectors; remove one first:\n    \
             pnm calendar connectors list\n    pnm calendar connectors remove <connector-id>"
        )
        .into());
    }

    let mut create = json!({
        "contextId": p.context,
        "provider": p.choice.provider(),
        "label": p.label,
        "busy": busy_choice(p.busy, &p.busy_contexts, &[]),
    });
    if let Some(cov) = p.coverage() {
        create["coverage"] = cov;
    }
    let mut listener = None;
    match p.choice {
        Choice::Apple | Choice::Caldav => {
            let (Some(endpoint), Some(username)) = (&p.endpoint, &p.username) else {
                return Err("the CalDAV server and account are needed".into());
            };
            if interactive {
                println!("{DIM}{}{RESET}", help::USER_APP_PASSWORD);
            }
            let password = read_secret(&format!("App-specific password for {username}"))?;
            create["caldav"] = json!({
                "endpoint": endpoint,
                "username": username,
                "sealedPassword": seal_password(client, endpoint, username, &password).await?,
            });
        }
        Choice::IcsBusy => {
            if interactive {
                println!("{DIM}{}{RESET}", help::USER_PRIVATE_ICAL);
            }
            let address = read_secret("Private iCal address (https:// or webcal://)")?;
            create["ics"] = json!({ "sealedAddress": seal_ics_address(client, &address).await? });
        }
        Choice::Google | Choice::Microsoft => {
            if p.flow == Some("deviceCode") {
                create["flow"] = json!("deviceCode");
            } else {
                let l = Loopback::bind().await?;
                create["redirectUri"] = json!(l.redirect_uri);
                listener = Some(l);
            }
        }
    }
    // A 0.2 VTA writes every context into one calendar: fall back only for one context.
    let older = (p.also.is_empty() && super::calendar_connectors::same_at_v2(&create))
        .then_some(tt::TASK_VTA_CALENDAR_CONNECTORS_CREATE_0_2);
    let resp = call_newest(
        client,
        tt::TASK_VTA_CALENDAR_CONNECTORS_CREATE_0_3,
        older,
        create,
        None,
    )
    .await?;
    let id = resp["connector"]["connectorId"]
        .as_str()
        .unwrap_or_default()
        .to_string();

    if let Some(device) = resp.get("deviceAuthorization") {
        let opened = resp["connector"]["updatedAt"]
            .as_str()
            .unwrap_or_default()
            .to_string();
        let shown = device_wait(client, &id, device).await?;
        let outcome = device_outcome(&id, &opened, &shown);
        // VTI-CAL-122: an organisation may forbid the device flow; offer the browser instead.
        let browser = offer(&offers, "microsoft")
            .is_some_and(|o| flows_here(o).contains(&"authorizationCode"));
        if outcome.is_err() && interactive && browser {
            println!("{YELLOW}The code was not accepted.{RESET}");
            if Terminal
                .confirm("Sign in through a browser on this machine instead?", true)
                .unwrap_or(false)
            {
                let l = Loopback::bind().await?;
                let again = call_newest(
                    client,
                    tt::TASK_VTA_CALENDAR_CONNECTORS_UPDATE_0_3,
                    Some(tt::TASK_VTA_CALENDAR_CONNECTORS_UPDATE_0_2),
                    json!({ "connectorId": id, "reauthorize": { "redirectUri": l.redirect_uri } }),
                    Some(&id),
                )
                .await?;
                if let Some(a) = again.get("authorization") {
                    let completed = grant(client, &id, "microsoft", a, Some(l)).await?;
                    println!("{GREEN}\u{2713}{RESET} Connected.");
                    return done(&completed);
                }
            }
        }
        return outcome;
    }
    if let Some(a) = resp.get("authorization") {
        let completed = grant(client, &id, p.choice.provider(), a, listener).await?;
        if !is_json_output() {
            println!("{GREEN}\u{2713}{RESET} Connected.");
        }
        return done(&completed);
    }
    if is_json_output() {
        return Ok(print_json(&resp)?);
    }
    println!("{GREEN}\u{2713}{RESET} Connected.");
    done(&resp)
}

/// `pnm calendar connect --help-operator`: what this VTA does not offer, and for each the
/// operator's exact fix, plain so it can be copied (VTI-CAL-132).
fn print_operator_help(offers: &Value) -> CmdResult {
    let blocks = operator_help(offers);
    if is_json_output() {
        return Ok(print_json(&serde_json::json!({
            "providers": offers["providers"],
            "help": blocks.iter().map(|(p, b)| json!({ "provider": p, "text": b })).collect::<Vec<_>>(),
        }))?);
    }
    if blocks.is_empty() {
        println!("This VTA offers every provider and every way in; there is nothing to configure.");
        return Ok(());
    }
    for (i, (_, b)) in blocks.iter().enumerate() {
        if i > 0 {
            println!("\n----\n");
        }
        println!("{b}");
    }
    Ok(())
}

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

    /// Answers by prompt: each prompt the wizard asks must have one, or the test fails —
    /// so a question asked that should not be is caught too.
    #[derive(Default)]
    struct Scripted {
        answers: Vec<(&'static str, &'static str)>,
        asked: Vec<String>,
        said: Vec<String>,
    }

    impl Scripted {
        fn new(answers: &[(&'static str, &'static str)]) -> Self {
            Self {
                answers: answers.to_vec(),
                asked: Vec::new(),
                said: Vec::new(),
            }
        }

        fn take(&mut self, prompt: &str) -> Result<&'static str, String> {
            self.asked.push(prompt.to_string());
            let at = self
                .answers
                .iter()
                .position(|(p, _)| prompt.contains(p))
                .ok_or_else(|| format!("no scripted answer for {prompt:?}"))?;
            Ok(self.answers.remove(at).1)
        }
    }

    impl Ask for Scripted {
        fn select(
            &mut self,
            prompt: &str,
            items: &[String],
            default: usize,
        ) -> Result<usize, String> {
            match self.take(prompt)? {
                "" => Ok(default),
                label => items
                    .iter()
                    .position(|i| i.starts_with(label))
                    .ok_or_else(|| format!("{label:?} is not offered for {prompt:?}: {items:?}")),
            }
        }

        fn input(&mut self, prompt: &str, default: Option<&str>) -> Result<String, String> {
            match self.take(prompt)? {
                "" => Ok(default.unwrap_or_default().to_string()),
                v => Ok(v.to_string()),
            }
        }

        fn confirm(&mut self, prompt: &str, default: bool) -> Result<bool, String> {
            match self.take(prompt)? {
                "" => Ok(default),
                v => Ok(v == "yes"),
            }
        }

        fn say(&mut self, text: &str) {
            self.said.push(text.to_string());
            self.asked.push(format!("(said) {text}"));
        }
    }

    /// What a VTA offering everything answers: Microsoft by a device code first.
    fn everything() -> Value {
        json!({ "providers": [
            { "provider": "google", "available": true, "writes": true, "readsBusy": true,
              "flows": [{ "flow": "authorizationCode", "redirectKinds": ["loopback"], "builtIn": true }] },
            { "provider": "microsoft", "available": true, "writes": true, "readsBusy": true,
              "flows": [{ "flow": "deviceCode", "builtIn": true },
                        { "flow": "authorizationCode", "redirectKinds": ["loopback", "extension"], "builtIn": true }] },
            { "provider": "caldav", "available": true, "writes": true, "readsBusy": true, "flows": [] },
            { "provider": "icsBusy", "available": true, "writes": false, "readsBusy": true, "flows": [] }
          ], "connectorsHeld": 0, "connectorLimit": 8 })
    }

    fn opts() -> ConnectOptions {
        ConnectOptions::new()
    }

    #[test]
    fn vti_cal_119_microsoft_without_a_terminal_takes_the_recommended_device_code() {
        let mut o = opts();
        o.provider = Some("microsoft".into());
        o.context = Some("work".into());
        let p = plan(None, &everything(), &[], &o).unwrap();
        assert_eq!(p.flow, Some("deviceCode"));
        assert_eq!(
            p.write.as_deref(),
            Some("busy"),
            "busy time, no titles, by default"
        );
        assert!(p.busy, "busy time read back by default");
        assert_eq!(p.label, "Outlook");
    }

    #[test]
    fn vti_cal_119_google_is_never_offered_a_device_code() {
        let mut o = opts();
        o.provider = Some("google".into());
        o.context = Some("work".into());
        o.flow = Some("device-code".into());
        let e = plan(None, &everything(), &[], &o).unwrap_err();
        assert!(e.contains("Google has no device code"), "{e}");
        assert!(e.contains("--flow authorization-code"), "the fix: {e}");
    }

    #[test]
    fn apple_asks_for_the_account_and_takes_the_defaults() {
        let mut a = Scripted::new(&[
            ("Which calendar", "Apple iCloud"),
            ("Trust context", "personal"),
            ("Apple ID", "ada@example.com"),
            ("write", ""),
            ("busy time back", ""),
            ("A name", ""),
            ("calendar at the provider", ""),
            ("different mode for one community", ""),
        ]);
        let p = plan(Some(&mut a), &everything(), &[], &opts()).unwrap();
        assert_eq!(p.choice, Choice::Apple);
        assert_eq!(p.endpoint.as_deref(), Some(ICLOUD_CALDAV));
        assert_eq!(p.username.as_deref(), Some("ada@example.com"));
        assert_eq!(p.write.as_deref(), Some("busy"));
        assert!(p.busy);
        assert_eq!(p.label, "iCloud");
        assert!(a.answers.is_empty(), "every scripted question was asked");
    }

    #[test]
    fn vti_cal_123_busy_time_only_asks_nothing_about_writing() {
        let mut a = Scripted::new(&[
            ("Which calendar", "Busy time only"),
            ("Trust context", "personal"),
            ("A name", "Work (busy)"),
        ]);
        let p = plan(Some(&mut a), &everything(), &[], &opts()).unwrap();
        assert_eq!(p.choice, Choice::IcsBusy);
        assert_eq!(p.write, None);
        assert!(p.busy);
        assert_eq!(p.flow, None);
        assert_eq!(p.label, "Work (busy)");
        assert!(
            !a.asked
                .iter()
                .any(|q| q.contains("write") || q.contains("busy time back")),
            "{:?}",
            a.asked
        );
    }

    #[test]
    fn microsoft_in_a_terminal_offers_both_ways_recommended_first() {
        let mut a = Scripted::new(&[
            ("Which calendar", "Microsoft"),
            ("How do you want to sign in", "Sign in through a browser"),
            ("Trust context", "work"),
            ("write", "Titles"),
            ("busy time back", "no"),
            ("A name", ""),
            ("calendar at the provider", "Outlook (VTI)"),
            ("different mode for one community", ""),
        ]);
        let p = plan(Some(&mut a), &everything(), &[], &opts()).unwrap();
        assert_eq!(p.flow, Some("authorizationCode"));
        assert_eq!(p.write.as_deref(), Some("titles"));
        assert!(!p.busy);
        assert_eq!(p.calendar_name.as_deref(), Some("Outlook (VTI)"));
    }

    #[test]
    fn vti_cal_125_only_what_the_vta_offers_is_offered() {
        let mut offers = everything();
        offers["providers"][0] = json!({ "provider": "google", "available": false,
            "unavailableBecause": "notConfigured", "writes": true, "readsBusy": true, "flows": [] });
        offers["providers"][2]["caldavHosts"] = json!(["caldav.fastmail.com"]);
        // A scripted answer naming Google fails: it is not on the menu.
        let mut a = Scripted::new(&[("Which calendar", "Google")]);
        let e = plan(Some(&mut a), &offers, &[], &opts()).unwrap_err();
        assert!(e.contains("not offered"), "{e}");
        // Asked for by flag: refused with why and what is offered instead.
        let mut o = opts();
        o.provider = Some("google".into());
        let e = plan(None, &offers, &[], &o).unwrap_err();
        assert!(e.contains("has not registered an app"), "{e}");
        assert!(e.contains("It offers: microsoft, ics-busy, caldav"), "{e}");
        o.provider = Some("apple".into());
        let e = plan(None, &offers, &[], &o).unwrap_err();
        assert!(e.contains("caldav.icloud.com"), "{e}");
    }

    #[test]
    fn without_a_terminal_a_missing_value_names_its_flag() {
        let e = plan(None, &everything(), &[], &opts()).unwrap_err();
        assert!(e.contains("--provider"), "{e}");
        let mut o = opts();
        o.provider = Some("apple".into());
        let e = plan(None, &everything(), &[], &o).unwrap_err();
        assert!(e.contains("--context <id>"), "{e}");
        o.context = Some("personal".into());
        let e = plan(None, &everything(), &[], &o).unwrap_err();
        assert!(e.contains("--username"), "{e}");
        o.username = Some("ada@example.com".into());
        o.write = Some("off".into());
        o.no_busy = true;
        let e = plan(None, &everything(), &[], &o).unwrap_err();
        assert!(e.contains("would do nothing"), "{e}");
    }

    fn two_contexts() -> Vec<(String, String)> {
        vec![
            ("work".to_string(), "Work".to_string()),
            ("home".to_string(), "Home".to_string()),
        ]
    }

    #[test]
    fn vti_cal_127_one_sign_in_serves_a_second_context_after_the_notice() {
        let mut a = Scripted::new(&[
            ("Which calendar", "Google"),
            ("Trust context", "Work"),
            ("write", ""),
            ("busy time back", ""),
            ("A name", ""),
            ("Name of Work (work)'s calendar", ""),
            ("different mode for one community in Work", ""),
            ("Add another trust context", "yes"),
            ("Which trust context", "Home"),
            ("written for Home", "Titles"),
            ("Name of Home (home)'s calendar", "Family"),
            ("different mode for one community in Home", "yes"),
            ("The community's DID", "did:web:club.example"),
            ("written for it", "Busy"),
            ("different mode for one community in Home", "no"),
            ("Count busy time read back in Home", "no"),
        ]);
        let p = plan(Some(&mut a), &everything(), &two_contexts(), &opts()).unwrap();
        assert!(a.answers.is_empty(), "unasked: {:?}", a.answers);
        // VTI-CAL-131: said before the context is added.
        let notice = a
            .asked
            .iter()
            .position(|q| q.starts_with("(said)"))
            .unwrap();
        let add = a
            .asked
            .iter()
            .position(|q| q.contains("Add another trust context"))
            .unwrap();
        assert!(notice < add, "{:?}", a.asked);
        assert!(a.said[0].contains("same account"));
        assert_eq!(
            p.coverage().unwrap(),
            json!([
                { "contextId": "work", "write": "busy" },
                { "contextId": "home", "write": "titles", "calendarName": "Family",
                  "communities": [{ "community": "did:web:club.example", "write": "busy" }] }
            ])
        );
        assert!(p.busy_contexts.is_empty(), "counted in work alone");
    }

    #[test]
    fn vti_cal_127_also_contexts_by_flag_count_busy_everywhere() {
        let mut o = opts();
        o.provider = Some("microsoft".into());
        o.context = Some("work".into());
        o.also_contexts = vec!["home".into()];
        o.calendar_name = Some("Work (VTI)".into());
        let p = plan(None, &everything(), &[], &o).unwrap();
        assert_eq!(
            p.coverage().unwrap(),
            json!([{ "contextId": "work", "write": "busy", "calendarName": "Work (VTI)" },
                   { "contextId": "home", "write": "busy" }])
        );
        assert_eq!(
            p.busy_contexts,
            vec!["work".to_string(), "home".to_string()]
        );
        o.also_contexts = vec!["work".into()];
        assert!(
            plan(None, &everything(), &[], &o)
                .unwrap_err()
                .contains("named twice")
        );
    }

    #[test]
    fn vti_cal_132_a_provider_not_offered_says_the_operator_fix() {
        let mut offers = everything();
        offers["providers"][1] = json!({ "provider": "microsoft", "available": false,
            "unavailableBecause": "builtinOff", "reason": "builtinOff",
            "writes": true, "readsBusy": true, "flows": [] });
        let mut o = opts();
        o.provider = Some("microsoft".into());
        let e = plan(None, &offers, &[], &o).unwrap_err();
        assert!(e.contains("turned the built-in clients off"), "{e}");
        assert!(e.contains("builtin_clients = true"), "{e}");
    }
}