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