vta-cli-common 0.72.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
//! `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.1`), 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`.
//!
//! 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_connectors::{
    Loopback, busy_choice, call, 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,
}

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>;
}

/// 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())
    }
}

/// 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>,
}

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 {
        return Some(match o["unavailableBecause"].as_str() {
            Some("disabledByOperator") => "its operator turned it off".into(),
            Some("unreachable") => "the VTA cannot reach it".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,
    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();
                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"),
                ));
            }
            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(),
        (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)) => {
                let items = [
                    "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(),
                ];
                ["busy", "titles", "off"]
                    [a.select("What should the VTA write into it?", &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) {
        (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(),
    };

    Ok(Plan {
        choice,
        context,
        label,
        write,
        busy,
        flow,
        endpoint,
        username,
    })
}

/// `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 = call(
        client,
        tt::TASK_VTA_CALENDAR_CONNECTORS_PROVIDERS_LIST_0_1,
        req,
        None,
    )
    .await?;
    let interactive = !opts.non_interactive && !is_json_output() && std::io::stdin().is_terminal();
    let mut term = Terminal;
    let p = plan(
        if interactive {
            Some(&mut term as &mut dyn Ask)
        } else {
            None
        },
        &offers,
        opts,
    )?;
    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, &[], &[]),
    });
    if let Some(w) = &p.write {
        create["coverage"] = json!([{ "contextId": p.context, "write": w }]);
    }
    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 p.choice == Choice::Apple && interactive {
                println!(
                    "{DIM}iCloud needs an app-specific password, not your Apple ID password: \
                     make one at https://account.apple.com → Sign-In and Security → \
                     App-Specific Passwords.{RESET}"
                );
            }
            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}Use the calendar's private address in iCal format — Google: Settings \
                     → your calendar → \"Secret address in iCal format\"; Outlook: Settings → \
                     Calendar → Shared calendars → Publish a calendar → ICS. Only times are kept \
                     of what it holds.{RESET}"
                );
            }
            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);
            }
        }
    }
    let resp = call(
        client,
        tt::TASK_VTA_CALENDAR_CONNECTORS_CREATE_0_2,
        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(
                    client,
                    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)
}

#[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>,
    }

    impl Scripted {
        fn new(answers: &[(&'static str, &'static str)]) -> Self {
            Self {
                answers: answers.to_vec(),
                asked: 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"),
            }
        }
    }

    /// 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", ""),
        ]);
        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", ""),
        ]);
        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);
    }

    #[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}");
    }
}