Skip to main content

romm_cli/tui/screens/
setup_wizard.rs

1//! First-run setup: server URL, ROMs directory, authentication, test connection, persist config.
2
3use anyhow::{anyhow, Context, Result};
4use crossterm::event::{
5    self, DisableMouseCapture, EnableMouseCapture, Event, KeyCode, KeyEvent, KeyEventKind,
6};
7use crossterm::execute;
8use crossterm::terminal::{
9    disable_raw_mode, enable_raw_mode, EnterAlternateScreen, LeaveAlternateScreen,
10};
11use ratatui::backend::CrosstermBackend;
12use ratatui::layout::{Constraint, Direction, Layout, Rect};
13use ratatui::style::{Color, Modifier, Style};
14use ratatui::text::{Line, Span, Text};
15use ratatui::widgets::{Block, Borders, List, ListItem, ListState, Paragraph};
16use ratatui::Terminal;
17use std::io::stdout;
18
19use crate::client::RommClient;
20use crate::config::{
21    is_keyring_placeholder, load_config, normalize_romm_origin, persist_user_config,
22    read_user_config_json_from_disk, AuthConfig, Config,
23};
24use crate::core::download::validate_configured_download_directory;
25use crate::endpoints::client_tokens::ExchangeClientToken;
26use crate::tui::path_picker::{PathPicker, PathPickerEvent, PathPickerMode};
27
28#[derive(Clone, Copy, PartialEq, Eq)]
29enum AuthKind {
30    None,
31    Basic,
32    Bearer,
33    ApiKey,
34    Pairing,
35}
36
37#[derive(Clone, Copy, PartialEq, Eq)]
38enum Step {
39    Url,
40    Https,
41    Download,
42    AuthMenu,
43    BasicUser,
44    BasicPass,
45    Bearer,
46    ApiHeader,
47    ApiKey,
48    PairingCode,
49    Summary,
50}
51
52fn wizard_layout(area: Rect, step: Step) -> [Rect; 3] {
53    let top = if matches!(step, Step::Url) { 5 } else { 3 };
54    let v = Layout::default()
55        .direction(Direction::Vertical)
56        .constraints([
57            Constraint::Length(top),
58            Constraint::Min(6),
59            Constraint::Length(4),
60        ])
61        .split(area);
62    [v[0], v[1], v[2]]
63}
64
65fn wizard_footer_text(keys: &str) -> Text<'_> {
66    let ver = format!("romm-cli {}", env!("CARGO_PKG_VERSION"));
67    Text::from(vec![
68        Line::from(keys).style(Style::default().fg(Color::Cyan)),
69        Line::from(ver).style(Style::default().fg(Color::DarkGray)),
70    ])
71}
72
73/// Interactive setup run before the main TUI when `API_BASE_URL` is missing.
74pub struct SetupWizard {
75    step: Step,
76    auth_kind: AuthKind,
77    auth_menu_selected: usize,
78    url: String,
79    url_cursor: usize,
80    download_picker: PathPicker,
81    username: String,
82    user_cursor: usize,
83    password: String,
84    bearer_token: String,
85    bearer_cursor: usize,
86    api_header: String,
87    header_cursor: usize,
88    api_key: String,
89    api_key_cursor: usize,
90    pairing_code: String,
91    pairing_cursor: usize,
92    /// Empty field + `true` means resolve secret from OS keyring on save (disk had `<stored-in-keyring>`).
93    reuse_keyring_password: bool,
94    reuse_keyring_bearer: bool,
95    reuse_keyring_api_key: bool,
96    pub testing: bool,
97    pub use_https: bool,
98    pub error: Option<String>,
99}
100
101impl SetupWizard {
102    pub fn new() -> Self {
103        let default_dl = dirs::download_dir()
104            .unwrap_or_else(|| dirs::home_dir().unwrap_or_default().join("Downloads"))
105            .join("romm-cli")
106            .display()
107            .to_string();
108        Self {
109            step: Step::Url,
110            auth_kind: AuthKind::None,
111            auth_menu_selected: 0,
112            url: "https://".to_string(),
113            url_cursor: "https://".len(),
114            download_picker: PathPicker::new(PathPickerMode::Directory, &default_dl),
115            username: String::new(),
116            user_cursor: 0,
117            password: String::new(),
118            bearer_token: String::new(),
119            bearer_cursor: 0,
120            api_header: String::new(),
121            header_cursor: 0,
122            api_key: String::new(),
123            api_key_cursor: 0,
124            pairing_code: String::new(),
125            pairing_cursor: 0,
126            reuse_keyring_password: false,
127            reuse_keyring_bearer: false,
128            reuse_keyring_api_key: false,
129            testing: false,
130            use_https: true,
131            error: None,
132        }
133    }
134
135    pub fn new_auth_only(config: &Config) -> Self {
136        let mut wizard = Self::new();
137        wizard.step = Step::AuthMenu;
138        wizard.url = config.base_url.clone();
139        wizard
140            .download_picker
141            .set_path_text(config.download_dir.clone());
142        wizard.use_https = config.use_https;
143
144        let disk = read_user_config_json_from_disk();
145
146        match &config.auth {
147            Some(AuthConfig::Basic { username, password }) => {
148                wizard.auth_kind = AuthKind::Basic;
149                wizard.auth_menu_selected = 1;
150                wizard.username = username.clone();
151                wizard.user_cursor = username.len();
152                let disk_pass = disk
153                    .as_ref()
154                    .and_then(|c| c.auth.as_ref())
155                    .and_then(|a| match a {
156                        AuthConfig::Basic { password, .. } => Some(password.as_str()),
157                        _ => None,
158                    });
159                if disk_pass.is_some_and(is_keyring_placeholder) {
160                    wizard.password = String::new();
161                    wizard.reuse_keyring_password = true;
162                } else {
163                    wizard.password = password.clone();
164                }
165            }
166            Some(AuthConfig::Bearer { token }) => {
167                wizard.auth_kind = AuthKind::Bearer;
168                wizard.auth_menu_selected = 2;
169                let disk_tok = disk
170                    .as_ref()
171                    .and_then(|c| c.auth.as_ref())
172                    .and_then(|a| match a {
173                        AuthConfig::Bearer { token } => Some(token.as_str()),
174                        _ => None,
175                    });
176                if disk_tok.is_some_and(is_keyring_placeholder) {
177                    wizard.bearer_token = String::new();
178                    wizard.bearer_cursor = 0;
179                    wizard.reuse_keyring_bearer = true;
180                } else {
181                    wizard.bearer_token = token.clone();
182                    wizard.bearer_cursor = token.len();
183                }
184            }
185            Some(AuthConfig::ApiKey { header, key }) => {
186                wizard.auth_kind = AuthKind::ApiKey;
187                wizard.auth_menu_selected = 3;
188                wizard.api_header = header.clone();
189                wizard.header_cursor = header.len();
190                let disk_key = disk
191                    .as_ref()
192                    .and_then(|c| c.auth.as_ref())
193                    .and_then(|a| match a {
194                        AuthConfig::ApiKey { key, .. } => Some(key.as_str()),
195                        _ => None,
196                    });
197                if disk_key.is_some_and(is_keyring_placeholder) {
198                    wizard.api_key = String::new();
199                    wizard.api_key_cursor = 0;
200                    wizard.reuse_keyring_api_key = true;
201                } else {
202                    wizard.api_key = key.clone();
203                    wizard.api_key_cursor = key.len();
204                }
205            }
206            None => {
207                wizard.auth_kind = AuthKind::None;
208                wizard.auth_menu_selected = 0;
209            }
210        }
211        wizard
212    }
213
214    fn auth_labels() -> [&'static str; 5] {
215        [
216            "No authentication",
217            "Basic (username + password)",
218            "API Token (Bearer)",
219            "API key in custom header",
220            "Pair with Web UI (8-character code)",
221        ]
222    }
223
224    fn auth_kind_from_index(i: usize) -> AuthKind {
225        match i {
226            1 => AuthKind::Basic,
227            2 => AuthKind::Bearer,
228            3 => AuthKind::ApiKey,
229            4 => AuthKind::Pairing,
230            _ => AuthKind::None,
231        }
232    }
233
234    /// Build config after exchanging a Web UI pairing code (unauthenticated POST).
235    async fn pairing_config_from_exchange(&self, verbose: bool) -> Result<Config> {
236        let base_url = normalize_romm_origin(self.url.trim());
237        if base_url.is_empty() {
238            return Err(anyhow!("Server URL cannot be empty"));
239        }
240        let code = self.pairing_code.trim().to_string();
241        if code.is_empty() {
242            return Err(anyhow!("Pairing code cannot be empty"));
243        }
244        let download_dir =
245            validate_configured_download_directory(self.download_picker.path_trimmed().trim())?
246                .display()
247                .to_string();
248        let temp_config = Config {
249            base_url: base_url.clone(),
250            download_dir: download_dir.clone(),
251            use_https: self.use_https,
252            auth: None,
253        };
254        let client = RommClient::new(&temp_config, verbose)?;
255        let response = client
256            .call(&ExchangeClientToken { code })
257            .await
258            .context("failed to exchange pairing code")?;
259        Ok(Config {
260            base_url,
261            download_dir,
262            use_https: self.use_https,
263            auth: Some(AuthConfig::Bearer {
264                token: response.raw_token,
265            }),
266        })
267    }
268
269    fn build_config(&self) -> Result<Config> {
270        let base_url = normalize_romm_origin(self.url.trim());
271        if base_url.is_empty() {
272            return Err(anyhow!("Server URL cannot be empty"));
273        }
274        let download_dir =
275            validate_configured_download_directory(self.download_picker.path_trimmed().trim())?
276                .display()
277                .to_string();
278        let auth: Option<AuthConfig> = match self.auth_kind {
279            AuthKind::None => None,
280            AuthKind::Basic => {
281                let u = self.username.trim();
282                if u.is_empty() {
283                    return Err(anyhow!("Username cannot be empty"));
284                }
285                let password = if self.password.is_empty() && self.reuse_keyring_password {
286                    crate::config::keyring_get("API_PASSWORD").ok_or_else(|| {
287                        anyhow!("Password not in OS keyring; enter a password or run romm-cli init")
288                    })?
289                } else if self.password.is_empty() {
290                    return Err(anyhow!("Password cannot be empty"));
291                } else {
292                    self.password.clone()
293                };
294                Some(AuthConfig::Basic {
295                    username: u.to_string(),
296                    password,
297                })
298            }
299            AuthKind::Bearer => {
300                let token = if self.bearer_token.trim().is_empty() && self.reuse_keyring_bearer {
301                    crate::config::keyring_get("API_TOKEN").ok_or_else(|| {
302                        anyhow!("API token not in OS keyring; enter a token or run romm-cli init")
303                    })?
304                } else if self.bearer_token.trim().is_empty() {
305                    return Err(anyhow!("Bearer token cannot be empty"));
306                } else {
307                    self.bearer_token.trim().to_string()
308                };
309                Some(AuthConfig::Bearer { token })
310            }
311            AuthKind::ApiKey => {
312                let h = self.api_header.trim();
313                if h.is_empty() {
314                    return Err(anyhow!("Header name cannot be empty"));
315                }
316                let key = if self.api_key.is_empty() && self.reuse_keyring_api_key {
317                    crate::config::keyring_get("API_KEY").ok_or_else(|| {
318                        anyhow!("API key not in OS keyring; enter a key or run romm-cli init")
319                    })?
320                } else if self.api_key.is_empty() {
321                    return Err(anyhow!("API key cannot be empty"));
322                } else {
323                    self.api_key.clone()
324                };
325                Some(AuthConfig::ApiKey {
326                    header: h.to_string(),
327                    key,
328                })
329            }
330            AuthKind::Pairing => {
331                return Err(anyhow!(
332                    "Pairing auth is applied when connecting; use the pairing code step and connect"
333                ));
334            }
335        };
336        Ok(Config {
337            base_url,
338            download_dir,
339            use_https: self.use_https,
340            auth,
341        })
342    }
343
344    pub fn render(&mut self, f: &mut ratatui::Frame, area: ratatui::layout::Rect) {
345        let title = match self.step {
346            Step::Url => "Step 1/5 — RomM server URL",
347            Step::Https => "Step 2/5 — Secure connection",
348            Step::Download => "Step 3/5 — ROMs directory",
349            Step::AuthMenu => "Step 4/5 — Authentication",
350            Step::BasicUser | Step::BasicPass => "Step 5/5 — Basic auth",
351            Step::Bearer => "Step 5/5 — API Token",
352            Step::ApiHeader | Step::ApiKey => "Step 5/5 — API key",
353            Step::PairingCode => "Step 5/5 — Pair with Web UI",
354            Step::Summary => "Review & connect",
355        };
356
357        let main = wizard_layout(area, self.step);
358
359        match self.step {
360            Step::Url => {
361                let intro = Text::from(vec![
362                    Line::from("First-time setup: point the CLI at your RomM server."),
363                    Line::from(Span::styled(
364                        "Example: https://romm.example.com or http://192.168.1.10:8080",
365                        Style::default().fg(Color::DarkGray),
366                    )),
367                    Line::from(Span::styled(
368                        "Same origin as in your browser (no trailing /api). Esc: quit",
369                        Style::default().fg(Color::DarkGray),
370                    )),
371                ]);
372                f.render_widget(Paragraph::new(intro), main[0]);
373            }
374            _ => {
375                let hint_top = "Same origin as in your browser (no trailing /api). Esc: quit";
376                let p = Paragraph::new(hint_top).style(Style::default().fg(Color::DarkGray));
377                f.render_widget(p, main[0]);
378            }
379        }
380
381        match self.step {
382            Step::Url => {
383                let line = format!(
384                    "{}▏",
385                    self.url.chars().take(self.url_cursor).collect::<String>()
386                );
387                let rest: String = self.url.chars().skip(self.url_cursor).collect();
388                let text = format!("{line}{rest}");
389                let block = Block::default().title(title).borders(Borders::ALL);
390                let p = Paragraph::new(text).block(block);
391                f.render_widget(p, main[1]);
392            }
393            Step::Https => {
394                let text = if self.use_https {
395                    "[X] Use HTTPS (Recommended)"
396                } else {
397                    "[ ] Use HTTPS (Insecure)"
398                };
399                let block = Block::default().title(title).borders(Borders::ALL);
400                let p = Paragraph::new(format!("\n  {}\n\n  Space: toggle   Enter: next", text))
401                    .block(block);
402                f.render_widget(p, main[1]);
403            }
404            Step::Download => {
405                let footer = "↓/↑: list focus  ↑ at top: back to path  Ctrl+Enter: accept typed path (creates folders)  Tab: path/list  Esc: quit";
406                self.download_picker.render(f, main[1], title, footer);
407            }
408            Step::AuthMenu => {
409                let items: Vec<ListItem> = Self::auth_labels()
410                    .iter()
411                    .map(|s| ListItem::new(*s))
412                    .collect();
413                let mut state = ListState::default();
414                state.select(Some(self.auth_menu_selected));
415                let list = List::new(items)
416                    .block(Block::default().title(title).borders(Borders::ALL))
417                    .highlight_style(
418                        Style::default()
419                            .fg(Color::Yellow)
420                            .add_modifier(Modifier::BOLD),
421                    )
422                    .highlight_symbol(">> ");
423                f.render_stateful_widget(list, main[1], &mut state);
424            }
425            Step::BasicUser | Step::BasicPass => {
426                let user_line = if self.step == Step::BasicUser {
427                    format!(
428                        "{}▏{}",
429                        self.username
430                            .chars()
431                            .take(self.user_cursor)
432                            .collect::<String>(),
433                        self.username
434                            .chars()
435                            .skip(self.user_cursor)
436                            .collect::<String>()
437                    )
438                } else {
439                    self.username.clone()
440                };
441                let pass_display: String = if self.step == Step::BasicPass {
442                    "•".repeat(self.password.len()) + "▏"
443                } else {
444                    "•".repeat(self.password.len())
445                };
446                let kr_hint = if self.step == Step::BasicPass
447                    && self.password.is_empty()
448                    && self.reuse_keyring_password
449                {
450                    "\n\n(stored in OS keyring — leave blank to keep, or type a new password)"
451                } else {
452                    ""
453                };
454                let block = Block::default().title(title).borders(Borders::ALL);
455                let body = format!(
456                    "Username\n{user_line}\n\nPassword (hidden)\n{pass_display}{kr_hint}\n\nTab: switch field"
457                );
458                let p = Paragraph::new(body).block(block);
459                f.render_widget(p, main[1]);
460            }
461            Step::Bearer => {
462                let line = format!(
463                    "{}▏{}",
464                    self.bearer_token
465                        .chars()
466                        .take(self.bearer_cursor)
467                        .collect::<String>(),
468                    self.bearer_token
469                        .chars()
470                        .skip(self.bearer_cursor)
471                        .collect::<String>()
472                );
473                let mut bearer_text = Text::from(vec![Line::from(line)]);
474                if self.bearer_token.is_empty() && self.reuse_keyring_bearer {
475                    bearer_text.push_line(Line::from(""));
476                    bearer_text.push_line(Line::from(Span::styled(
477                        "Token stored in OS keyring — leave blank to keep, or type a new token.",
478                        Style::default().fg(Color::DarkGray),
479                    )));
480                }
481                let block = Block::default().title(title).borders(Borders::ALL);
482                let p = Paragraph::new(bearer_text).block(block);
483                f.render_widget(p, main[1]);
484            }
485            Step::PairingCode => {
486                let line = format!(
487                    "{}▏{}",
488                    self.pairing_code
489                        .chars()
490                        .take(self.pairing_cursor)
491                        .collect::<String>(),
492                    self.pairing_code
493                        .chars()
494                        .skip(self.pairing_cursor)
495                        .collect::<String>()
496                );
497                let body = format!("Enter the 8-character code from the RomM web UI.\n\n{line}");
498                let block = Block::default().title(title).borders(Borders::ALL);
499                let p = Paragraph::new(body).block(block);
500                f.render_widget(p, main[1]);
501            }
502            Step::ApiHeader | Step::ApiKey => {
503                let header_line = if self.step == Step::ApiHeader {
504                    format!(
505                        "{}▏{}",
506                        self.api_header
507                            .chars()
508                            .take(self.header_cursor)
509                            .collect::<String>(),
510                        self.api_header
511                            .chars()
512                            .skip(self.header_cursor)
513                            .collect::<String>()
514                    )
515                } else {
516                    self.api_header.clone()
517                };
518                let key_line = if self.step == Step::ApiKey {
519                    "•".repeat(self.api_key.len()) + "▏"
520                } else {
521                    "•".repeat(self.api_key.len())
522                };
523                let kr_hint = if self.step == Step::ApiKey
524                    && self.api_key.is_empty()
525                    && self.reuse_keyring_api_key
526                {
527                    "\n\n(stored in OS keyring — leave blank to keep, or type a new key)"
528                } else {
529                    ""
530                };
531                let body = format!(
532                    "Header name\n{header_line}\n\nKey (hidden)\n{key_line}{kr_hint}\n\nTab: switch field"
533                );
534                let block = Block::default().title(title).borders(Borders::ALL);
535                let p = Paragraph::new(body).block(block);
536                f.render_widget(p, main[1]);
537            }
538            Step::Summary => {
539                let url_line = normalize_romm_origin(self.url.trim());
540                let auth_desc = match self.auth_kind {
541                    AuthKind::None => "None",
542                    AuthKind::Basic => "Basic",
543                    AuthKind::Bearer => "API Token",
544                    AuthKind::ApiKey => "API key header",
545                    AuthKind::Pairing => {
546                        if self.pairing_code.trim().is_empty() {
547                            "Pair with Web UI (no code yet)"
548                        } else {
549                            "Pair with Web UI (code entered)"
550                        }
551                    }
552                };
553                let mut lines = vec![
554                    format!("Server: {url_line}"),
555                    format!("ROMs Dir: {}", self.download_picker.path_trimmed()),
556                    format!("Use HTTPS: {}", if self.use_https { "Yes" } else { "No" }),
557                    format!("Auth: {auth_desc}"),
558                    String::new(),
559                ];
560                if self.testing {
561                    lines.push("Connecting to server…".to_string());
562                } else if let Some(ref e) = self.error {
563                    lines.push(format!("Last error: {e}"));
564                } else {
565                    lines.push("Enter: test connection and save   Esc: quit".to_string());
566                }
567                let block = Block::default().title(title).borders(Borders::ALL);
568                let p = Paragraph::new(lines.join("\n")).block(block);
569                f.render_widget(p, main[1]);
570            }
571        }
572
573        let footer_keys = match self.step {
574            Step::Url => "Enter: next   Backspace: delete   Esc: quit",
575            Step::Https => "Space: toggle   Enter: next   Esc: quit",
576            Step::Download => "Ctrl+Enter: next (creates path)   ↑ list top: path bar   Tab: path/list   Esc: quit",
577            Step::AuthMenu => "↑/↓: choose   Enter: next   Esc: quit",
578            Step::BasicUser | Step::BasicPass => {
579                "Type text   Tab: switch field   Enter: next step   Esc: quit"
580            }
581            Step::Bearer => "Enter: next step   Esc: quit",
582            Step::PairingCode => "Enter: next step   Esc: quit",
583            Step::ApiHeader | Step::ApiKey => "Tab: switch field   Enter: next step   Esc: quit",
584            Step::Summary => {
585                if self.testing {
586                    "Please wait…"
587                } else {
588                    "Enter: connect & save"
589                }
590            }
591        };
592        let p = Paragraph::new(wizard_footer_text(footer_keys))
593            .block(Block::default().borders(Borders::ALL));
594        f.render_widget(p, main[2]);
595    }
596
597    pub fn cursor_pos(&self, area: ratatui::layout::Rect) -> Option<(u16, u16)> {
598        let main = wizard_layout(area, self.step);
599        let inner = main[1];
600        match self.step {
601            Step::Url => {
602                let x = inner.x + 1 + self.url_cursor.min(self.url.len()) as u16;
603                Some((x, inner.y + 1))
604            }
605            Step::Download => self
606                .download_picker
607                .cursor_position(inner, "Step 3/5 — ROMs directory"),
608            Step::Bearer => {
609                let x = inner.x + 1 + self.bearer_cursor.min(self.bearer_token.len()) as u16;
610                Some((x, inner.y + 1))
611            }
612            Step::PairingCode => {
613                let x = inner.x + 1 + self.pairing_cursor.min(self.pairing_code.len()) as u16;
614                Some((x, inner.y + 3))
615            }
616            Step::BasicUser => {
617                let x = inner.x + 1 + self.user_cursor.min(self.username.len()) as u16;
618                Some((x, inner.y + 2))
619            }
620            Step::BasicPass => {
621                let x = inner.x + 1 + "•".repeat(self.password.len()).len() as u16;
622                Some((x, inner.y + 6))
623            }
624            Step::ApiHeader => {
625                let x = inner.x + 1 + self.header_cursor.min(self.api_header.len()) as u16;
626                Some((x, inner.y + 2))
627            }
628            Step::ApiKey => {
629                let x = inner.x + 1 + self.api_key_cursor.min(self.api_key.len()) as u16;
630                Some((x, inner.y + 6))
631            }
632            Step::Https | Step::AuthMenu | Step::Summary => None,
633        }
634    }
635
636    fn add_char_url(&mut self, c: char) {
637        let pos = self.url_cursor.min(self.url.len());
638        self.url.insert(pos, c);
639        self.url_cursor = pos + 1;
640    }
641
642    fn del_char_url(&mut self) {
643        if self.url_cursor > 0 && self.url_cursor <= self.url.len() {
644            self.url.remove(self.url_cursor - 1);
645            self.url_cursor -= 1;
646        }
647    }
648
649    fn advance_from_auth_menu(&mut self) {
650        self.auth_kind = Self::auth_kind_from_index(self.auth_menu_selected);
651        self.step = match self.auth_kind {
652            AuthKind::None => Step::Summary,
653            AuthKind::Basic => Step::BasicUser,
654            AuthKind::Bearer => Step::Bearer,
655            AuthKind::ApiKey => Step::ApiHeader,
656            AuthKind::Pairing => {
657                self.pairing_cursor = self.pairing_code.len();
658                Step::PairingCode
659            }
660        };
661    }
662
663    fn advance_step(&mut self) -> Result<()> {
664        self.error = None;
665        match self.step {
666            Step::Url => {
667                if normalize_romm_origin(self.url.trim()).is_empty() {
668                    self.error = Some("Enter a valid server URL".to_string());
669                    return Ok(());
670                }
671                self.step = Step::Https;
672            }
673            Step::Https => {
674                self.step = Step::Download;
675            }
676            Step::Download => {}
677            Step::AuthMenu => self.advance_from_auth_menu(),
678            Step::BasicUser => self.step = Step::BasicPass,
679            Step::BasicPass => self.step = Step::Summary,
680            Step::Bearer => self.step = Step::Summary,
681            Step::ApiHeader => self.step = Step::ApiKey,
682            Step::ApiKey => self.step = Step::Summary,
683            Step::PairingCode => self.step = Step::Summary,
684            Step::Summary => {}
685        }
686        Ok(())
687    }
688
689    pub async fn try_connect_and_persist(&mut self, verbose: bool) -> Result<Config> {
690        let cfg = if self.auth_kind == AuthKind::Pairing {
691            self.pairing_config_from_exchange(verbose).await?
692        } else {
693            self.build_config()?
694        };
695        let client = RommClient::new(&cfg, verbose)?;
696        client.fetch_openapi_json().await?;
697        let base = cfg.base_url.clone();
698        let download = self.download_picker.path_trimmed();
699        persist_user_config(&base, &download, self.use_https, cfg.auth.clone())?;
700        load_config()
701    }
702
703    pub fn handle_key(&mut self, key: &KeyEvent) -> Result<bool> {
704        if key.kind != KeyEventKind::Press {
705            return Ok(false);
706        }
707        if key.code == KeyCode::Esc {
708            return Ok(true); // Signal to caller that we should exit/cancel
709        }
710
711        if self.testing {
712            return Ok(false);
713        }
714
715        match self.step {
716            Step::Url => match key.code {
717                KeyCode::Enter => {
718                    let _ = self.advance_step();
719                }
720                KeyCode::Char(c) => self.add_char_url(c),
721                KeyCode::Backspace => self.del_char_url(),
722                KeyCode::Left if self.url_cursor > 0 => {
723                    self.url_cursor -= 1;
724                }
725                KeyCode::Right if self.url_cursor < self.url.len() => {
726                    self.url_cursor += 1;
727                }
728                _ => {}
729            },
730            Step::Https => match key.code {
731                KeyCode::Enter => {
732                    let _ = self.advance_step();
733                }
734                KeyCode::Char(' ') => self.use_https = !self.use_https,
735                _ => {}
736            },
737            Step::Download => match self.download_picker.handle_key(key) {
738                PathPickerEvent::Confirmed(p) => {
739                    self.error = None;
740                    match validate_configured_download_directory(p.to_string_lossy().as_ref()) {
741                        Ok(canonical) => {
742                            self.download_picker
743                                .set_path_text(canonical.display().to_string());
744                            self.step = Step::AuthMenu;
745                        }
746                        Err(e) => {
747                            self.error = Some(format!("{e:#}"));
748                        }
749                    }
750                }
751                PathPickerEvent::None => {}
752            },
753            Step::AuthMenu => match key.code {
754                KeyCode::Up | KeyCode::Char('k') if self.auth_menu_selected > 0 => {
755                    self.auth_menu_selected -= 1;
756                }
757                KeyCode::Down | KeyCode::Char('j') if self.auth_menu_selected < 4 => {
758                    self.auth_menu_selected += 1;
759                }
760                KeyCode::Enter => {
761                    let _ = self.advance_step();
762                }
763                _ => {}
764            },
765            Step::BasicUser => match key.code {
766                KeyCode::Tab => self.step = Step::BasicPass,
767                KeyCode::Enter => {
768                    let _ = self.advance_step();
769                }
770                KeyCode::Char(c) => {
771                    let pos = self.user_cursor.min(self.username.len());
772                    self.username.insert(pos, c);
773                    self.user_cursor = pos + 1;
774                }
775                KeyCode::Backspace
776                    if self.user_cursor > 0 && self.user_cursor <= self.username.len() =>
777                {
778                    self.username.remove(self.user_cursor - 1);
779                    self.user_cursor -= 1;
780                }
781                KeyCode::Left if self.user_cursor > 0 => {
782                    self.user_cursor -= 1;
783                }
784                KeyCode::Right if self.user_cursor < self.username.len() => {
785                    self.user_cursor += 1;
786                }
787                _ => {}
788            },
789            Step::BasicPass => match key.code {
790                KeyCode::Tab => self.step = Step::BasicUser,
791                KeyCode::Enter => {
792                    let _ = self.advance_step();
793                }
794                KeyCode::Char(c) => {
795                    self.reuse_keyring_password = false;
796                    self.password.push(c);
797                }
798                KeyCode::Backspace => {
799                    self.password.pop();
800                }
801                _ => {}
802            },
803            Step::Bearer => match key.code {
804                KeyCode::Enter => {
805                    let _ = self.advance_step();
806                }
807                KeyCode::Char(c) => {
808                    self.reuse_keyring_bearer = false;
809                    let pos = self.bearer_cursor.min(self.bearer_token.len());
810                    self.bearer_token.insert(pos, c);
811                    self.bearer_cursor = pos + 1;
812                }
813                KeyCode::Backspace
814                    if self.bearer_cursor > 0 && self.bearer_cursor <= self.bearer_token.len() =>
815                {
816                    self.bearer_token.remove(self.bearer_cursor - 1);
817                    self.bearer_cursor -= 1;
818                }
819                KeyCode::Left if self.bearer_cursor > 0 => {
820                    self.bearer_cursor -= 1;
821                }
822                KeyCode::Right if self.bearer_cursor < self.bearer_token.len() => {
823                    self.bearer_cursor += 1;
824                }
825                _ => {}
826            },
827            Step::PairingCode => match key.code {
828                KeyCode::Enter => {
829                    let _ = self.advance_step();
830                }
831                KeyCode::Char(c) => {
832                    let pos = self.pairing_cursor.min(self.pairing_code.len());
833                    self.pairing_code.insert(pos, c);
834                    self.pairing_cursor = pos + 1;
835                }
836                KeyCode::Backspace
837                    if self.pairing_cursor > 0
838                        && self.pairing_cursor <= self.pairing_code.len() =>
839                {
840                    self.pairing_code.remove(self.pairing_cursor - 1);
841                    self.pairing_cursor -= 1;
842                }
843                KeyCode::Left if self.pairing_cursor > 0 => {
844                    self.pairing_cursor -= 1;
845                }
846                KeyCode::Right if self.pairing_cursor < self.pairing_code.len() => {
847                    self.pairing_cursor += 1;
848                }
849                _ => {}
850            },
851            Step::ApiHeader => match key.code {
852                KeyCode::Tab => self.step = Step::ApiKey,
853                KeyCode::Enter => {
854                    let _ = self.advance_step();
855                }
856                KeyCode::Char(c) => {
857                    let pos = self.header_cursor.min(self.api_header.len());
858                    self.api_header.insert(pos, c);
859                    self.header_cursor = pos + 1;
860                }
861                KeyCode::Backspace
862                    if self.header_cursor > 0 && self.header_cursor <= self.api_header.len() =>
863                {
864                    self.api_header.remove(self.header_cursor - 1);
865                    self.header_cursor -= 1;
866                }
867                KeyCode::Left if self.header_cursor > 0 => {
868                    self.header_cursor -= 1;
869                }
870                KeyCode::Right if self.header_cursor < self.api_header.len() => {
871                    self.header_cursor += 1;
872                }
873                _ => {}
874            },
875            Step::ApiKey => match key.code {
876                KeyCode::Tab => self.step = Step::ApiHeader,
877                KeyCode::Enter => {
878                    let _ = self.advance_step();
879                }
880                KeyCode::Char(c) => {
881                    self.reuse_keyring_api_key = false;
882                    let pos = self.api_key_cursor.min(self.api_key.len());
883                    self.api_key.insert(pos, c);
884                    self.api_key_cursor = pos + 1;
885                }
886                KeyCode::Backspace
887                    if self.api_key_cursor > 0 && self.api_key_cursor <= self.api_key.len() =>
888                {
889                    self.api_key.remove(self.api_key_cursor - 1);
890                    self.api_key_cursor -= 1;
891                }
892                KeyCode::Left if self.api_key_cursor > 0 => {
893                    self.api_key_cursor -= 1;
894                }
895                KeyCode::Right if self.api_key_cursor < self.api_key.len() => {
896                    self.api_key_cursor += 1;
897                }
898                _ => {}
899            },
900            Step::Summary => {
901                if key.code == KeyCode::Enter {
902                    self.testing = true;
903                    self.error = None;
904                    // The caller handles the actual async try_connect_and_persist call
905                    // when they see testing = true.
906                }
907            }
908        }
909        Ok(false)
910    }
911
912    pub async fn run(mut self, verbose: bool) -> Result<Config> {
913        enable_raw_mode()?;
914        let mut stdout = stdout();
915        execute!(stdout, EnterAlternateScreen, EnableMouseCapture)?;
916        let backend = CrosstermBackend::new(stdout);
917        let mut terminal = Terminal::new(backend)?;
918
919        loop {
920            terminal.draw(|f| {
921                let area = f.area();
922                self.render(f, area);
923                if let Some((x, y)) = self.cursor_pos(area) {
924                    f.set_cursor_position((x, y));
925                }
926            })?;
927
928            if event::poll(std::time::Duration::from_millis(100))? {
929                if let Event::Key(key) = event::read()? {
930                    if self.handle_key(&key)? {
931                        disable_raw_mode()?;
932                        execute!(
933                            terminal.backend_mut(),
934                            LeaveAlternateScreen,
935                            DisableMouseCapture
936                        )?;
937                        terminal.show_cursor()?;
938                        return Err(anyhow!("setup cancelled"));
939                    }
940
941                    if self.testing {
942                        terminal.draw(|f| {
943                            let area = f.area();
944                            self.render(f, area);
945                        })?;
946                        let result = self.try_connect_and_persist(verbose).await;
947                        self.testing = false;
948                        match result {
949                            Ok(cfg) => {
950                                disable_raw_mode()?;
951                                execute!(
952                                    terminal.backend_mut(),
953                                    LeaveAlternateScreen,
954                                    DisableMouseCapture
955                                )?;
956                                terminal.show_cursor()?;
957                                return Ok(cfg);
958                            }
959                            Err(e) => {
960                                self.error = Some(format!("{e:#}"));
961                            }
962                        }
963                    }
964                }
965            }
966        }
967    }
968}
969
970impl Default for SetupWizard {
971    fn default() -> Self {
972        Self::new()
973    }
974}
975
976#[cfg(test)]
977mod tests {
978    use super::*;
979    use wiremock::matchers::{method, path};
980    use wiremock::{Mock, MockServer, ResponseTemplate};
981
982    fn wizard_with_pairing(mock_uri: &str, code: &str) -> SetupWizard {
983        SetupWizard {
984            step: Step::PairingCode,
985            auth_kind: AuthKind::Pairing,
986            auth_menu_selected: 4,
987            url: mock_uri.to_string(),
988            url_cursor: mock_uri.len(),
989            download_picker: PathPicker::new(PathPickerMode::Directory, "/tmp/romm-dl-test"),
990            username: String::new(),
991            user_cursor: 0,
992            password: String::new(),
993            bearer_token: String::new(),
994            bearer_cursor: 0,
995            api_header: String::new(),
996            header_cursor: 0,
997            api_key: String::new(),
998            api_key_cursor: 0,
999            pairing_code: code.to_string(),
1000            pairing_cursor: code.len(),
1001            reuse_keyring_password: false,
1002            reuse_keyring_bearer: false,
1003            reuse_keyring_api_key: false,
1004            testing: false,
1005            use_https: false,
1006            error: None,
1007        }
1008    }
1009
1010    #[tokio::test]
1011    async fn pairing_config_from_exchange_returns_bearer_token() {
1012        let mock_server = MockServer::start().await;
1013
1014        let token_json = serde_json::json!({
1015            "id": 1,
1016            "name": "cli-device",
1017            "scopes": [],
1018            "expires_at": null,
1019            "last_used_at": null,
1020            "created_at": "2020-01-01T00:00:00Z",
1021            "user_id": 42,
1022            "raw_token": "exchanged-bearer-secret"
1023        });
1024
1025        Mock::given(method("POST"))
1026            .and(path("/api/client-tokens/exchange"))
1027            .respond_with(ResponseTemplate::new(200).set_body_json(&token_json))
1028            .mount(&mock_server)
1029            .await;
1030
1031        let uri = mock_server.uri();
1032        let wizard = wizard_with_pairing(&uri, "ABCD1234");
1033        let cfg = wizard
1034            .pairing_config_from_exchange(false)
1035            .await
1036            .expect("pairing exchange should succeed");
1037
1038        match cfg.auth {
1039            Some(AuthConfig::Bearer { token }) => {
1040                assert_eq!(token, "exchanged-bearer-secret");
1041            }
1042            _ => panic!("expected bearer auth after pairing exchange"),
1043        }
1044        assert_eq!(cfg.base_url, normalize_romm_origin(&uri));
1045        let expected_download_dir =
1046            validate_configured_download_directory("/tmp/romm-dl-test").unwrap();
1047        assert_eq!(
1048            cfg.download_dir,
1049            expected_download_dir.display().to_string()
1050        );
1051    }
1052}