Skip to main content

cc_switch/interactive/
interactive.rs

1use crate::cli::display_utils::{
2    TextAlignment, format_token_for_display, get_terminal_width, pad_text_to_width,
3    text_display_width,
4};
5use crate::config::EnvironmentConfig;
6use crate::config::types::{ConfigStorage, Configuration};
7use anyhow::{Context, Result};
8use colored::*;
9use crossterm::{
10    event::{self, Event, KeyCode, KeyEvent, KeyEventKind},
11    execute, terminal,
12};
13use std::io::{self, Write};
14use std::process::Command;
15
16/// Calculate display width of a character
17/// Returns 2 for wide characters (CJK), 1 for others
18fn char_display_width(c: char) -> usize {
19    match c as u32 {
20        0x00..=0x7F => 1,
21        0x80..=0x2FF => 1,
22        0x2190..=0x21FF => 2,
23        0x3000..=0x303F => 2,
24        0x3040..=0x309F => 2,
25        0x30A0..=0x30FF => 2,
26        0x4E00..=0x9FFF => 2,
27        0xAC00..=0xD7AF => 2,
28        0x3400..=0x4DBF => 2,
29        0xFF01..=0xFF60 => 2,
30        _ => 1,
31    }
32}
33
34/// Truncate text to fit within available width, considering character display width
35fn truncate_text_to_width(text: &str, available_width: usize) -> (String, usize) {
36    let mut current_width = 0;
37    let truncated: String = text
38        .chars()
39        .take_while(|&c| {
40            let char_width = char_display_width(c);
41            if current_width + char_width <= available_width {
42                current_width += char_width;
43                true
44            } else {
45                false
46            }
47        })
48        .collect();
49    let truncated_width = text_display_width(&truncated);
50    (truncated, truncated_width)
51}
52
53/// Clean up terminal state by leaving alternate screen and disabling raw mode
54fn cleanup_terminal(stdout: &mut io::Stdout) {
55    let _ = execute!(stdout, terminal::LeaveAlternateScreen);
56    let _ = terminal::disable_raw_mode();
57}
58
59/// Border drawing utilities for terminal compatibility
60struct BorderDrawing {
61    /// Check if terminal supports Unicode box drawing characters
62    pub unicode_supported: bool,
63}
64
65impl BorderDrawing {
66    /// Create new border drawing utility
67    fn new() -> Self {
68        let unicode_supported = Self::detect_unicode_support();
69        Self { unicode_supported }
70    }
71
72    /// Detect if terminal supports Unicode characters
73    fn detect_unicode_support() -> bool {
74        // Check environment variables that indicate Unicode support
75        if let Ok(term) = std::env::var("TERM") {
76            // Modern terminals that support Unicode
77            if term.contains("xterm") || term.contains("screen") || term == "tmux-256color" {
78                return true;
79            }
80        }
81
82        // Check locale settings
83        if let Ok(lang) = std::env::var("LANG")
84            && (lang.contains("UTF-8") || lang.contains("utf8"))
85        {
86            return true;
87        }
88
89        // Conservative fallback - assume Unicode is supported for better UX
90        // If issues arise, ASCII fallback will be manually triggered
91        true
92    }
93
94    /// Draw top border with title
95    fn draw_top_border(&self, title: &str, width: usize) -> String {
96        if self.unicode_supported {
97            let title_padded = format!(" {title} ");
98            let title_len = text_display_width(&title_padded);
99
100            if title_len >= width.saturating_sub(2) {
101                // Title too long, use simple border
102                format!("╔{}╗", "═".repeat(width.saturating_sub(2)))
103            } else {
104                let inner_width = width.saturating_sub(2); // Total width minus borders
105                let padding_total = inner_width.saturating_sub(title_len);
106                let padding_left = padding_total / 2;
107                let padding_right = padding_total - padding_left;
108                format!(
109                    "╔{}{}{}╗",
110                    "═".repeat(padding_left),
111                    title_padded,
112                    "═".repeat(padding_right)
113                )
114            }
115        } else {
116            // ASCII fallback
117            let title_padded = format!(" {title} ");
118            let title_len = title_padded.len();
119
120            if title_len >= width.saturating_sub(2) {
121                format!("+{}+", "-".repeat(width.saturating_sub(2)))
122            } else {
123                let inner_width = width.saturating_sub(2);
124                let padding_total = inner_width.saturating_sub(title_len);
125                let padding_left = padding_total / 2;
126                let padding_right = padding_total - padding_left;
127                format!(
128                    "+{}{}{}+",
129                    "-".repeat(padding_left),
130                    title_padded,
131                    "-".repeat(padding_right)
132                )
133            }
134        }
135    }
136
137    /// Draw middle border line with text
138    fn draw_middle_line(&self, text: &str, width: usize) -> String {
139        let text_len = text_display_width(text);
140        // Account for borders: "║ " (1+1) + " ║" (1+1) = 4 characters
141        let available_width = width.saturating_sub(4);
142
143        let (left_border, right_border) = if self.unicode_supported {
144            ("║", "║")
145        } else {
146            ("|", "|")
147        };
148
149        if text_len > available_width {
150            // Truncate text to fit within available width, considering display width
151            let (truncated, truncated_width) = truncate_text_to_width(text, available_width);
152            let padding_spaces = available_width.saturating_sub(truncated_width);
153            format!(
154                "{left_border} {}{} {right_border}",
155                truncated,
156                " ".repeat(padding_spaces)
157            )
158        } else {
159            let padded_text = pad_text_to_width(text, available_width, TextAlignment::Left, ' ');
160            format!("{left_border} {padded_text} {right_border}")
161        }
162    }
163
164    /// Draw bottom border
165    fn draw_bottom_border(&self, width: usize) -> String {
166        if self.unicode_supported {
167            format!("╚{}╝", "═".repeat(width - 2))
168        } else {
169            format!("+{}+", "-".repeat(width - 2))
170        }
171    }
172}
173
174/// Handle interactive current command
175///
176/// Provides interactive menu for:
177/// 1. Execute claude --dangerously-skip-permissions
178/// 2. Switch configuration (lists available aliases)
179/// 3. Exit
180///
181/// # Errors
182/// Returns error if file operations fail or user input fails
183pub fn handle_current_command() -> Result<()> {
184    let storage = ConfigStorage::load()?;
185
186    println!("\n{}", "Current Configuration:".green().bold());
187    println!("Environment variable mode: configurations are set per-command execution");
188    println!("Select a configuration from the menu below to launch Claude");
189    println!("Select 'cc' to launch Claude with default settings");
190
191    // Try to enable interactive menu with keyboard navigation
192    let raw_mode_enabled = terminal::enable_raw_mode().is_ok();
193
194    if raw_mode_enabled {
195        let mut stdout = io::stdout();
196        if execute!(
197            stdout,
198            terminal::EnterAlternateScreen,
199            terminal::Clear(terminal::ClearType::All)
200        )
201        .is_ok()
202        {
203            // Full interactive mode with arrow keys for main menu
204            let result = handle_main_menu_interactive(&mut stdout, &storage);
205
206            // Always restore terminal
207            let _ = execute!(stdout, terminal::LeaveAlternateScreen);
208            let _ = terminal::disable_raw_mode();
209
210            return result;
211        } else {
212            // Fallback to simple mode
213            let _ = terminal::disable_raw_mode();
214        }
215    }
216
217    // Fallback to simple numbered menu
218    handle_main_menu_simple(&storage)
219}
220
221/// Handle main menu with keyboard navigation
222fn handle_main_menu_interactive(stdout: &mut io::Stdout, storage: &ConfigStorage) -> Result<()> {
223    let menu_items = [
224        "Execute claude --dangerously-skip-permissions",
225        "Switch configuration",
226        "Exit",
227    ];
228    let mut selected_index = 0;
229
230    loop {
231        // Clear screen and redraw
232        execute!(stdout, terminal::Clear(terminal::ClearType::All))?;
233        execute!(stdout, crossterm::cursor::MoveTo(0, 0))?;
234
235        // Header - use BorderDrawing for compatibility
236        let border = BorderDrawing::new();
237        const MAIN_MENU_WIDTH: usize = 68;
238
239        println!(
240            "\r{}",
241            border.draw_top_border("Main Menu", MAIN_MENU_WIDTH).green()
242        );
243        println!(
244            "\r{}",
245            border
246                .draw_middle_line(
247                    "↑↓/jk导航,1-9快选,E-编辑,R-官方,Q-退出,Enter确认,Esc取消",
248                    MAIN_MENU_WIDTH
249                )
250                .green()
251        );
252        println!("\r{}", border.draw_bottom_border(MAIN_MENU_WIDTH).green());
253        println!();
254
255        // Draw menu items
256        for (index, item) in menu_items.iter().enumerate() {
257            if index == selected_index {
258                println!("\r> {} {}", "●".blue().bold(), item.blue().bold());
259            } else {
260                println!("\r  {} {}", "○".dimmed(), item.dimmed());
261            }
262        }
263
264        // Ensure output is flushed
265        stdout.flush()?;
266
267        // Handle input with error recovery
268        let event = match event::read() {
269            Ok(event) => event,
270            Err(e) => {
271                // Clean up terminal state on input error
272                cleanup_terminal(stdout);
273                return Err(e.into());
274            }
275        };
276
277        match event {
278            Event::Key(KeyEvent {
279                code,
280                kind: KeyEventKind::Press,
281                ..
282            }) => {
283                match code {
284                    KeyCode::Up => {
285                        selected_index = selected_index.saturating_sub(1);
286                    }
287                    KeyCode::Down => {
288                        if selected_index < menu_items.len() - 1 {
289                            selected_index += 1;
290                        }
291                    }
292                    KeyCode::Enter => {
293                        // Execute terminal cleanup here
294                        cleanup_terminal(stdout);
295
296                        return handle_main_menu_action(selected_index, storage);
297                    }
298                    KeyCode::Esc => {
299                        // Clean up terminal before exit
300                        cleanup_terminal(stdout);
301
302                        println!("\nExiting...");
303                        return Ok(());
304                    }
305                    _ => {}
306                }
307            }
308            Event::Key(_) => {} // Ignore key release events
309            _ => {}
310        }
311    }
312}
313
314/// Handle main menu simple fallback
315fn handle_main_menu_simple(storage: &ConfigStorage) -> Result<()> {
316    loop {
317        println!("\n{}", "Available Actions:".blue().bold());
318        println!("1. Execute claude --dangerously-skip-permissions");
319        println!("2. Switch configuration");
320        println!("3. Exit");
321
322        print!("\nPlease select an option (1-3): ");
323        io::stdout().flush().context("Failed to flush stdout")?;
324
325        let mut input = String::new();
326        io::stdin()
327            .read_line(&mut input)
328            .context("Failed to read input")?;
329
330        let choice = input.trim();
331
332        match choice {
333            "1" => return handle_main_menu_action(0, storage),
334            "2" => return handle_main_menu_action(1, storage),
335            "3" => return handle_main_menu_action(2, storage),
336            _ => {
337                println!("Invalid option. Please select 1-3.");
338            }
339        }
340    }
341}
342
343/// Handle main menu action based on selected index
344fn handle_main_menu_action(selected_index: usize, storage: &ConfigStorage) -> Result<()> {
345    match selected_index {
346        0 => {
347            println!("\nExecuting: claude --dangerously-skip-permissions");
348            execute_claude_command(true)?;
349        }
350        1 => {
351            // Use the interactive selection instead of simple menu
352            handle_interactive_selection(storage)?;
353        }
354        2 => {
355            println!("Exiting...");
356        }
357        _ => {
358            println!("Invalid selection");
359        }
360    }
361    Ok(())
362}
363
364/// Handle interactive configuration selection with real-time preview
365///
366/// # Arguments
367/// * `storage` - Reference to configuration storage
368///
369/// # Errors
370/// Returns error if terminal operations fail or user selection fails
371pub fn handle_interactive_selection(storage: &ConfigStorage) -> Result<()> {
372    if storage.configurations.is_empty() {
373        println!("No configurations available. Use 'add' command to create configurations first.");
374        return Ok(());
375    }
376
377    let mut configs: Vec<Configuration> = storage.configurations.values().cloned().collect();
378    configs.sort_by(|a, b| a.alias_name.cmp(&b.alias_name));
379
380    let mut selected_index = 0;
381
382    // Try to enable raw mode, fallback to simple menu if it fails
383    let raw_mode_enabled = terminal::enable_raw_mode().is_ok();
384
385    if raw_mode_enabled {
386        let mut stdout = io::stdout();
387        if execute!(
388            stdout,
389            terminal::EnterAlternateScreen,
390            terminal::Clear(terminal::ClearType::All)
391        )
392        .is_ok()
393        {
394            // Full interactive mode with arrow keys
395            let storage_mode = storage.default_storage_mode.clone().unwrap_or_default();
396            let result = handle_full_interactive_menu(
397                &mut stdout,
398                &mut configs,
399                &mut selected_index,
400                storage,
401                storage_mode,
402            );
403
404            // Always restore terminal
405            let _ = execute!(stdout, terminal::LeaveAlternateScreen);
406            let _ = terminal::disable_raw_mode();
407
408            return result;
409        } else {
410            // Fallback to simple mode
411            let _ = terminal::disable_raw_mode();
412        }
413    }
414
415    // Fallback to simple numbered menu
416    handle_simple_interactive_menu(&configs.iter().collect::<Vec<_>>(), storage)
417}
418
419/// Handle full interactive menu with arrow key navigation and pagination
420fn handle_full_interactive_menu(
421    stdout: &mut io::Stdout,
422    configs: &mut Vec<Configuration>,
423    selected_index: &mut usize,
424    storage: &ConfigStorage,
425    storage_mode: crate::config::types::StorageMode,
426) -> Result<()> {
427    // Handle empty configuration list
428    if configs.is_empty() {
429        println!("\r{}", "No configurations available".yellow());
430        println!(
431            "\r{}",
432            "Use 'cc-switch add <alias> <token> <url>' to add configurations first.".dimmed()
433        );
434        println!("\r{}", "Press any key to continue...".dimmed());
435        let _ = event::read(); // Wait for user input
436        return Ok(());
437    }
438
439    const PAGE_SIZE: usize = 9; // Maximum 9 configs per page
440
441    // Calculate pagination info
442    let total_pages = if configs.len() <= PAGE_SIZE {
443        1
444    } else {
445        configs.len().div_ceil(PAGE_SIZE)
446    };
447    let mut current_page = 0;
448
449    loop {
450        // Calculate current page config range
451        let start_idx = current_page * PAGE_SIZE;
452        let end_idx = std::cmp::min(start_idx + PAGE_SIZE, configs.len());
453        let page_configs = &configs[start_idx..end_idx];
454
455        // Clear screen and redraw
456        execute!(stdout, terminal::Clear(terminal::ClearType::All))?;
457        execute!(stdout, crossterm::cursor::MoveTo(0, 0))?;
458
459        // Header with pagination info - use BorderDrawing for compatibility
460        let border = BorderDrawing::new();
461        // Width needs to accommodate: ║ (1) + space (1) + text (76) + space (1) + ║ (1) = 80
462        // Text width includes arrows (↑↓) and Chinese characters counted as 2 columns each
463        const CONFIG_MENU_WIDTH: usize = 80;
464
465        println!(
466            "\r{}",
467            border
468                .draw_top_border("Select Configuration", CONFIG_MENU_WIDTH)
469                .green()
470        );
471        if total_pages > 1 {
472            println!(
473                "\r{}",
474                border
475                    .draw_middle_line(
476                        &format!("第 {} 页,共 {} 页", current_page + 1, total_pages),
477                        CONFIG_MENU_WIDTH
478                    )
479                    .green()
480            );
481            println!(
482                "\r{}",
483                border
484                    .draw_middle_line(
485                        "↑↓/jk导航,1-9快选,E-编辑,N/P翻页,R-官方,Q-退出,Enter确认",
486                        CONFIG_MENU_WIDTH
487                    )
488                    .green()
489            );
490        } else {
491            println!(
492                "\r{}",
493                border
494                    .draw_middle_line(
495                        "↑↓/jk导航,1-9快选,E-编辑,R-官方,Q-退出,Enter确认,Esc取消",
496                        CONFIG_MENU_WIDTH
497                    )
498                    .green()
499            );
500        }
501        println!("\r{}", border.draw_bottom_border(CONFIG_MENU_WIDTH).green());
502        println!();
503
504        // Add official option (always visible, always red)
505        let official_index = 0;
506        if *selected_index == official_index {
507            println!(
508                "\r> {} {} {}",
509                "●".red().bold(),
510                "[R]".red().bold(),
511                "official".red().bold()
512            );
513            println!("\r    Use official Claude API (no custom configuration)");
514            println!();
515        } else {
516            println!("\r  {} {} {}", "○".red(), "[R]".red(), "official".red());
517        }
518
519        // Draw current page configs with proper numbering
520        for (page_index, config) in page_configs.iter().enumerate() {
521            let actual_config_index = start_idx + page_index;
522            let display_number = page_index + 1; // Numbers 1-9 for current page
523            let actual_index = actual_config_index + 1; // +1 because official is at index 0
524            let number_label = format!("[{display_number}]");
525
526            if *selected_index == actual_index {
527                println!(
528                    "\r> {} {} {}",
529                    "●".blue().bold(),
530                    number_label.blue().bold(),
531                    config.alias_name.blue().bold()
532                );
533
534                // Show details with improved formatting and alignment
535                let details = format_config_details(config, "\r    ", false);
536                for detail_line in details {
537                    println!("{detail_line}");
538                }
539                println!();
540            } else {
541                println!(
542                    "\r  {} {} {}",
543                    "○".dimmed(),
544                    number_label.dimmed(),
545                    config.alias_name.dimmed()
546                );
547            }
548        }
549
550        // Add exit option (always visible)
551        let exit_index = configs.len() + 1;
552        if *selected_index == exit_index {
553            println!(
554                "\r> {} {} {}",
555                "●".yellow().bold(),
556                "[Q]".yellow().bold(),
557                "Exit".yellow().bold()
558            );
559            println!("\r    Exit without making changes");
560            println!();
561        } else {
562            println!(
563                "\r  {} {} {}",
564                "○".dimmed(),
565                "[Q]".dimmed(),
566                "Exit".dimmed()
567            );
568        }
569
570        // Show pagination help if needed
571        if total_pages > 1 {
572            println!(
573                "\r{}",
574                format!(
575                    "Page Navigation: [N]ext, [P]revious (第 {} 页,共 {} 页)",
576                    current_page + 1,
577                    total_pages
578                )
579                .dimmed()
580            );
581        }
582
583        // Ensure output is flushed
584        stdout.flush()?;
585
586        // Handle input with error recovery
587        let event = match event::read() {
588            Ok(event) => event,
589            Err(e) => {
590                // Clean up terminal state on input error
591                cleanup_terminal(stdout);
592                return Err(e.into());
593            }
594        };
595
596        match event {
597            Event::Key(KeyEvent {
598                code,
599                kind: KeyEventKind::Press,
600                ..
601            }) => match code {
602                KeyCode::Up | KeyCode::Char('k') | KeyCode::Char('K') => {
603                    *selected_index = selected_index.saturating_sub(1);
604                }
605                KeyCode::Down | KeyCode::Char('j') | KeyCode::Char('J') => {
606                    if *selected_index < configs.len() + 1 {
607                        *selected_index += 1;
608                    }
609                }
610                KeyCode::PageDown | KeyCode::Char('n') | KeyCode::Char('N') => {
611                    if total_pages > 1 && current_page < total_pages - 1 {
612                        current_page += 1;
613                        // Reset selection to first item of new page
614                        let new_page_start_idx = current_page * PAGE_SIZE;
615                        *selected_index = new_page_start_idx + 1; // +1 because official is at index 0
616                    }
617                }
618                KeyCode::PageUp | KeyCode::Char('p') | KeyCode::Char('P') => {
619                    if total_pages > 1 && current_page > 0 {
620                        current_page -= 1;
621                        // Reset selection to first item of new page
622                        let new_page_start_idx = current_page * PAGE_SIZE;
623                        *selected_index = new_page_start_idx + 1; // +1 because official is at index 0
624                    }
625                }
626                KeyCode::Enter => {
627                    // Clean up terminal before processing selection
628                    cleanup_terminal(stdout);
629
630                    return handle_selection_action(
631                        &configs.iter().collect::<Vec<_>>(),
632                        *selected_index,
633                        storage,
634                        storage_mode,
635                    );
636                }
637                KeyCode::Esc => {
638                    // Clean up terminal before exit
639                    cleanup_terminal(stdout);
640
641                    println!("\nSelection cancelled");
642                    return Ok(());
643                }
644                KeyCode::Char(c) if c.is_ascii_digit() => {
645                    let digit = c.to_digit(10).unwrap() as usize;
646                    // Map digit to current page config
647                    if digit >= 1 && digit <= page_configs.len() {
648                        let actual_config_index = start_idx + (digit - 1);
649                        let selection_index = actual_config_index + 1; // +1 because official is at index 0
650
651                        // Clean up terminal before processing selection
652                        cleanup_terminal(stdout);
653
654                        return handle_selection_action(
655                            &configs.iter().collect::<Vec<_>>(),
656                            selection_index,
657                            storage,
658                            storage_mode,
659                        );
660                    }
661                    // Invalid digit - ignore silently
662                }
663                KeyCode::Char('r') | KeyCode::Char('R') => {
664                    // Clean up terminal before processing selection
665                    cleanup_terminal(stdout);
666
667                    return handle_selection_action(
668                        &configs.iter().collect::<Vec<_>>(),
669                        0,
670                        storage,
671                        storage_mode,
672                    );
673                }
674                KeyCode::Char('e') | KeyCode::Char('E') => {
675                    // Only allow editing if a config is selected (not official or exit)
676                    if *selected_index > 0 && *selected_index <= configs.len() {
677                        // Clean up terminal before entering edit mode
678                        cleanup_terminal(stdout);
679
680                        let config_index = *selected_index - 1; // -1 because official is at index 0
681
682                        // Try to edit the configuration
683                        let edit_result = handle_config_edit(&configs[config_index]);
684
685                        // Re-enter alternate screen and raw mode before continuing
686                        if execute!(
687                            stdout,
688                            terminal::EnterAlternateScreen,
689                            terminal::Clear(terminal::ClearType::All)
690                        )
691                        .is_ok()
692                            && terminal::enable_raw_mode().is_ok()
693                        {
694                            // Check if edit was successful (saved) or if user cancelled
695                            match edit_result {
696                                Ok(_) => {
697                                    // Configuration was saved successfully, reload configs
698                                    if let Ok(reloaded_storage) = ConfigStorage::load() {
699                                        *configs = reloaded_storage
700                                            .configurations
701                                            .values()
702                                            .cloned()
703                                            .collect();
704                                        configs.sort_by(|a, b| a.alias_name.cmp(&b.alias_name));
705                                        // Keep selection within bounds
706                                        if *selected_index > configs.len() + 1 {
707                                            *selected_index = configs.len() + 1;
708                                        }
709                                    }
710                                    // Continue the loop to display updated configs
711                                    continue;
712                                }
713                                Err(e) => {
714                                    // Check if this is a "return to menu" error (user cancelled)
715                                    if e.downcast_ref::<EditModeError>()
716                                        == Some(&EditModeError::ReturnToMenu)
717                                    {
718                                        // User cancelled edit, just continue the loop
719                                        continue;
720                                    }
721                                    // For other errors, propagate them up
722                                    cleanup_terminal(stdout);
723                                    return Err(e);
724                                }
725                            }
726                        }
727                    }
728                    // Invalid selection - ignore silently
729                }
730                KeyCode::Char('q') | KeyCode::Char('Q') => {
731                    // Clean up terminal before processing selection
732                    cleanup_terminal(stdout);
733
734                    return handle_selection_action(
735                        &configs.iter().collect::<Vec<_>>(),
736                        configs.len() + 1,
737                        storage,
738                        storage_mode,
739                    );
740                }
741                _ => {}
742            },
743            Event::Key(_) => {} // Ignore key release events
744            _ => {}
745        }
746    }
747}
748
749/// Handle simple interactive menu (fallback)
750fn handle_simple_interactive_menu(
751    configs: &[&Configuration],
752    storage: &ConfigStorage,
753) -> Result<()> {
754    const PAGE_SIZE: usize = 9; // Same page size as full interactive menu
755
756    // If configs fit in one page, show the simple original menu
757    if configs.len() <= PAGE_SIZE {
758        return handle_simple_single_page_menu(configs, storage);
759    }
760
761    // Multi-page simple menu
762    let total_pages = configs.len().div_ceil(PAGE_SIZE);
763    let mut current_page = 0;
764
765    loop {
766        // Calculate current page config range
767        let start_idx = current_page * PAGE_SIZE;
768        let end_idx = std::cmp::min(start_idx + PAGE_SIZE, configs.len());
769        let page_configs = &configs[start_idx..end_idx];
770
771        println!("\n{}", "Available Configurations:".blue().bold());
772        if total_pages > 1 {
773            println!("第 {} 页,共 {} 页", current_page + 1, total_pages);
774            println!("使用 'n' 下一页, 'p' 上一页, 'r' 官方配置, 'q' 退出");
775        }
776        println!();
777
778        // Add official option (always available)
779        println!("{} {}", "[r]".red().bold(), "official".red());
780        println!("   Use official Claude API (no custom configuration)");
781        println!();
782
783        // Show current page configs with improved formatting
784        for (page_index, config) in page_configs.iter().enumerate() {
785            let display_number = page_index + 1;
786
787            println!(
788                "{}. {}",
789                format!("[{display_number}]").green().bold(),
790                config.alias_name.green()
791            );
792
793            // Show config details with consistent formatting
794            let details = format_config_details(config, "   ", true);
795            for detail_line in details {
796                println!("{detail_line}");
797            }
798            println!();
799        }
800
801        // Exit option
802        println!("{} {}", "[q]".yellow().bold(), "Exit".yellow());
803
804        if total_pages > 1 {
805            println!(
806                "\n页面导航: [n]下页, [p]上页 | 配置选择: [1-{}] | [e]编辑 | [r]官方 | [q]退出",
807                page_configs.len()
808            );
809        }
810
811        print!("\n请输入选择: ");
812        io::stdout().flush()?;
813
814        let mut input = String::new();
815        io::stdin().read_line(&mut input)?;
816        let choice = input.trim().to_lowercase();
817
818        match choice.as_str() {
819            "r" => {
820                // Official option
821                println!("Using official Claude configuration");
822
823                // Update settings.json to remove Anthropic configuration
824                let mut settings = crate::config::types::ClaudeSettings::load(
825                    storage.get_claude_settings_dir().map(|s| s.as_str()),
826                )?;
827                settings.remove_anthropic_env();
828                settings.save(storage.get_claude_settings_dir().map(|s| s.as_str()))?;
829
830                return launch_claude_with_env(EnvironmentConfig::empty(), None, None, false);
831            }
832            "e" => {
833                // Edit functionality for simple menu
834                // In simple menu, we don't have a selected config, so we can't edit
835                println!("编辑功能在交互式菜单中可用");
836            }
837            "q" => {
838                println!("Exiting...");
839                return Ok(());
840            }
841            "n" if total_pages > 1 && current_page < total_pages - 1 => {
842                current_page += 1;
843                continue;
844            }
845            "p" if total_pages > 1 && current_page > 0 => {
846                current_page -= 1;
847                continue;
848            }
849            digit_str => {
850                if let Ok(digit) = digit_str.parse::<usize>()
851                    && digit >= 1
852                    && digit <= page_configs.len()
853                {
854                    let actual_config_index = start_idx + (digit - 1);
855                    let selection_index = actual_config_index + 1; // +1 because official is at index 0
856                    let storage_mode = storage.default_storage_mode.clone().unwrap_or_default();
857                    return handle_selection_action(
858                        configs,
859                        selection_index,
860                        storage,
861                        storage_mode,
862                    );
863                }
864                println!("无效选择,请重新输入");
865            }
866        }
867    }
868}
869
870/// Handle simple single page menu (original behavior for ≤9 configs)
871fn handle_simple_single_page_menu(
872    configs: &[&Configuration],
873    storage: &ConfigStorage,
874) -> Result<()> {
875    println!("\n{}", "Available Configurations:".blue().bold());
876
877    // Add official option (first)
878    println!("1. {}", "official".red());
879    println!("   Use official Claude API (no custom configuration)");
880    println!();
881
882    for (index, config) in configs.iter().enumerate() {
883        println!(
884            "{}. {}",
885            index + 2, // +2 because official is at position 1
886            config.alias_name.green()
887        );
888
889        // Show config details with consistent formatting
890        let details = format_config_details(config, "   ", true);
891        for detail_line in details {
892            println!("{detail_line}");
893        }
894        println!();
895    }
896
897    println!("{}. {}", configs.len() + 2, "Exit".yellow());
898
899    print!("\nSelect configuration (1-{}): ", configs.len() + 2);
900    io::stdout().flush()?;
901
902    let mut input = String::new();
903    io::stdin().read_line(&mut input)?;
904
905    match input.trim().parse::<usize>() {
906        Ok(1) => {
907            // Official option
908            println!("Using official Claude configuration");
909
910            // Update settings.json to remove Anthropic configuration
911            let mut settings = crate::config::types::ClaudeSettings::load(
912                storage.get_claude_settings_dir().map(|s| s.as_str()),
913            )?;
914            settings.remove_anthropic_env();
915            settings.save(storage.get_claude_settings_dir().map(|s| s.as_str()))?;
916
917            launch_claude_with_env(EnvironmentConfig::empty(), None, None, false)
918        }
919        Ok(num) if num >= 2 && num <= configs.len() + 1 => {
920            let storage_mode = storage.default_storage_mode.clone().unwrap_or_default();
921            handle_selection_action(configs, num - 1, storage, storage_mode) // -1 to account for official option at index 0
922        }
923        Ok(num) if num == configs.len() + 2 => {
924            println!("Exiting...");
925            Ok(())
926        }
927        _ => {
928            println!("Invalid selection");
929            Ok(())
930        }
931    }
932}
933
934/// Handle the actual selection and configuration switch
935fn handle_selection_action(
936    configs: &[&Configuration],
937    selected_index: usize,
938    storage: &ConfigStorage,
939    storage_mode: crate::config::types::StorageMode,
940) -> Result<()> {
941    if selected_index == 0 {
942        // Official option (reset to default)
943        println!("\nUsing official Claude configuration");
944
945        // Update settings.json to remove Anthropic configuration
946        let mut settings = crate::config::types::ClaudeSettings::load(
947            storage.get_claude_settings_dir().map(|s| s.as_str()),
948        )?;
949        settings.remove_anthropic_env();
950        settings.save(storage.get_claude_settings_dir().map(|s| s.as_str()))?;
951
952        launch_claude_with_env(EnvironmentConfig::empty(), None, None, false)
953    } else if selected_index <= configs.len() {
954        // Switch to selected configuration
955        let config_index = selected_index - 1; // -1 because official is at index 0
956        let selected_config = configs[config_index].clone();
957        let env_config = EnvironmentConfig::from_config(&selected_config);
958
959        println!(
960            "\nSwitched to configuration '{}'",
961            selected_config.alias_name.green().bold()
962        );
963
964        // Show selected configuration details with consistent formatting
965        let details = format_config_details(&selected_config, "", false);
966        for detail_line in details {
967            println!("{detail_line}");
968        }
969
970        // Update settings.json with the configuration
971        let mut settings = crate::config::types::ClaudeSettings::load(
972            storage.get_claude_settings_dir().map(|s| s.as_str()),
973        )?;
974        settings.switch_to_config_with_mode(
975            &selected_config,
976            storage_mode,
977            storage.get_claude_settings_dir().map(|s| s.as_str()),
978        )?;
979
980        launch_claude_with_env(env_config, None, None, false)
981    } else {
982        // Exit
983        println!("\nExiting...");
984        Ok(())
985    }
986}
987
988/// Launch Claude CLI with environment variables and exec to replace current process
989pub fn launch_claude_with_env(
990    env_config: EnvironmentConfig,
991    prompt: Option<&str>,
992    resume: Option<&str>,
993    continue_session: bool,
994) -> Result<()> {
995    println!("\nLaunching Claude CLI...");
996
997    // Set environment variables for current process
998    for (key, value) in env_config.as_env_tuples() {
999        unsafe {
1000            std::env::set_var(&key, &value);
1001        }
1002    }
1003
1004    // On Unix systems, use exec to replace current process
1005    #[cfg(unix)]
1006    {
1007        use std::os::unix::process::CommandExt;
1008        let mut command = Command::new("claude");
1009        command.arg("--dangerously-skip-permissions");
1010        if let Some(session_id) = resume {
1011            command.args(["--resume", session_id]);
1012        }
1013        if continue_session {
1014            command.arg("--continue");
1015        }
1016        if let Some(p) = prompt {
1017            command.arg(p);
1018        }
1019        let error = command.exec();
1020        // exec never returns on success, so if we get here, it failed
1021        anyhow::bail!("Failed to exec claude: {}", error);
1022    }
1023
1024    // On non-Unix systems, fallback to spawn and wait
1025    #[cfg(not(unix))]
1026    {
1027        use std::process::Stdio;
1028        let mut command = Command::new("claude");
1029        command.arg("--dangerously-skip-permissions");
1030        if let Some(session_id) = resume {
1031            command.args(["--resume", session_id]);
1032        }
1033        if continue_session {
1034            command.arg("--continue");
1035        }
1036        if let Some(p) = prompt {
1037            command.arg(p);
1038        }
1039        command
1040            .stdin(Stdio::inherit())
1041            .stdout(Stdio::inherit())
1042            .stderr(Stdio::inherit());
1043
1044        let mut child = command.spawn().context(
1045            "Failed to launch Claude CLI. Make sure 'claude' command is available in PATH",
1046        )?;
1047
1048        let status = child.wait()?;
1049
1050        if !status.success() {
1051            anyhow::bail!("Claude CLI exited with error status: {}", status);
1052        }
1053    }
1054}
1055
1056/// Execute claude command with or without --dangerously-skip-permissions using exec
1057///
1058/// # Arguments
1059/// * `skip_permissions` - Whether to add --dangerously-skip-permissions flag
1060fn execute_claude_command(skip_permissions: bool) -> Result<()> {
1061    println!("Launching Claude CLI...");
1062
1063    // On Unix systems, use exec to replace current process
1064    #[cfg(unix)]
1065    {
1066        use std::os::unix::process::CommandExt;
1067        let mut command = Command::new("claude");
1068        if skip_permissions {
1069            command.arg("--dangerously-skip-permissions");
1070        }
1071
1072        let error = command.exec();
1073        // exec never returns on success, so if we get here, it failed
1074        anyhow::bail!("Failed to exec claude: {}", error);
1075    }
1076
1077    // On non-Unix systems, fallback to spawn and wait
1078    #[cfg(not(unix))]
1079    {
1080        use std::process::Stdio;
1081        let mut command = Command::new("claude");
1082        if skip_permissions {
1083            command.arg("--dangerously-skip-permissions");
1084        }
1085
1086        command
1087            .stdin(Stdio::inherit())
1088            .stdout(Stdio::inherit())
1089            .stderr(Stdio::inherit());
1090
1091        let mut child = command.spawn().context(
1092            "Failed to launch Claude CLI. Make sure 'claude' command is available in PATH",
1093        )?;
1094
1095        let status = child
1096            .wait()
1097            .context("Failed to wait for Claude CLI process")?;
1098
1099        if !status.success() {
1100            anyhow::bail!("Claude CLI exited with error status: {}", status);
1101        }
1102    }
1103}
1104
1105/// Read input from stdin with a prompt
1106///
1107/// # Arguments
1108/// * `prompt` - The prompt to display to the user
1109///
1110/// # Returns
1111/// The user's input as a String
1112pub fn read_input(prompt: &str) -> Result<String> {
1113    print!("{prompt}");
1114    io::stdout().flush().context("Failed to flush stdout")?;
1115    let mut input = String::new();
1116    io::stdin()
1117        .read_line(&mut input)
1118        .context("Failed to read input")?;
1119    Ok(input.trim().to_string())
1120}
1121
1122/// Read sensitive input (token) with a prompt (without echoing)
1123///
1124/// # Arguments
1125/// * `prompt` - The prompt to display to the user
1126///
1127/// # Returns
1128/// The user's input as a String
1129pub fn read_sensitive_input(prompt: &str) -> Result<String> {
1130    print!("{prompt}");
1131    io::stdout().flush().context("Failed to flush stdout")?;
1132    let mut input = String::new();
1133    io::stdin()
1134        .read_line(&mut input)
1135        .context("Failed to read input")?;
1136    Ok(input.trim().to_string())
1137}
1138
1139/// Format configuration details with consistent indentation and alignment
1140///
1141/// This function provides unified formatting for configuration display across
1142/// all interactive menus, ensuring consistent visual presentation.
1143///
1144/// # Arguments
1145/// * `config` - The configuration to format
1146/// * `indent` - Base indentation string (e.g., "    " or "   ")
1147/// * `compact` - Whether to use compact formatting (single line where possible)
1148///
1149/// # Returns  
1150/// Vector of formatted lines for configuration display
1151fn format_config_details(config: &Configuration, indent: &str, _compact: bool) -> Vec<String> {
1152    let mut lines = Vec::new();
1153
1154    // Calculate optimal field width for alignment
1155    let terminal_width = get_terminal_width();
1156    let _available_width = terminal_width.saturating_sub(text_display_width(indent) + 8);
1157
1158    // Field labels with consistent width for alignment
1159    let token_label = "Token:";
1160    let url_label = "URL:";
1161    let model_label = "Model:";
1162    let small_model_label = "Small Fast Model:";
1163    let max_thinking_tokens_label = "Max Thinking Tokens:";
1164    let api_timeout_ms_label = "API Timeout (ms):";
1165    let disable_nonessential_traffic_label = "Disable Nonessential Traffic:";
1166    let default_sonnet_model_label = "Default Sonnet Model:";
1167    let default_opus_model_label = "Default Opus Model:";
1168    let default_haiku_model_label = "Default Haiku Model:";
1169
1170    // Find the widest label for alignment
1171    let max_label_width = [
1172        token_label,
1173        url_label,
1174        model_label,
1175        small_model_label,
1176        max_thinking_tokens_label,
1177        api_timeout_ms_label,
1178        disable_nonessential_traffic_label,
1179        default_sonnet_model_label,
1180        default_opus_model_label,
1181        default_haiku_model_label,
1182    ]
1183    .iter()
1184    .map(|label| text_display_width(label))
1185    .max()
1186    .unwrap_or(0);
1187
1188    // Format token with proper alignment
1189    let token_line = format!(
1190        "{}{} {}",
1191        indent,
1192        pad_text_to_width(token_label, max_label_width, TextAlignment::Left, ' '),
1193        format_token_for_display(&config.token).dimmed()
1194    );
1195    lines.push(token_line);
1196
1197    // Format URL with proper alignment
1198    let url_line = format!(
1199        "{}{} {}",
1200        indent,
1201        pad_text_to_width(url_label, max_label_width, TextAlignment::Left, ' '),
1202        config.url.cyan()
1203    );
1204    lines.push(url_line);
1205
1206    // Format model information if available
1207    if let Some(model) = &config.model {
1208        let model_line = format!(
1209            "{}{} {}",
1210            indent,
1211            pad_text_to_width(model_label, max_label_width, TextAlignment::Left, ' '),
1212            model.yellow()
1213        );
1214        lines.push(model_line);
1215    }
1216
1217    // Format small fast model if available
1218    if let Some(small_fast_model) = &config.small_fast_model {
1219        let small_model_line = format!(
1220            "{}{} {}",
1221            indent,
1222            pad_text_to_width(small_model_label, max_label_width, TextAlignment::Left, ' '),
1223            small_fast_model.yellow()
1224        );
1225        lines.push(small_model_line);
1226    }
1227
1228    // Format max thinking tokens if available
1229    if let Some(max_thinking_tokens) = config.max_thinking_tokens {
1230        let tokens_line = format!(
1231            "{}{} {}",
1232            indent,
1233            pad_text_to_width(
1234                max_thinking_tokens_label,
1235                max_label_width,
1236                TextAlignment::Left,
1237                ' '
1238            ),
1239            format!("{}", max_thinking_tokens).yellow()
1240        );
1241        lines.push(tokens_line);
1242    }
1243
1244    // Format API timeout if available
1245    if let Some(api_timeout_ms) = config.api_timeout_ms {
1246        let timeout_line = format!(
1247            "{}{} {}",
1248            indent,
1249            pad_text_to_width(
1250                api_timeout_ms_label,
1251                max_label_width,
1252                TextAlignment::Left,
1253                ' '
1254            ),
1255            format!("{}", api_timeout_ms).yellow()
1256        );
1257        lines.push(timeout_line);
1258    }
1259
1260    // Format disable nonessential traffic flag if available
1261    if let Some(disable_flag) = config.claude_code_disable_nonessential_traffic {
1262        let flag_line = format!(
1263            "{}{} {}",
1264            indent,
1265            pad_text_to_width(
1266                disable_nonessential_traffic_label,
1267                max_label_width,
1268                TextAlignment::Left,
1269                ' '
1270            ),
1271            format!("{}", disable_flag).yellow()
1272        );
1273        lines.push(flag_line);
1274    }
1275
1276    // Format default Sonnet model if available
1277    if let Some(sonnet_model) = &config.anthropic_default_sonnet_model {
1278        let sonnet_line = format!(
1279            "{}{} {}",
1280            indent,
1281            pad_text_to_width(
1282                default_sonnet_model_label,
1283                max_label_width,
1284                TextAlignment::Left,
1285                ' '
1286            ),
1287            sonnet_model.yellow()
1288        );
1289        lines.push(sonnet_line);
1290    }
1291
1292    // Format default Opus model if available
1293    if let Some(opus_model) = &config.anthropic_default_opus_model {
1294        let opus_line = format!(
1295            "{}{} {}",
1296            indent,
1297            pad_text_to_width(
1298                default_opus_model_label,
1299                max_label_width,
1300                TextAlignment::Left,
1301                ' '
1302            ),
1303            opus_model.yellow()
1304        );
1305        lines.push(opus_line);
1306    }
1307
1308    // Format default Haiku model if available
1309    if let Some(haiku_model) = &config.anthropic_default_haiku_model {
1310        let haiku_line = format!(
1311            "{}{} {}",
1312            indent,
1313            pad_text_to_width(
1314                default_haiku_model_label,
1315                max_label_width,
1316                TextAlignment::Left,
1317                ' '
1318            ),
1319            haiku_model.yellow()
1320        );
1321        lines.push(haiku_line);
1322    }
1323
1324    lines
1325}
1326
1327#[cfg(test)]
1328mod border_drawing_tests {
1329    use super::*;
1330
1331    #[test]
1332    fn test_border_drawing_unicode_support() {
1333        let _border = BorderDrawing::new();
1334        // Should create without panic - testing that BorderDrawing can be instantiated
1335    }
1336
1337    #[test]
1338    fn test_border_drawing_top_border() {
1339        let border = BorderDrawing {
1340            unicode_supported: true,
1341        };
1342        let result = border.draw_top_border("Test", 20);
1343        assert!(!result.is_empty());
1344        assert!(result.contains("Test"));
1345    }
1346
1347    #[test]
1348    fn test_border_drawing_ascii_fallback() {
1349        let border = BorderDrawing {
1350            unicode_supported: false,
1351        };
1352        let result = border.draw_top_border("Test", 20);
1353        assert!(!result.is_empty());
1354        assert!(result.contains("Test"));
1355        assert!(result.contains("+"));
1356        assert!(result.contains("-"));
1357    }
1358
1359    #[test]
1360    fn test_border_drawing_middle_line() {
1361        let border = BorderDrawing {
1362            unicode_supported: true,
1363        };
1364        let result = border.draw_middle_line("Test message", 30);
1365        assert!(!result.is_empty());
1366        assert!(result.contains("Test message"));
1367    }
1368
1369    #[test]
1370    fn test_border_drawing_bottom_border() {
1371        let border = BorderDrawing {
1372            unicode_supported: true,
1373        };
1374        let result = border.draw_bottom_border(20);
1375        assert!(!result.is_empty());
1376    }
1377
1378    #[test]
1379    fn test_border_drawing_width_consistency() {
1380        let border = BorderDrawing {
1381            unicode_supported: true,
1382        };
1383        let width = 30;
1384        let top = border.draw_top_border("Title", width);
1385        let middle = border.draw_middle_line("Content", width);
1386        let bottom = border.draw_bottom_border(width);
1387
1388        // All borders should have the same character length (approximately)
1389        assert!(top.chars().count() >= width - 2);
1390        assert!(middle.chars().count() >= width - 2);
1391        assert!(bottom.chars().count() >= width - 2);
1392    }
1393}
1394
1395#[cfg(test)]
1396mod pagination_tests {
1397
1398    /// Test pagination calculation logic
1399    #[test]
1400    fn test_pagination_calculation() {
1401        const PAGE_SIZE: usize = 9;
1402
1403        // Test single page scenarios
1404        assert_eq!(1_usize.div_ceil(PAGE_SIZE), 1); // 1 config -> 1 page
1405        assert_eq!(9_usize.div_ceil(PAGE_SIZE), 1); // 9 configs -> 1 page
1406
1407        // Test multi-page scenarios
1408        assert_eq!(10_usize.div_ceil(PAGE_SIZE), 2); // 10 configs -> 2 pages
1409        assert_eq!(18_usize.div_ceil(PAGE_SIZE), 2); // 18 configs -> 2 pages
1410        assert_eq!(19_usize.div_ceil(PAGE_SIZE), 3); // 19 configs -> 3 pages
1411        assert_eq!(27_usize.div_ceil(PAGE_SIZE), 3); // 27 configs -> 3 pages
1412        assert_eq!(28_usize.div_ceil(PAGE_SIZE), 4); // 28 configs -> 4 pages
1413    }
1414
1415    /// Test page range calculation
1416    #[test]
1417    fn test_page_range_calculation() {
1418        const PAGE_SIZE: usize = 9;
1419
1420        // Test first page
1421        let current_page = 0;
1422        let start_idx = current_page * PAGE_SIZE; // 0
1423        let end_idx = std::cmp::min(start_idx + PAGE_SIZE, 15); // min(9, 15) = 9
1424        assert_eq!(start_idx, 0);
1425        assert_eq!(end_idx, 9);
1426        assert_eq!(end_idx - start_idx, 9); // Full page
1427
1428        // Test second page
1429        let current_page = 1;
1430        let start_idx = current_page * PAGE_SIZE; // 9
1431        let end_idx = std::cmp::min(start_idx + PAGE_SIZE, 15); // min(18, 15) = 15
1432        assert_eq!(start_idx, 9);
1433        assert_eq!(end_idx, 15);
1434        assert_eq!(end_idx - start_idx, 6); // Partial page
1435
1436        // Test edge case: exactly PAGE_SIZE configs
1437        let current_page = 0;
1438        let start_idx = current_page * PAGE_SIZE; // 0
1439        let end_idx = std::cmp::min(start_idx + PAGE_SIZE, PAGE_SIZE); // min(9, 9) = 9
1440        assert_eq!(start_idx, 0);
1441        assert_eq!(end_idx, 9);
1442        assert_eq!(end_idx - start_idx, 9); // Full page
1443    }
1444
1445    /// Test digit key mapping to config indices
1446    #[test]
1447    fn test_digit_mapping_to_config_index() {
1448        const PAGE_SIZE: usize = 9;
1449
1450        // Test first page mapping (configs 0-8)
1451        let current_page = 0;
1452        let start_idx = current_page * PAGE_SIZE; // 0
1453
1454        // Digit 1 should map to config index 0
1455        let digit = 1;
1456        let actual_config_index = start_idx + (digit - 1); // 0 + (1-1) = 0
1457        assert_eq!(actual_config_index, 0);
1458
1459        // Digit 9 should map to config index 8
1460        let digit = 9;
1461        let actual_config_index = start_idx + (digit - 1); // 0 + (9-1) = 8
1462        assert_eq!(actual_config_index, 8);
1463
1464        // Test second page mapping (configs 9-17)
1465        let current_page = 1;
1466        let start_idx = current_page * PAGE_SIZE; // 9
1467
1468        // Digit 1 should map to config index 9
1469        let digit = 1;
1470        let actual_config_index = start_idx + (digit - 1); // 9 + (1-1) = 9
1471        assert_eq!(actual_config_index, 9);
1472
1473        // Digit 5 should map to config index 13
1474        let digit = 5;
1475        let actual_config_index = start_idx + (digit - 1); // 9 + (5-1) = 13
1476        assert_eq!(actual_config_index, 13);
1477    }
1478
1479    /// Test selection index conversion for handle_selection_action
1480    #[test]
1481    fn test_selection_index_conversion() {
1482        // Test mapping digit to selection index for handle_selection_action
1483        // Note: handle_selection_action expects indices where:
1484        // - 0 = official config
1485        // - 1 = first user config
1486        // - 2 = second user config, etc.
1487
1488        const PAGE_SIZE: usize = 9;
1489
1490        // First page, digit 1 -> config index 0 -> selection index 1
1491        let current_page = 0;
1492        let start_idx = current_page * PAGE_SIZE; // 0
1493        let digit = 1;
1494        let actual_config_index = start_idx + (digit - 1); // 0
1495        let selection_index = actual_config_index + 1; // +1 because official is at index 0
1496        assert_eq!(selection_index, 1);
1497
1498        // Second page, digit 1 -> config index 9 -> selection index 10
1499        let current_page = 1;
1500        let start_idx = current_page * PAGE_SIZE; // 9
1501        let digit = 1;
1502        let actual_config_index = start_idx + (digit - 1); // 9
1503        let selection_index = actual_config_index + 1; // +1 because official is at index 0
1504        assert_eq!(selection_index, 10);
1505    }
1506
1507    /// Test page navigation bounds checking
1508    #[test]
1509    fn test_page_navigation_bounds() {
1510        const PAGE_SIZE: usize = 9;
1511        let total_configs: usize = 25; // 3 pages total
1512        let total_pages = total_configs.div_ceil(PAGE_SIZE); // 3 pages
1513        assert_eq!(total_pages, 3);
1514
1515        // Test first page - can't go to previous
1516        let mut current_page = 0;
1517        if current_page > 0 {
1518            current_page -= 1;
1519        }
1520        assert_eq!(current_page, 0); // Should stay at 0
1521
1522        // Test last page - can't go to next
1523        let mut current_page = total_pages - 1; // 2 (last page)
1524        if current_page < total_pages - 1 {
1525            current_page += 1;
1526        }
1527        assert_eq!(current_page, 2); // Should stay at 2
1528
1529        // Test middle page navigation
1530        let mut current_page = 1;
1531
1532        // Can go to next page
1533        if current_page < total_pages - 1 {
1534            current_page += 1;
1535        }
1536        assert_eq!(current_page, 2);
1537
1538        // Can go to previous page
1539        if current_page > 0 {
1540            current_page = current_page.saturating_sub(1);
1541        }
1542        assert_eq!(current_page, 1);
1543    }
1544
1545    /// Test boundary conditions for digit key processing
1546    #[test]
1547    fn test_digit_key_boundary_conditions() {
1548        const PAGE_SIZE: usize = 9;
1549
1550        // Test digit 0 (should be ignored)
1551        let digit = 0;
1552        assert!(digit < 1, "Digit 0 should be less than 1 and ignored");
1553
1554        // Test digit beyond available configs (should be ignored)
1555        let configs_len = 5; // Only 5 configs available
1556        let page_configs_len = std::cmp::min(PAGE_SIZE, configs_len); // 5
1557        let digit = 9; // User presses 9
1558        assert!(
1559            digit > page_configs_len,
1560            "Digit 9 should be beyond available configs (5) and ignored"
1561        );
1562
1563        // Test valid digit range
1564        for digit in 1..=page_configs_len {
1565            assert!(
1566                digit >= 1 && digit <= page_configs_len,
1567                "Digit {} should be valid",
1568                digit
1569            );
1570        }
1571    }
1572
1573    /// Test empty configuration list handling
1574    #[test]
1575    fn test_empty_configs_handling() {
1576        let empty_configs: Vec<String> = Vec::new();
1577        assert!(
1578            empty_configs.is_empty(),
1579            "Empty config list should be properly detected"
1580        );
1581
1582        // Verify that empty check comes before pagination calculation
1583        let configs_len = empty_configs.len(); // 0
1584        assert_eq!(configs_len, 0, "Empty configs should have length 0");
1585
1586        // No pagination should be calculated for empty configs
1587        // (function should return early)
1588    }
1589
1590    /// Test page navigation boundary conditions
1591    #[test]
1592    fn test_page_navigation_boundaries() {
1593        const PAGE_SIZE: usize = 9;
1594        let total_configs: usize = 20; // 3 pages total
1595        let total_pages = total_configs.div_ceil(PAGE_SIZE); // 3 pages
1596
1597        // Test first page navigation (cannot go to previous page)
1598        let mut current_page = 0;
1599        let original_page = current_page;
1600
1601        // Simulate PageUp on first page (should not change)
1602        if current_page > 0 {
1603            current_page -= 1;
1604        }
1605        assert_eq!(
1606            current_page, original_page,
1607            "First page should not navigate to previous"
1608        );
1609
1610        // Test last page navigation (cannot go to next page)
1611        let mut current_page = total_pages - 1; // Last page (2)
1612        let original_page = current_page;
1613
1614        // Simulate PageDown on last page (should not change)
1615        if current_page < total_pages - 1 {
1616            current_page += 1;
1617        }
1618        assert_eq!(
1619            current_page, original_page,
1620            "Last page should not navigate to next"
1621        );
1622
1623        // Test valid navigation from middle page
1624        let mut current_page = 1; // Middle page
1625
1626        // Navigate to next page
1627        if current_page < total_pages - 1 {
1628            current_page += 1;
1629        }
1630        assert_eq!(current_page, 2, "Should navigate to next page");
1631
1632        // Navigate to previous page
1633        if current_page > 0 {
1634            current_page = current_page.saturating_sub(1);
1635        }
1636        assert_eq!(current_page, 1, "Should navigate to previous page");
1637    }
1638
1639    /// Test j key navigation (should move selection down like Down arrow)
1640    #[test]
1641    fn test_j_key_navigation() {
1642        let mut selected_index: usize = 0;
1643        let configs_len = 5; // 5 configs + 1 official + 1 exit = 7 total options
1644
1645        // Test j key moves selection down
1646        // j key should behave like Down arrow
1647        if selected_index < configs_len + 1 {
1648            selected_index += 1;
1649        }
1650        assert_eq!(selected_index, 1, "j key should move selection down by one");
1651
1652        // Test j key at bottom boundary (should not go beyond configs_len + 1)
1653        selected_index = configs_len + 1;
1654        let original_index = selected_index;
1655        if selected_index < configs_len + 1 {
1656            selected_index += 1;
1657        }
1658        assert_eq!(
1659            selected_index, original_index,
1660            "j key should not move beyond bottom boundary"
1661        );
1662    }
1663
1664    /// Test k key navigation (should move selection up like Up arrow)
1665    #[test]
1666    fn test_k_key_navigation() {
1667        let mut selected_index: usize = 5;
1668
1669        // Test k key moves selection up
1670        // k key should behave like Up arrow
1671        selected_index = selected_index.saturating_sub(1);
1672        assert_eq!(selected_index, 4, "k key should move selection up by one");
1673
1674        // Test k key at top boundary (should not go below 0)
1675        selected_index = 0;
1676        let original_index = selected_index;
1677        selected_index = selected_index.saturating_sub(1);
1678        assert_eq!(
1679            selected_index, original_index,
1680            "k key should not move beyond top boundary"
1681        );
1682    }
1683
1684    /// Test j/k key boundary conditions match arrow key behavior
1685    #[test]
1686    fn test_jk_key_boundary_conditions() {
1687        const CONFIGS_LEN: usize = 5;
1688
1689        // Test j key at bottom boundary (same as Down arrow)
1690        let mut selected_index: usize = CONFIGS_LEN + 1; // At exit option
1691        let original_index = selected_index;
1692        if selected_index < CONFIGS_LEN + 1 {
1693            selected_index += 1; // This is what j key does
1694        }
1695        assert_eq!(
1696            selected_index, original_index,
1697            "j key should respect bottom boundary like Down arrow"
1698        );
1699
1700        // Test k key at top boundary (same as Up arrow)
1701        let mut selected_index: usize = 0; // At official option
1702        let original_index = selected_index;
1703        selected_index = selected_index.saturating_sub(1); // This is what k key does
1704        assert_eq!(
1705            selected_index, original_index,
1706            "k key should respect top boundary like Up arrow"
1707        );
1708    }
1709}
1710
1711/// Error type for handling edit mode navigation
1712#[derive(Debug, PartialEq)]
1713enum EditModeError {
1714    ReturnToMenu,
1715}
1716
1717impl std::fmt::Display for EditModeError {
1718    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1719        match self {
1720            EditModeError::ReturnToMenu => write!(f, "return_to_menu"),
1721        }
1722    }
1723}
1724
1725impl std::error::Error for EditModeError {}
1726
1727/// Handle configuration editing with interactive field selection
1728fn handle_config_edit(config: &Configuration) -> Result<()> {
1729    println!("\n{}", "配置编辑模式".green().bold());
1730    println!("{}", "===================".green());
1731    println!("正在编辑配置: {}", config.alias_name.cyan().bold());
1732    println!();
1733
1734    // Create a mutable copy for editing
1735    let mut editing_config = config.clone();
1736    let original_alias = config.alias_name.clone();
1737
1738    loop {
1739        // Display current field values
1740        display_edit_menu(&editing_config);
1741
1742        // Get user input for field selection
1743        println!("\n{}", "提示: 可使用大小写字母".dimmed());
1744        print!("请选择要编辑的字段 (1-9, A-B), 或输入 S 保存, Q 返回上一级菜单: ");
1745        io::stdout().flush()?;
1746
1747        let mut input = String::new();
1748        io::stdin().read_line(&mut input)?;
1749        let input = input.trim();
1750
1751        // Note: Both lowercase and uppercase are accepted for commands
1752        match input {
1753            "1" => edit_field_alias(&mut editing_config)?,
1754            "2" => edit_field_token(&mut editing_config)?,
1755            "3" => edit_field_url(&mut editing_config)?,
1756            "4" => edit_field_model(&mut editing_config)?,
1757            "5" => edit_field_small_fast_model(&mut editing_config)?,
1758            "6" => edit_field_max_thinking_tokens(&mut editing_config)?,
1759            "7" => edit_field_api_timeout_ms(&mut editing_config)?,
1760            "8" => edit_field_claude_code_disable_nonessential_traffic(&mut editing_config)?,
1761            "9" => edit_field_anthropic_default_sonnet_model(&mut editing_config)?,
1762            "10" | "a" | "A" => edit_field_anthropic_default_opus_model(&mut editing_config)?,
1763            "11" | "b" | "B" => edit_field_anthropic_default_haiku_model(&mut editing_config)?,
1764            "s" | "S" => {
1765                // Save changes
1766                return save_configuration_changes(&original_alias, &editing_config);
1767            }
1768            "q" | "Q" => {
1769                println!("\n{}", "返回上一级菜单".blue());
1770                return Err(EditModeError::ReturnToMenu.into());
1771            }
1772            _ => {
1773                println!("{}", "无效选择,请重试".red());
1774            }
1775        }
1776    }
1777}
1778
1779/// Display the edit menu with current field values
1780fn display_edit_menu(config: &Configuration) {
1781    println!("\n{}", "当前配置值:".blue().bold());
1782    println!("{}", "─────────────────────────".blue());
1783
1784    println!("1. 别名 (alias_name): {}", config.alias_name.green());
1785
1786    println!(
1787        "2. 令牌 (ANTHROPIC_AUTH_TOKEN): {}",
1788        format_token_for_display(&config.token).green()
1789    );
1790
1791    println!("3. URL (ANTHROPIC_BASE_URL): {}", config.url.green());
1792
1793    println!(
1794        "4. 模型 (ANTHROPIC_MODEL): {}",
1795        config.model.as_deref().unwrap_or("[未设置]").green()
1796    );
1797
1798    println!(
1799        "5. 快速模型 (ANTHROPIC_SMALL_FAST_MODEL): {}",
1800        config
1801            .small_fast_model
1802            .as_deref()
1803            .unwrap_or("[未设置]")
1804            .green()
1805    );
1806
1807    println!(
1808        "6. 最大思考令牌数 (ANTHROPIC_MAX_THINKING_TOKENS): {}",
1809        config
1810            .max_thinking_tokens
1811            .map(|t| t.to_string())
1812            .unwrap_or("[未设置]".to_string())
1813            .green()
1814    );
1815
1816    println!(
1817        "7. API超时时间 (API_TIMEOUT_MS): {}",
1818        config
1819            .api_timeout_ms
1820            .map(|t| t.to_string())
1821            .unwrap_or("[未设置]".to_string())
1822            .green()
1823    );
1824
1825    println!(
1826        "8. 禁用非必要流量 (CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC): {}",
1827        config
1828            .claude_code_disable_nonessential_traffic
1829            .map(|t| t.to_string())
1830            .unwrap_or("[未设置]".to_string())
1831            .green()
1832    );
1833
1834    println!(
1835        "9. 默认 Sonnet 模型 (ANTHROPIC_DEFAULT_SONNET_MODEL): {}",
1836        config
1837            .anthropic_default_sonnet_model
1838            .as_deref()
1839            .unwrap_or("[未设置]")
1840            .green()
1841    );
1842
1843    println!(
1844        "A. 默认 Opus 模型 (ANTHROPIC_DEFAULT_OPUS_MODEL): {}",
1845        config
1846            .anthropic_default_opus_model
1847            .as_deref()
1848            .unwrap_or("[未设置]")
1849            .green()
1850    );
1851
1852    println!(
1853        "B. 默认 Haiku 模型 (ANTHROPIC_DEFAULT_HAIKU_MODEL): {}",
1854        config
1855            .anthropic_default_haiku_model
1856            .as_deref()
1857            .unwrap_or("[未设置]")
1858            .green()
1859    );
1860
1861    println!("{}", "─────────────────────────".blue());
1862    println!(
1863        "S. {} | Q. {}",
1864        "保存更改".green().bold(),
1865        "返回上一级菜单".blue()
1866    );
1867}
1868
1869/// Helper function to edit a string field
1870fn edit_string_field(
1871    field_name: &str,
1872    current_value: &str,
1873    validator: impl Fn(&str) -> Result<()>,
1874) -> Result<Option<String>> {
1875    println!("\n编辑{field_name}:");
1876    println!("当前值: {}", current_value.cyan());
1877    print!("新值 (回车保持不变): ");
1878    io::stdout().flush()?;
1879
1880    let mut input = String::new();
1881    io::stdin().read_line(&mut input)?;
1882    let input = input.trim();
1883
1884    if !input.is_empty() {
1885        validator(input)?;
1886        println!("{field_name}已更新为: {}", input.green());
1887        Ok(Some(input.to_string()))
1888    } else {
1889        Ok(None)
1890    }
1891}
1892
1893/// Type alias for optional string field result
1894type OptionalStringResult = Result<Option<Option<String>>>;
1895
1896/// Helper function to edit an optional string field (can be cleared)
1897fn edit_optional_string_field(
1898    field_name: &str,
1899    current_value: Option<&str>,
1900) -> OptionalStringResult {
1901    println!("\n编辑{field_name}:");
1902    println!("当前值: {}", current_value.unwrap_or("[未设置]").cyan());
1903    print!("新值 (回车保持不变,输入空格清除): ");
1904    io::stdout().flush()?;
1905
1906    let mut input = String::new();
1907    io::stdin().read_line(&mut input)?;
1908    let input = input.trim();
1909
1910    if !input.is_empty() {
1911        if input == " " {
1912            println!("{}", format!("{field_name}已清除").green());
1913            Ok(Some(None))
1914        } else {
1915            println!("{field_name}已更新为: {}", input.green());
1916            Ok(Some(Some(input.to_string())))
1917        }
1918    } else {
1919        Ok(None)
1920    }
1921}
1922
1923/// Type alias for optional u32 field result
1924type OptionalU32Result = Result<Option<Option<u32>>>;
1925
1926/// Helper function to edit an optional u32 field (can be cleared)
1927fn edit_optional_u32_field(field_name: &str, current_value: Option<u32>) -> OptionalU32Result {
1928    println!("\n编辑{field_name}:");
1929    println!(
1930        "当前值: {}",
1931        current_value
1932            .map(|t| t.to_string())
1933            .unwrap_or("[未设置]".to_string())
1934            .cyan()
1935    );
1936    print!("新值 (回车保持不变,输入 0 清除): ");
1937    io::stdout().flush()?;
1938
1939    let mut input = String::new();
1940    io::stdin().read_line(&mut input)?;
1941    let input = input.trim();
1942
1943    if !input.is_empty() {
1944        if input == "0" {
1945            println!("{}", format!("{field_name}已清除").green());
1946            Ok(Some(None))
1947        } else if let Ok(value) = input.parse::<u32>() {
1948            println!("{field_name}已更新为: {}", value.to_string().green());
1949            Ok(Some(Some(value)))
1950        } else {
1951            println!("{}", "错误: 请输入有效的数字".red());
1952            Ok(None)
1953        }
1954    } else {
1955        Ok(None)
1956    }
1957}
1958
1959/// Edit alias field
1960fn edit_field_alias(config: &mut Configuration) -> Result<()> {
1961    let validator = |input: &str| -> Result<()> {
1962        if input.contains(char::is_whitespace) {
1963            anyhow::bail!("错误: 别名不能包含空白字符");
1964        }
1965        if input == "cc" {
1966            anyhow::bail!("错误: 'cc' 是保留名称");
1967        }
1968        Ok(())
1969    };
1970
1971    match edit_string_field("别名", &config.alias_name, validator) {
1972        Ok(Some(new_value)) => config.alias_name = new_value,
1973        Ok(None) => {}
1974        Err(e) => println!("{}", e.to_string().red()),
1975    }
1976    Ok(())
1977}
1978
1979/// Edit token field
1980fn edit_field_token(config: &mut Configuration) -> Result<()> {
1981    let no_validator = |_: &str| -> Result<()> { Ok(()) };
1982    if let Some(new_value) = edit_string_field(
1983        "令牌",
1984        &format_token_for_display(&config.token),
1985        no_validator,
1986    )? {
1987        config.token = new_value;
1988        println!("{}", "令牌已更新".green());
1989    }
1990    Ok(())
1991}
1992
1993/// Edit URL field
1994fn edit_field_url(config: &mut Configuration) -> Result<()> {
1995    let no_validator = |_: &str| -> Result<()> { Ok(()) };
1996    if let Some(new_value) = edit_string_field("URL", &config.url, no_validator)? {
1997        config.url = new_value;
1998    }
1999    Ok(())
2000}
2001
2002/// Edit model field
2003fn edit_field_model(config: &mut Configuration) -> Result<()> {
2004    if let Some(result) = edit_optional_string_field("模型", config.model.as_deref())? {
2005        config.model = result;
2006    }
2007    Ok(())
2008}
2009
2010/// Edit small_fast_model field
2011fn edit_field_small_fast_model(config: &mut Configuration) -> Result<()> {
2012    if let Some(result) =
2013        edit_optional_string_field("快速模型", config.small_fast_model.as_deref())?
2014    {
2015        config.small_fast_model = result;
2016    }
2017    Ok(())
2018}
2019
2020/// Edit max_thinking_tokens field
2021fn edit_field_max_thinking_tokens(config: &mut Configuration) -> Result<()> {
2022    if let Some(result) = edit_optional_u32_field("最大思考令牌数", config.max_thinking_tokens)?
2023    {
2024        config.max_thinking_tokens = result;
2025    }
2026    Ok(())
2027}
2028
2029/// Edit api_timeout_ms field
2030fn edit_field_api_timeout_ms(config: &mut Configuration) -> Result<()> {
2031    if let Some(result) = edit_optional_u32_field("API超时时间 (毫秒)", config.api_timeout_ms)?
2032    {
2033        config.api_timeout_ms = result;
2034    }
2035    Ok(())
2036}
2037
2038/// Edit claude_code_disable_nonessential_traffic field
2039fn edit_field_claude_code_disable_nonessential_traffic(config: &mut Configuration) -> Result<()> {
2040    if let Some(result) = edit_optional_u32_field(
2041        "禁用非必要流量标志",
2042        config.claude_code_disable_nonessential_traffic,
2043    )? {
2044        config.claude_code_disable_nonessential_traffic = result;
2045    }
2046    Ok(())
2047}
2048
2049/// Edit anthropic_default_sonnet_model field
2050fn edit_field_anthropic_default_sonnet_model(config: &mut Configuration) -> Result<()> {
2051    if let Some(result) = edit_optional_string_field(
2052        "默认 Sonnet 模型",
2053        config.anthropic_default_sonnet_model.as_deref(),
2054    )? {
2055        config.anthropic_default_sonnet_model = result;
2056    }
2057    Ok(())
2058}
2059
2060/// Edit anthropic_default_opus_model field
2061fn edit_field_anthropic_default_opus_model(config: &mut Configuration) -> Result<()> {
2062    if let Some(result) = edit_optional_string_field(
2063        "默认 Opus 模型",
2064        config.anthropic_default_opus_model.as_deref(),
2065    )? {
2066        config.anthropic_default_opus_model = result;
2067    }
2068    Ok(())
2069}
2070
2071/// Edit anthropic_default_haiku_model field
2072fn edit_field_anthropic_default_haiku_model(config: &mut Configuration) -> Result<()> {
2073    if let Some(result) = edit_optional_string_field(
2074        "默认 Haiku 模型",
2075        config.anthropic_default_haiku_model.as_deref(),
2076    )? {
2077        config.anthropic_default_haiku_model = result;
2078    }
2079    Ok(())
2080}
2081
2082/// Save configuration changes to disk and handle alias conflicts
2083fn save_configuration_changes(original_alias: &str, new_config: &Configuration) -> Result<()> {
2084    // Load current storage
2085    let mut storage = ConfigStorage::load()?;
2086
2087    // Check for alias conflicts if alias changed
2088    if original_alias != new_config.alias_name
2089        && storage.get_configuration(&new_config.alias_name).is_some()
2090    {
2091        println!("\n{}", "别名冲突!".red().bold());
2092        println!("配置 '{}' 已存在", new_config.alias_name.yellow());
2093        print!("是否覆盖现有配置? (y/N): ");
2094        io::stdout().flush()?;
2095
2096        let mut input = String::new();
2097        io::stdin().read_line(&mut input)?;
2098        let input = input.trim().to_lowercase();
2099
2100        if input != "y" && input != "yes" {
2101            println!("{}", "编辑已取消".yellow());
2102            return Ok(());
2103        }
2104    }
2105
2106    // Update configuration using the method from config_storage.rs
2107    storage.update_configuration(original_alias, new_config.clone())?;
2108    storage.save()?;
2109
2110    println!("\n{}", "配置已成功保存!".green().bold());
2111
2112    Ok(())
2113}