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
19pub 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 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 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 handle_omp_simple_interactive_menu(&configs)
72}
73
74fn 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 let auth_mode_label = "Auth Mode:";
90 let api_key_label = "API Key:";
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 auth_mode_label,
97 api_key_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 lines.push(format!(
109 "{}{} {:<width$} {}",
110 indent,
111 "•".blue(),
112 auth_mode_label.blue().bold(),
113 config.auth_mode.green(),
114 width = max_label_width
115 ));
116
117 let api_key_display = match config.auth_mode.as_str() {
119 "anthropic" => config
120 .anthropic_api_key
121 .as_ref()
122 .map(|k| mask_key(k))
123 .or_else(|| config.anthropic_oauth_token.as_ref().map(|t| mask_key(t))),
124 "openai" => config.openai_api_key.as_ref().map(|k| mask_key(k)),
125 _ => None,
126 };
127
128 if let Some(key) = api_key_display {
129 lines.push(format!(
130 "{}{} {:<width$} {}",
131 indent,
132 "•".blue(),
133 api_key_label.blue().bold(),
134 key,
135 width = max_label_width
136 ));
137 }
138
139 if let Some(ref model) = config.slow_model {
141 lines.push(format!(
142 "{}{} {:<width$} {}",
143 indent,
144 "•".blue(),
145 slow_model_label.blue().bold(),
146 model,
147 width = max_label_width
148 ));
149 }
150
151 if let Some(ref model) = config.smol_model {
152 lines.push(format!(
153 "{}{} {:<width$} {}",
154 indent,
155 "•".blue(),
156 smol_model_label.blue().bold(),
157 model,
158 width = max_label_width
159 ));
160 }
161
162 if let Some(ref model) = config.plan_model {
163 lines.push(format!(
164 "{}{} {:<width$} {}",
165 indent,
166 "•".blue(),
167 plan_model_label.blue().bold(),
168 model,
169 width = max_label_width
170 ));
171 }
172
173 lines
174}
175
176fn mask_key(key: &str) -> String {
178 if key.len() <= 8 {
179 "*".repeat(key.len())
180 } else {
181 format!("{}****{}", &key[..4], &key[key.len() - 4..])
182 }
183}
184
185#[allow(clippy::ptr_arg)]
186fn handle_omp_full_interactive_menu(
187 stdout: &mut io::Stdout,
188 configs: &mut Vec<OmpConfiguration>,
189 selected_index: &mut usize,
190) -> Result<()> {
191 let page_size = 9;
192 let mut current_page = 0;
193 let total_pages = configs.len().div_ceil(page_size);
194
195 loop {
196 execute!(stdout, terminal::Clear(terminal::ClearType::All))?;
197
198 let header = "OMP Configuration Selector";
200 let width = get_terminal_width();
201 let padded_header = pad_text_to_width(header, width, TextAlignment::Center, ' ');
202 writeln!(stdout, "{}", padded_header.white().bold().on_blue())?;
203 writeln!(stdout)?;
204
205 if configs.is_empty() {
206 writeln!(
207 stdout,
208 "\r{}",
209 "Use 'cc-switch omp add' to add configurations first.".dimmed()
210 )?;
211 writeln!(stdout, "\r{}", "Press any key to continue...".dimmed())?;
212 let _ = event::read();
213 return Ok(());
214 }
215
216 let start_idx = current_page * page_size;
218 let end_idx = (start_idx + page_size).min(configs.len());
219
220 for (i, config) in configs[start_idx..end_idx].iter().enumerate() {
222 let actual_index = start_idx + i;
223 let is_selected = actual_index == *selected_index;
224
225 let indicator = if is_selected {
226 format!("{} ", "→".green().bold())
227 } else {
228 " ".to_string()
229 };
230
231 let number = format!("{:>2}.", i + 1);
232 let number_display = if is_selected {
233 number.green().bold()
234 } else {
235 number.normal()
236 };
237
238 writeln!(
239 stdout,
240 "\r{}{} {}",
241 indicator,
242 number_display,
243 config.alias_name.bold()
244 )?;
245
246 if is_selected {
248 let details = format_omp_config_details(config, "\r ");
249 for detail_line in details {
250 writeln!(stdout, "{detail_line}")?;
251 }
252 }
253 writeln!(stdout)?;
254 }
255
256 writeln!(stdout)?;
258 let footer = if total_pages > 1 {
259 format!(
260 "Page {}/{} | ↑↓/j/k: Navigate | 1-9: Select | Enter: Use | e: Edit | d: Delete | n: Next | p: Prev | q: Quit",
261 current_page + 1,
262 total_pages
263 )
264 } else {
265 "↑↓/j/k: Navigate | 1-9: Select | Enter: Use | e: Edit | d: Delete | q: Quit"
266 .to_string()
267 };
268 let padded_footer = pad_text_to_width(&footer, width, TextAlignment::Center, ' ');
269 writeln!(stdout, "{}", padded_footer.white().on_bright_black())?;
270
271 stdout.flush()?;
272
273 if let Event::Key(KeyEvent {
275 code,
276 kind: KeyEventKind::Press,
277 ..
278 }) = event::read()?
279 {
280 match code {
281 KeyCode::Char('q') | KeyCode::Char('Q') => {
282 cleanup_terminal(stdout);
283 return Ok(());
284 }
285 KeyCode::Up | KeyCode::Char('k') => {
286 if *selected_index > 0 {
287 *selected_index -= 1;
288 if *selected_index < start_idx {
289 current_page = current_page.saturating_sub(1);
290 }
291 }
292 }
293 KeyCode::Down | KeyCode::Char('j') => {
294 if *selected_index < configs.len() - 1 {
295 *selected_index += 1;
296 if *selected_index >= end_idx {
297 current_page = (current_page + 1).min(total_pages - 1);
298 }
299 }
300 }
301 KeyCode::Char('n') | KeyCode::Char('N') => {
302 if current_page < total_pages - 1 {
303 current_page += 1;
304 *selected_index = current_page * page_size;
305 }
306 }
307 KeyCode::Char('p') | KeyCode::Char('P') => {
308 if current_page > 0 {
309 current_page -= 1;
310 *selected_index = current_page * page_size;
311 }
312 }
313 KeyCode::Char('d') | KeyCode::Char('D') if *selected_index < configs.len() => {
314 cleanup_terminal(stdout);
315 let config_name = configs[*selected_index].alias_name.clone();
316 println!("Delete configuration '{}'? (y/n): ", config_name);
317 let mut input = String::new();
318 io::stdin().read_line(&mut input)?;
319 if input.trim().to_lowercase() == "y" {
320 let mut storage = ConfigStorage::load()?;
321 if storage.remove_omp_configuration(&config_name) {
322 storage.save()?;
323 configs.remove(*selected_index);
324 if *selected_index >= configs.len() && !configs.is_empty() {
325 *selected_index = configs.len() - 1;
326 }
327 println!("Configuration '{}' deleted.", config_name);
328 }
329 }
330 execute!(
332 stdout,
333 terminal::EnterAlternateScreen,
334 terminal::Clear(terminal::ClearType::All)
335 )?;
336 }
337 KeyCode::Char('e') | KeyCode::Char('E') if *selected_index < configs.len() => {
338 cleanup_terminal(stdout);
339 let edit_result = handle_omp_config_edit(&configs[*selected_index]);
340 if execute!(
341 stdout,
342 terminal::EnterAlternateScreen,
343 terminal::Clear(terminal::ClearType::All)
344 )
345 .is_err()
346 {
347 return edit_result;
348 }
349 if edit_result.is_ok() {
350 if let Ok(reloaded_storage) = ConfigStorage::load()
352 && let Some(ref map) = reloaded_storage.omp_configurations
353 {
354 *configs = map.values().cloned().collect();
355 configs.sort_by(|a, b| a.alias_name.cmp(&b.alias_name));
356 }
357 }
358 }
359 KeyCode::Char(c) if c.is_ascii_digit() => {
360 let digit = c.to_digit(10).unwrap() as usize;
361 if digit >= 1 && digit <= (end_idx - start_idx) {
362 let actual_config_index = start_idx + (digit - 1);
363 cleanup_terminal(stdout);
364 return handle_omp_selection_action(configs, actual_config_index);
365 }
366 }
367 KeyCode::Enter => {
368 if *selected_index < configs.len() {
369 cleanup_terminal(stdout);
370 return handle_omp_selection_action(configs, *selected_index);
371 }
372 }
373 KeyCode::Esc => {
374 cleanup_terminal(stdout);
375 return Ok(());
376 }
377 _ => {}
378 }
379 }
380 }
381}
382
383fn handle_omp_simple_interactive_menu(configs: &[OmpConfiguration]) -> Result<()> {
385 const PAGE_SIZE: usize = 9;
386
387 if configs.len() <= PAGE_SIZE {
388 return handle_omp_simple_single_page_menu(configs);
389 }
390
391 let total_pages = configs.len().div_ceil(PAGE_SIZE);
393 let mut current_page = 0;
394
395 loop {
396 println!("\n{}", "Available OMP Configurations:".blue().bold());
397 println!("Page {}/{}", current_page + 1, total_pages);
398 println!("{}", "-".repeat(50));
399
400 let start_idx = current_page * PAGE_SIZE;
401 let end_idx = (start_idx + PAGE_SIZE).min(configs.len());
402
403 for (i, config) in configs[start_idx..end_idx].iter().enumerate() {
404 let number = start_idx + i + 1;
405 println!(
406 "{:>2}. {} ({})",
407 number,
408 config.alias_name.bold(),
409 config.auth_mode
410 );
411 }
412
413 println!(
414 "\nEnter number (1-{}), 'n' for next, 'p' for prev, or 'q' to quit: ",
415 end_idx - start_idx
416 );
417
418 let mut input = String::new();
419 io::stdin().read_line(&mut input)?;
420 let input = input.trim();
421
422 match input {
423 "q" | "Q" => return Ok(()),
424 "n" | "N" => {
425 if current_page < total_pages - 1 {
426 current_page += 1;
427 }
428 }
429 "p" | "P" => {
430 current_page = current_page.saturating_sub(1);
431 }
432 _ => {
433 if let Ok(num) = input.parse::<usize>()
434 && num >= 1
435 && num <= configs.len()
436 {
437 return handle_omp_selection_action(configs, num - 1);
438 }
439 println!("Invalid selection, please try again");
440 }
441 }
442 }
443}
444
445fn handle_omp_simple_single_page_menu(configs: &[OmpConfiguration]) -> Result<()> {
447 println!("\n{}", "Available OMP Configurations:".blue().bold());
448
449 for (index, config) in configs.iter().enumerate() {
450 println!(
451 "{:>2}. {} ({})",
452 index + 1,
453 config.alias_name.bold(),
454 config.auth_mode
455 );
456
457 let details = format_omp_config_details(config, " ");
458 for detail_line in details {
459 println!("{detail_line}");
460 }
461 println!();
462 }
463
464 println!("Enter number (1-{}), or 'q' to quit: ", configs.len());
465
466 loop {
467 let mut input = String::new();
468 io::stdin().read_line(&mut input)?;
469 let input = input.trim();
470
471 if input == "q" || input == "Q" {
472 return Ok(());
473 }
474
475 if let Ok(num) = input.parse::<usize>()
476 && num >= 1
477 && num <= configs.len()
478 {
479 return handle_omp_selection_action(configs, num - 1);
480 }
481
482 println!("Invalid selection, please try again");
483 }
484}
485
486fn handle_omp_selection_action(configs: &[OmpConfiguration], index: usize) -> Result<()> {
488 let config = &configs[index];
489 println!(
490 "\nSwitching to OMP configuration '{}' (mode: {})...",
491 config.alias_name, config.auth_mode
492 );
493
494 write_env_file(config)?;
496
497 let omp_path = resolve_npm_cli("omp");
499 let status = Command::new(omp_path).status()?;
500
501 if !status.success() {
502 eprintln!("OMP exited with non-zero status: {}", status);
503 }
504
505 Ok(())
506}
507
508fn handle_omp_config_edit(config: &OmpConfiguration) -> Result<()> {
510 println!("\n{}", "Edit OMP Configuration".bold());
511 println!("{}", "=".repeat(50));
512
513 let mut storage = ConfigStorage::load()?;
514 let mut edited_config = config.clone();
515
516 match edit_string_field("Alias name", &edited_config.alias_name, |_| Ok(())) {
518 Ok(Some(new_alias)) => {
519 edited_config.alias_name = new_alias;
520 }
521 Ok(None) => {}
522 Err(e) => {
523 if e.downcast_ref::<EditModeError>() == Some(&EditModeError::ReturnToMenu) {
524 println!("Edit cancelled.");
525 return Ok(());
526 }
527 return Err(e);
528 }
529 }
530
531 match edited_config.auth_mode.as_str() {
533 "anthropic" => {
534 if let Some(ref key) = edited_config.anthropic_api_key {
535 match edit_string_field("Anthropic API Key", key, |_| Ok(())) {
536 Ok(Some(new_key)) => {
537 edited_config.anthropic_api_key = Some(new_key);
538 }
539 Ok(None) => {}
540 Err(e) => {
541 if e.downcast_ref::<EditModeError>() == Some(&EditModeError::ReturnToMenu) {
542 println!("Edit cancelled.");
543 return Ok(());
544 }
545 return Err(e);
546 }
547 }
548 }
549 if let Some(ref token) = edited_config.anthropic_oauth_token {
550 match edit_string_field("Anthropic OAuth Token", token, |_| Ok(())) {
551 Ok(Some(new_token)) => {
552 edited_config.anthropic_oauth_token = Some(new_token);
553 }
554 Ok(None) => {}
555 Err(e) => {
556 if e.downcast_ref::<EditModeError>() == Some(&EditModeError::ReturnToMenu) {
557 println!("Edit cancelled.");
558 return Ok(());
559 }
560 return Err(e);
561 }
562 }
563 }
564 }
565 "openai" => {
566 if let Some(ref key) = edited_config.openai_api_key {
567 match edit_string_field("OpenAI API Key", key, |_| Ok(())) {
568 Ok(Some(new_key)) => {
569 edited_config.openai_api_key = Some(new_key);
570 }
571 Ok(None) => {}
572 Err(e) => {
573 if e.downcast_ref::<EditModeError>() == Some(&EditModeError::ReturnToMenu) {
574 println!("Edit cancelled.");
575 return Ok(());
576 }
577 return Err(e);
578 }
579 }
580 }
581 }
582 _ => {}
583 }
584
585 if let Some(result) =
587 edit_optional_string_field("Slow Model", edited_config.slow_model.as_deref())?
588 {
589 edited_config.slow_model = result;
590 }
591
592 if let Some(result) =
593 edit_optional_string_field("Smol Model", edited_config.smol_model.as_deref())?
594 {
595 edited_config.smol_model = result;
596 }
597
598 if let Some(result) =
599 edit_optional_string_field("Plan Model", edited_config.plan_model.as_deref())?
600 {
601 edited_config.plan_model = result;
602 }
603
604 storage.update_omp_configuration(&config.alias_name, edited_config)?;
606 storage.save()?;
607
608 println!("\n{}", "Configuration updated successfully!".green().bold());
609 Ok(())
610}