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