Skip to main content

cc_switch/interactive/
omp_interactive.rs

1use crate::cli::display_utils::{
2    TextAlignment, get_terminal_width, pad_text_to_width, text_display_width,
3};
4use crate::config::types::ConfigStorage;
5use crate::interactive::interactive::{
6    EditModeError, cleanup_terminal, edit_optional_string_field, edit_string_field,
7};
8use crate::omp::{OmpConfiguration, write_env_file};
9use crate::platform::resolve_npm_cli;
10use anyhow::Result;
11use colored::*;
12use crossterm::{
13    event::{self, Event, KeyCode, KeyEvent, KeyEventKind},
14    execute, terminal,
15};
16use std::io::{self, Write};
17use std::process::Command;
18
19/// Handle interactive OMP configuration selection with full TUI
20///
21/// Mirrors the Claude interactive TUI: alternate screen, arrow key / j/k navigation,
22/// number key shortcuts (1-9), pagination (9 per page), config detail preview.
23///
24/// # Arguments
25/// * `storage` - Reference to configuration storage
26///
27/// # Errors
28/// Returns error if terminal operations fail or user selection fails
29pub fn handle_omp_interactive_selection(storage: &ConfigStorage) -> Result<()> {
30    let configs_map = match &storage.omp_configurations {
31        Some(configs) if !configs.is_empty() => configs,
32        _ => {
33            println!(
34                "No OMP configurations available. Use 'cc-switch omp add' to create configurations first."
35            );
36            return Ok(());
37        }
38    };
39
40    let mut configs: Vec<OmpConfiguration> = configs_map.values().cloned().collect();
41    configs.sort_by(|a, b| a.alias_name.cmp(&b.alias_name));
42
43    let mut selected_index: usize = 0;
44
45    // Try to enable raw mode, fallback to simple menu if it fails
46    let raw_mode_enabled = terminal::enable_raw_mode().is_ok();
47
48    if raw_mode_enabled {
49        let mut stdout = io::stdout();
50        if execute!(
51            stdout,
52            terminal::EnterAlternateScreen,
53            terminal::Clear(terminal::ClearType::All)
54        )
55        .is_ok()
56        {
57            let result =
58                handle_omp_full_interactive_menu(&mut stdout, &mut configs, &mut selected_index);
59
60            // Always restore terminal
61            let _ = execute!(stdout, terminal::LeaveAlternateScreen);
62            let _ = terminal::disable_raw_mode();
63
64            return result;
65        } else {
66            let _ = terminal::disable_raw_mode();
67        }
68    }
69
70    // Fallback to simple numbered menu
71    handle_omp_simple_interactive_menu(&configs)
72}
73
74/// Format OMP configuration details for display
75///
76/// # Arguments
77/// * `config` - The configuration to format
78/// * `indent` - Base indentation string (e.g., "    " or "   ")
79///
80/// # Returns
81/// Vector of formatted lines for configuration display
82fn format_omp_config_details(config: &OmpConfiguration, indent: &str) -> Vec<String> {
83    let mut lines = Vec::new();
84
85    let terminal_width = get_terminal_width();
86    let _available_width = terminal_width.saturating_sub(text_display_width(indent) + 8);
87
88    // Field labels with consistent width for alignment
89    let api_key_label = "API Key:";
90    let base_url_label = "Base URL:";
91    let slow_model_label = "Slow Model:";
92    let smol_model_label = "Smol Model:";
93    let plan_model_label = "Plan Model:";
94
95    let max_label_width = [
96        api_key_label,
97        base_url_label,
98        slow_model_label,
99        smol_model_label,
100        plan_model_label,
101    ]
102    .iter()
103    .map(|label| text_display_width(label))
104    .max()
105    .unwrap_or(0);
106
107    // API Key (masked)
108    if let Some(key) = config.openai_api_key.as_ref().map(|k| mask_key(k)) {
109        lines.push(format!(
110            "{}{} {:<width$} {}",
111            indent,
112            "•".blue(),
113            api_key_label.blue().bold(),
114            key,
115            width = max_label_width
116        ));
117    }
118
119    // Base URL
120    if let Some(ref url) = config.base_url {
121        lines.push(format!(
122            "{}{} {:<width$} {}",
123            indent,
124            "•".blue(),
125            base_url_label.blue().bold(),
126            url,
127            width = max_label_width
128        ));
129    }
130
131    // Model configurations
132    if let Some(ref model) = config.slow_model {
133        lines.push(format!(
134            "{}{} {:<width$} {}",
135            indent,
136            "•".blue(),
137            slow_model_label.blue().bold(),
138            model,
139            width = max_label_width
140        ));
141    }
142
143    if let Some(ref model) = config.smol_model {
144        lines.push(format!(
145            "{}{} {:<width$} {}",
146            indent,
147            "•".blue(),
148            smol_model_label.blue().bold(),
149            model,
150            width = max_label_width
151        ));
152    }
153
154    if let Some(ref model) = config.plan_model {
155        lines.push(format!(
156            "{}{} {:<width$} {}",
157            indent,
158            "•".blue(),
159            plan_model_label.blue().bold(),
160            model,
161            width = max_label_width
162        ));
163    }
164
165    lines
166}
167
168/// Mask API key for display (show first 4 and last 4 characters)
169fn mask_key(key: &str) -> String {
170    if key.len() <= 8 {
171        "*".repeat(key.len())
172    } else {
173        format!("{}****{}", &key[..4], &key[key.len() - 4..])
174    }
175}
176
177#[allow(clippy::ptr_arg)]
178fn handle_omp_full_interactive_menu(
179    stdout: &mut io::Stdout,
180    configs: &mut Vec<OmpConfiguration>,
181    selected_index: &mut usize,
182) -> Result<()> {
183    let page_size = 9;
184    let mut current_page = 0;
185    let total_pages = configs.len().div_ceil(page_size);
186
187    loop {
188        execute!(stdout, terminal::Clear(terminal::ClearType::All))?;
189
190        // Draw header
191        let header = "OMP Configuration Selector";
192        let width = get_terminal_width();
193        let padded_header = pad_text_to_width(header, width, TextAlignment::Center, ' ');
194        writeln!(stdout, "{}", padded_header.white().bold().on_blue())?;
195        writeln!(stdout)?;
196
197        if configs.is_empty() {
198            writeln!(
199                stdout,
200                "\r{}",
201                "Use 'cc-switch omp add' to add configurations first.".dimmed()
202            )?;
203            writeln!(stdout, "\r{}", "Press any key to continue...".dimmed())?;
204            let _ = event::read();
205            return Ok(());
206        }
207
208        // Calculate page boundaries
209        let start_idx = current_page * page_size;
210        let end_idx = (start_idx + page_size).min(configs.len());
211
212        // Display configurations on current page
213        for (i, config) in configs[start_idx..end_idx].iter().enumerate() {
214            let actual_index = start_idx + i;
215            let is_selected = actual_index == *selected_index;
216
217            let indicator = if is_selected {
218                format!("{} ", "→".green().bold())
219            } else {
220                "  ".to_string()
221            };
222
223            let number = format!("{:>2}.", i + 1);
224            let number_display = if is_selected {
225                number.green().bold()
226            } else {
227                number.normal()
228            };
229
230            writeln!(
231                stdout,
232                "\r{}{} {}",
233                indicator,
234                number_display,
235                config.alias_name.bold()
236            )?;
237
238            // Show config details if selected
239            if is_selected {
240                let details = format_omp_config_details(config, "\r    ");
241                for detail_line in details {
242                    writeln!(stdout, "{detail_line}")?;
243                }
244            }
245            writeln!(stdout)?;
246        }
247
248        // Draw footer
249        writeln!(stdout)?;
250        let footer = if total_pages > 1 {
251            format!(
252                "Page {}/{} | ↑↓/j/k: Navigate | 1-9: Select | Enter: Use | e: Edit | d: Delete | n: Next | p: Prev | q: Quit",
253                current_page + 1,
254                total_pages
255            )
256        } else {
257            "↑↓/j/k: Navigate | 1-9: Select | Enter: Use | e: Edit | d: Delete | q: Quit"
258                .to_string()
259        };
260        let padded_footer = pad_text_to_width(&footer, width, TextAlignment::Center, ' ');
261        writeln!(stdout, "{}", padded_footer.white().on_bright_black())?;
262
263        stdout.flush()?;
264
265        // Handle input
266        if let Event::Key(KeyEvent {
267            code,
268            kind: KeyEventKind::Press,
269            ..
270        }) = event::read()?
271        {
272            match code {
273                KeyCode::Char('q') | KeyCode::Char('Q') => {
274                    cleanup_terminal(stdout);
275                    return Ok(());
276                }
277                KeyCode::Up | KeyCode::Char('k') => {
278                    if *selected_index > 0 {
279                        *selected_index -= 1;
280                        if *selected_index < start_idx {
281                            current_page = current_page.saturating_sub(1);
282                        }
283                    }
284                }
285                KeyCode::Down | KeyCode::Char('j') => {
286                    if *selected_index < configs.len() - 1 {
287                        *selected_index += 1;
288                        if *selected_index >= end_idx {
289                            current_page = (current_page + 1).min(total_pages - 1);
290                        }
291                    }
292                }
293                KeyCode::Char('n') | KeyCode::Char('N') => {
294                    if current_page < total_pages - 1 {
295                        current_page += 1;
296                        *selected_index = current_page * page_size;
297                    }
298                }
299                KeyCode::Char('p') | KeyCode::Char('P') => {
300                    if current_page > 0 {
301                        current_page -= 1;
302                        *selected_index = current_page * page_size;
303                    }
304                }
305                KeyCode::Char('d') | KeyCode::Char('D') if *selected_index < configs.len() => {
306                    cleanup_terminal(stdout);
307                    let config_name = configs[*selected_index].alias_name.clone();
308                    println!("Delete configuration '{}'? (y/n): ", config_name);
309                    let mut input = String::new();
310                    io::stdin().read_line(&mut input)?;
311                    if input.trim().to_lowercase() == "y" {
312                        let mut storage = ConfigStorage::load()?;
313                        if storage.remove_omp_configuration(&config_name) {
314                            storage.save()?;
315                            configs.remove(*selected_index);
316                            if *selected_index >= configs.len() && !configs.is_empty() {
317                                *selected_index = configs.len() - 1;
318                            }
319                            println!("Configuration '{}' deleted.", config_name);
320                        }
321                    }
322                    // Re-enter alternate screen
323                    execute!(
324                        stdout,
325                        terminal::EnterAlternateScreen,
326                        terminal::Clear(terminal::ClearType::All)
327                    )?;
328                }
329                KeyCode::Char('e') | KeyCode::Char('E') if *selected_index < configs.len() => {
330                    cleanup_terminal(stdout);
331                    let edit_result = handle_omp_config_edit(&configs[*selected_index]);
332                    if execute!(
333                        stdout,
334                        terminal::EnterAlternateScreen,
335                        terminal::Clear(terminal::ClearType::All)
336                    )
337                    .is_err()
338                    {
339                        return edit_result;
340                    }
341                    if edit_result.is_ok() {
342                        // Reload configurations
343                        if let Ok(reloaded_storage) = ConfigStorage::load()
344                            && let Some(ref map) = reloaded_storage.omp_configurations
345                        {
346                            *configs = map.values().cloned().collect();
347                            configs.sort_by(|a, b| a.alias_name.cmp(&b.alias_name));
348                        }
349                    }
350                }
351                KeyCode::Char(c) if c.is_ascii_digit() => {
352                    let digit = c.to_digit(10).unwrap() as usize;
353                    if digit >= 1 && digit <= (end_idx - start_idx) {
354                        let actual_config_index = start_idx + (digit - 1);
355                        cleanup_terminal(stdout);
356                        return handle_omp_selection_action(configs, actual_config_index);
357                    }
358                }
359                KeyCode::Enter => {
360                    if *selected_index < configs.len() {
361                        cleanup_terminal(stdout);
362                        return handle_omp_selection_action(configs, *selected_index);
363                    }
364                }
365                KeyCode::Esc => {
366                    cleanup_terminal(stdout);
367                    return Ok(());
368                }
369                _ => {}
370            }
371        }
372    }
373}
374
375/// Handle simple interactive menu (fallback) for OMP
376fn handle_omp_simple_interactive_menu(configs: &[OmpConfiguration]) -> Result<()> {
377    const PAGE_SIZE: usize = 9;
378
379    if configs.len() <= PAGE_SIZE {
380        return handle_omp_simple_single_page_menu(configs);
381    }
382
383    // Multi-page simple menu
384    let total_pages = configs.len().div_ceil(PAGE_SIZE);
385    let mut current_page = 0;
386
387    loop {
388        println!("\n{}", "Available OMP Configurations:".blue().bold());
389        println!("Page {}/{}", current_page + 1, total_pages);
390        println!("{}", "-".repeat(50));
391
392        let start_idx = current_page * PAGE_SIZE;
393        let end_idx = (start_idx + PAGE_SIZE).min(configs.len());
394
395        for (i, config) in configs[start_idx..end_idx].iter().enumerate() {
396            let number = start_idx + i + 1;
397            println!(
398                "{:>2}. {}{}",
399                number,
400                config.alias_name.bold(),
401                config
402                    .slow_model
403                    .as_ref()
404                    .map(|m| format!(" ({})", m))
405                    .unwrap_or_default()
406            );
407        }
408
409        println!(
410            "\nEnter number (1-{}), 'n' for next, 'p' for prev, or 'q' to quit: ",
411            end_idx - start_idx
412        );
413
414        let mut input = String::new();
415        io::stdin().read_line(&mut input)?;
416        let input = input.trim();
417
418        match input {
419            "q" | "Q" => return Ok(()),
420            "n" | "N" => {
421                if current_page < total_pages - 1 {
422                    current_page += 1;
423                }
424            }
425            "p" | "P" => {
426                current_page = current_page.saturating_sub(1);
427            }
428            _ => {
429                if let Ok(num) = input.parse::<usize>()
430                    && num >= 1
431                    && num <= configs.len()
432                {
433                    return handle_omp_selection_action(configs, num - 1);
434                }
435                println!("Invalid selection, please try again");
436            }
437        }
438    }
439}
440
441/// Handle simple single page menu (original behavior for ≤9 configs)
442fn handle_omp_simple_single_page_menu(configs: &[OmpConfiguration]) -> Result<()> {
443    println!("\n{}", "Available OMP Configurations:".blue().bold());
444
445    for (index, config) in configs.iter().enumerate() {
446        println!("{:>2}. {}", index + 1, config.alias_name.bold());
447
448        let details = format_omp_config_details(config, "   ");
449        for detail_line in details {
450            println!("{detail_line}");
451        }
452        println!();
453    }
454
455    println!("Enter number (1-{}), or 'q' to quit: ", configs.len());
456
457    loop {
458        let mut input = String::new();
459        io::stdin().read_line(&mut input)?;
460        let input = input.trim();
461
462        if input == "q" || input == "Q" {
463            return Ok(());
464        }
465
466        if let Ok(num) = input.parse::<usize>()
467            && num >= 1
468            && num <= configs.len()
469        {
470            return handle_omp_selection_action(configs, num - 1);
471        }
472
473        println!("Invalid selection, please try again");
474    }
475}
476
477/// Handle the action after a configuration is selected
478fn handle_omp_selection_action(configs: &[OmpConfiguration], index: usize) -> Result<()> {
479    let config = &configs[index];
480    println!(
481        "\nSwitching to OMP configuration '{}'...",
482        config.alias_name
483    );
484
485    // Write the .env file
486    write_env_file(config)?;
487
488    // Launch OMP
489    let omp_path = resolve_npm_cli("omp");
490    let status = Command::new(omp_path).status()?;
491
492    if !status.success() {
493        eprintln!("OMP exited with non-zero status: {}", status);
494    }
495
496    Ok(())
497}
498
499/// Handle editing an OMP configuration interactively
500fn handle_omp_config_edit(config: &OmpConfiguration) -> Result<()> {
501    println!("\n{}", "Edit OMP Configuration".bold());
502    println!("{}", "=".repeat(50));
503
504    let mut storage = ConfigStorage::load()?;
505    let mut edited_config = config.clone();
506
507    // Edit alias name
508    match edit_string_field("Alias name", &edited_config.alias_name, |_| Ok(())) {
509        Ok(Some(new_alias)) => {
510            edited_config.alias_name = new_alias;
511        }
512        Ok(None) => {}
513        Err(e) => {
514            if e.downcast_ref::<EditModeError>() == Some(&EditModeError::ReturnToMenu) {
515                println!("Edit cancelled.");
516                return Ok(());
517            }
518            return Err(e);
519        }
520    }
521
522    // Edit OpenAI API key
523    let current_key = edited_config.openai_api_key.clone().unwrap_or_default();
524    match edit_string_field("OpenAI API Key", &current_key, |_| Ok(())) {
525        Ok(Some(new_key)) => {
526            edited_config.openai_api_key = Some(new_key);
527        }
528        Ok(None) => {}
529        Err(e) => {
530            if e.downcast_ref::<EditModeError>() == Some(&EditModeError::ReturnToMenu) {
531                println!("Edit cancelled.");
532                return Ok(());
533            }
534            return Err(e);
535        }
536    }
537
538    // Edit base URL
539    if let Some(result) = edit_optional_string_field("Base URL", edited_config.base_url.as_deref())?
540    {
541        edited_config.base_url = result;
542    }
543
544    // Edit model configurations
545    if let Some(result) =
546        edit_optional_string_field("Slow Model", edited_config.slow_model.as_deref())?
547    {
548        edited_config.slow_model = result;
549    }
550
551    if let Some(result) =
552        edit_optional_string_field("Smol Model", edited_config.smol_model.as_deref())?
553    {
554        edited_config.smol_model = result;
555    }
556
557    if let Some(result) =
558        edit_optional_string_field("Plan Model", edited_config.plan_model.as_deref())?
559    {
560        edited_config.plan_model = result;
561    }
562
563    // Save the edited configuration
564    storage.update_omp_configuration(&config.alias_name, edited_config)?;
565    storage.save()?;
566
567    println!("\n{}", "Configuration updated successfully!".green().bold());
568    Ok(())
569}