rusty-rich 0.3.0

Rich text and beautiful formatting in the terminal — a Rust port of Python's Rich library
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
//! Interactive prompts — equivalent to Rich's `rich/prompt.py`.
//!
//! This module provides types for prompting the user for input:
//!
//! - `Prompt` — string input
//! - `IntPrompt` — integer input
//! - `FloatPrompt` — float input
//! - `Confirm` — yes / no input
//! - `Select<T>` — pick from a list of named choices
//!
//! All prompts support:
//! - Optional `Console` for styled output (falls back to raw stdout)
//! - Password mode (hidden input, masked with `*`)
//! - Choice validation with optional case sensitivity
//! - Display of default values and choices

use std::fmt;
use std::io::{self, BufRead, Write};

use crate::console::Console;
use crate::style::Style;

// ---------------------------------------------------------------------------
// PromptError
// ---------------------------------------------------------------------------

/// Errors that can occur during prompting.
#[derive(Debug)]
pub enum PromptError {
    /// The user provided an invalid response.
    InvalidResponse(String),
    /// An underlying I/O error occurred.
    IOError(io::Error),
    /// The user cancelled the prompt (e.g. Ctrl+C / Ctrl+D).
    Cancelled,
}

impl fmt::Display for PromptError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::InvalidResponse(msg) => write!(f, "{}", msg),
            Self::IOError(e) => write!(f, "I/O error: {}", e),
            Self::Cancelled => write!(f, "cancelled"),
        }
    }
}

impl std::error::Error for PromptError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            Self::IOError(e) => Some(e),
            _ => None,
        }
    }
}

impl From<io::Error> for PromptError {
    fn from(e: io::Error) -> Self {
        PromptError::IOError(e)
    }
}

// ---------------------------------------------------------------------------
// Password reader (crossterm raw mode, no rpassword dependency)
// ---------------------------------------------------------------------------

/// Read a line of input with echoing disabled; show `*` for each character.
/// Handles backspace for erasing the last character.
fn read_password() -> Result<String, PromptError> {
    use crossterm::event::{self, Event, KeyCode, KeyEventKind};
    use crossterm::terminal::{disable_raw_mode, enable_raw_mode};

    enable_raw_mode().map_err(PromptError::IOError)?;

    let mut result = String::new();

    let cleanup = || {
        let _ = disable_raw_mode();
    };

    loop {
        match event::read() {
            Ok(Event::Key(key))
                if key.kind == KeyEventKind::Press || key.kind == KeyEventKind::Repeat =>
            {
                match key.code {
                    KeyCode::Enter => {
                        let _ = io::stdout().write(b"\n");
                        let _ = io::stdout().flush();
                        break;
                    }
                    KeyCode::Char(c) => {
                        result.push(c);
                        let _ = io::stdout().write(b"*");
                        let _ = io::stdout().flush();
                    }
                    KeyCode::Backspace => {
                        if result.pop().is_some() {
                            let _ = io::stdout().write(b"\x08 \x08");
                            let _ = io::stdout().flush();
                        }
                    }
                    KeyCode::Esc | KeyCode::Delete => {
                        cleanup();
                        return Err(PromptError::Cancelled);
                    }
                    _ => {}
                }
            }
            Ok(Event::Key(key)) if key.code == KeyCode::Enter => {
                let _ = io::stdout().write(b"\n");
                let _ = io::stdout().flush();
                break;
            }
            Ok(Event::Key(key)) if key.code == KeyCode::Esc => {
                cleanup();
                return Err(PromptError::Cancelled);
            }
            Ok(_) => {}
            Err(e) => {
                cleanup();
                return Err(PromptError::IOError(e));
            }
        }
    }

    cleanup();
    Ok(result)
}

// ---------------------------------------------------------------------------
// PromptBase
// ---------------------------------------------------------------------------

/// Base configuration for all prompt types.
///
/// Holds common fields like the prompt text, optional console, password mode,
/// choices list, case sensitivity, and display flags.
pub struct PromptBase {
    /// The prompt text to display.
    pub prompt: String,
    /// An optional `Console` for styled output. If `None`, writes directly to
    /// `std::io::stdout()`.
    pub console: Option<Console>,
    /// When `true`, input characters are masked with `*`.
    pub password: bool,
    /// Optional list of valid choices. When set, the user's response is
    /// validated against this list.
    pub choices: Option<Vec<String>>,
    /// Whether choice matching is case-sensitive (default `false`).
    pub case_sensitive: bool,
    /// Whether to show the default value in the prompt string.
    pub show_default: bool,
    /// Whether to show the list of choices in the prompt string.
    pub show_choices: bool,
}

impl PromptBase {
    /// Create a new `PromptBase` with the given prompt text.
    pub fn new(prompt: impl Into<String>) -> Self {
        Self {
            prompt: prompt.into(),
            console: None,
            password: false,
            choices: None,
            case_sensitive: false,
            show_default: true,
            show_choices: true,
        }
    }

    /// Builder: set the console.
    pub fn console(mut self, console: Console) -> Self {
        self.console = Some(console);
        self
    }

    /// Builder: enable or disable password mode.
    pub fn password(mut self, yes: bool) -> Self {
        self.password = yes;
        self
    }

    /// Builder: set the valid choices.
    pub fn choices(mut self, choices: Vec<String>) -> Self {
        self.choices = Some(choices);
        self
    }

    /// Builder: set case sensitivity for choice validation.
    pub fn case_sensitive(mut self, yes: bool) -> Self {
        self.case_sensitive = yes;
        self
    }

    /// Builder: show or hide the default value.
    pub fn show_default(mut self, yes: bool) -> Self {
        self.show_default = yes;
        self
    }

    /// Builder: show or hide the choices list.
    pub fn show_choices(mut self, yes: bool) -> Self {
        self.show_choices = yes;
        self
    }

    // ------------------------------------------------------------------
    // Helpers
    // ------------------------------------------------------------------

    /// Format the default value for display.
    ///
    /// Returns `" (default: value)"` wrapped in the `prompt.default` style, or
    /// an empty string if `show_default` is `false`.
    pub fn render_default(&self, default: &str) -> String {
        if !self.show_default || default.is_empty() {
            return String::new();
        }
        let styled = apply_style(default, "prompt.default");
        format!(" ({})", styled)
    }

    /// Build the full prompt string including choices and default.
    ///
    /// Returns a string like:
    /// `"Enter choice [a/b/c] (default: x): "`
    pub fn make_prompt(&self) -> String {
        let mut parts = Vec::new();

        // Choices display
        if self.show_choices {
            if let Some(choices) = &self.choices {
                let display_choices: Vec<&str> = choices.iter().map(|s| s.as_str()).collect();
                let styled = apply_style(&display_choices.join("/"), "prompt.choices");
                parts.push(format!("[{}]", styled));
            }
        }

        let suffix = if parts.is_empty() {
            String::new()
        } else {
            format!(" {} ", parts.join(" "))
        };

        let styled_prompt = apply_style(&self.prompt, "prompt");
        format!("{}{}: ", styled_prompt, suffix)
    }

    /// Check whether `value` is a valid choice.
    ///
    /// If `choices` is `None`, returns `true`.
    /// Otherwise returns `true` only if `value` (optionally case-insensitive)
    /// matches one of the allowed choices.
    pub fn check_choice(&self, value: &str) -> bool {
        match &self.choices {
            None => true,
            Some(choices) => {
                if self.case_sensitive {
                    choices.iter().any(|c| c == value)
                } else {
                    let lower = value.to_lowercase();
                    choices.iter().any(|c| c.to_lowercase() == lower)
                }
            }
        }
    }

    /// Read a line from stdin.
    fn read_line(&self) -> Result<String, PromptError> {
        if self.password {
            read_password()
        } else {
            let mut input = String::new();
            io::stdin()
                .lock()
                .read_line(&mut input)
                .map_err(PromptError::IOError)?;
            if input.is_empty() {
                return Err(PromptError::Cancelled);
            }
            Ok(input
                .trim_end_matches('\n')
                .trim_end_matches('\r')
                .to_string())
        }
    }

    /// Write a string to stdout.
    fn write_output(&self, text: &str) -> Result<(), PromptError> {
        let mut out = io::stdout();
        out.write_all(text.as_bytes())?;
        out.flush()?;
        Ok(())
    }
}

// ---------------------------------------------------------------------------
// Prompt (string)
// ---------------------------------------------------------------------------

/// Prompt the user for a string.
///
/// # Example
///
/// ```rust,no_run
/// use rusty_rich::Prompt;
///
/// let name = Prompt::ask_with("Enter name").unwrap();
/// ```
pub struct Prompt {
    base: PromptBase,
}

impl Prompt {
    /// Create a new string prompt.
    pub fn new(prompt: impl Into<String>) -> Self {
        Self {
            base: PromptBase::new(prompt),
        }
    }

    /// Builder: set the console.
    pub fn console(mut self, console: Console) -> Self {
        self.base.console = Some(console);
        self
    }

    /// Builder: enable password mode.
    pub fn password(mut self, yes: bool) -> Self {
        self.base.password = yes;
        self
    }

    /// Builder: set valid choices.
    pub fn choices(mut self, choices: Vec<String>) -> Self {
        self.base.choices = Some(choices);
        self
    }

    /// Builder: set case sensitivity.
    pub fn case_sensitive(mut self, yes: bool) -> Self {
        self.base.case_sensitive = yes;
        self
    }

    /// Builder: show or hide choices.
    pub fn show_choices(mut self, yes: bool) -> Self {
        self.base.show_choices = yes;
        self
    }

    /// Builder: show or hide default.
    pub fn show_default(mut self, yes: bool) -> Self {
        self.base.show_default = yes;
        self
    }

    /// Render the prompt string with styling applied.
    ///
    /// Returns a styled string like `"Enter name: "` where the prompt text and
    /// choices are colored using the theme's `prompt` and `prompt.choices`
    /// styles.
    pub fn render(&self) -> String {
        self.base.make_prompt()
    }

    /// Ask the user for string input.
    ///
    /// Displays the prompt, reads a line from stdin, validates it against
    /// any configured choices, and returns the trimmed string.
    ///
    /// # Errors
    ///
    /// Returns `PromptError::Cancelled` on EOF or Ctrl+C,
    /// `PromptError::InvalidResponse` when the input does not match choices,
    /// and `PromptError::IOError` on I/O failures.
    pub fn ask(&self) -> Result<String, PromptError> {
        let prompt_str = self.base.make_prompt();
        self.base.write_output(&prompt_str)?;
        let value = self.base.read_line()?;
        if !self.base.check_choice(&value) {
            return Err(PromptError::InvalidResponse(format!(
                "invalid choice: '{}'",
                value
            )));
        }
        Ok(value)
    }

    /// Convenience: create a prompt, ask, and return the result.
    ///
    /// Equivalent to `Prompt::new(prompt).ask()`.
    pub fn ask_with(prompt: impl Into<String>) -> Result<String, PromptError> {
        Prompt::new(prompt).ask()
    }
}

// ---------------------------------------------------------------------------
// IntPrompt
// ---------------------------------------------------------------------------

/// Prompt the user for an integer.
///
/// # Example
///
/// ```rust,no_run
/// use rusty_rich::IntPrompt;
///
/// let age = IntPrompt::ask_with("Enter age").unwrap();
/// ```
pub struct IntPrompt {
    base: PromptBase,
}

impl IntPrompt {
    /// Create a new integer prompt.
    pub fn new(prompt: impl Into<String>) -> Self {
        Self {
            base: PromptBase::new(prompt),
        }
    }

    /// Builder: set the console.
    pub fn console(mut self, console: Console) -> Self {
        self.base.console = Some(console);
        self
    }

    /// Builder: enable password mode.
    pub fn password(mut self, yes: bool) -> Self {
        self.base.password = yes;
        self
    }

    /// Builder: set valid choices.
    pub fn choices(mut self, choices: Vec<String>) -> Self {
        self.base.choices = Some(choices);
        self
    }

    /// Builder: set case sensitivity.
    pub fn case_sensitive(mut self, yes: bool) -> Self {
        self.base.case_sensitive = yes;
        self
    }

    /// Ask the user for an integer.
    ///
    /// Reads input and attempts to parse it as `i64`. Loops until a valid
    /// integer is provided.
    ///
    /// # Errors
    ///
    /// Returns `PromptError::Cancelled` on EOF or Ctrl+C.
    /// Returns `PromptError::IOError` on I/O failures.
    pub fn ask(&self) -> Result<i64, PromptError> {
        loop {
            let prompt_str = self.base.make_prompt();
            self.base.write_output(&prompt_str)?;
            let value = self.base.read_line()?;
            if value.is_empty() {
                continue;
            }
            if !self.base.check_choice(&value) {
                let _ = self.base.write_output(&format!(
                    "Invalid choice: '{}'. Please try again.\n",
                    value
                ));
                continue;
            }
            match value.parse::<i64>() {
                Ok(n) => return Ok(n),
                Err(_) => {
                    let _ =
                        self.base.write_output("Please enter a valid integer.\n");
                }
            }
        }
    }

    /// Convenience: create an integer prompt, ask, and return the result.
    pub fn ask_with(prompt: impl Into<String>) -> Result<i64, PromptError> {
        IntPrompt::new(prompt).ask()
    }
}

// ---------------------------------------------------------------------------
// FloatPrompt
// ---------------------------------------------------------------------------

/// Prompt the user for a floating-point number.
///
/// # Example
///
/// ```rust,no_run
/// use rusty_rich::FloatPrompt;
///
/// let height = FloatPrompt::ask_with("Enter height").unwrap();
/// ```
pub struct FloatPrompt {
    base: PromptBase,
}

impl FloatPrompt {
    /// Create a new float prompt.
    pub fn new(prompt: impl Into<String>) -> Self {
        Self {
            base: PromptBase::new(prompt),
        }
    }

    /// Builder: set the console.
    pub fn console(mut self, console: Console) -> Self {
        self.base.console = Some(console);
        self
    }

    /// Builder: enable password mode.
    pub fn password(mut self, yes: bool) -> Self {
        self.base.password = yes;
        self
    }

    /// Builder: set valid choices.
    pub fn choices(mut self, choices: Vec<String>) -> Self {
        self.base.choices = Some(choices);
        self
    }

    /// Builder: set case sensitivity.
    pub fn case_sensitive(mut self, yes: bool) -> Self {
        self.base.case_sensitive = yes;
        self
    }

    /// Ask the user for a float.
    ///
    /// Reads input and attempts to parse it as `f64`. Loops until a valid
    /// float is provided.
    ///
    /// # Errors
    ///
    /// Returns `PromptError::Cancelled` on EOF or Ctrl+C.
    /// Returns `PromptError::IOError` on I/O failures.
    pub fn ask(&self) -> Result<f64, PromptError> {
        loop {
            let prompt_str = self.base.make_prompt();
            self.base.write_output(&prompt_str)?;
            let value = self.base.read_line()?;
            if value.is_empty() {
                continue;
            }
            if !self.base.check_choice(&value) {
                let _ = self.base.write_output(&format!(
                    "Invalid choice: '{}'. Please try again.\n",
                    value
                ));
                continue;
            }
            match value.parse::<f64>() {
                Ok(n) => return Ok(n),
                Err(_) => {
                    let _ =
                        self.base.write_output("Please enter a valid number.\n");
                }
            }
        }
    }

    /// Convenience: create a float prompt, ask, and return the result.
    pub fn ask_with(prompt: impl Into<String>) -> Result<f64, PromptError> {
        FloatPrompt::new(prompt).ask()
    }
}

// ---------------------------------------------------------------------------
// Confirm
// ---------------------------------------------------------------------------

/// Prompt the user for a yes/no answer.
///
/// Returns `bool` where `true` means yes / affirmative.
///
/// # Example
///
/// ```rust,no_run
/// use rusty_rich::Confirm;
///
/// let ok = Confirm::ask_with("Continue?", true).unwrap();
/// ```
pub struct Confirm {
    base: PromptBase,
    /// Default answer if the user presses Enter without typing.
    pub default: bool,
}

impl Confirm {
    /// Create a new confirmation prompt with a default answer.
    pub fn new(prompt: impl Into<String>, default: bool) -> Self {
        Self {
            base: PromptBase::new(prompt),
            default,
        }
    }

    /// Builder: set the console.
    pub fn console(mut self, console: Console) -> Self {
        self.base.console = Some(console);
        self
    }

    /// Build the confirmation prompt string.
    ///
    /// Displays `[y/N]` or `[Y/n]` depending on the default, followed by `: `.
    fn make_confirm_prompt(&self) -> String {
        let (yes, no) = if self.default {
            ("Y", "n")
        } else {
            ("y", "N")
        };
        let styled_prompt = apply_style(&self.base.prompt, "prompt");
        let styled_choices = apply_style(&format!("[{}/{}]", yes, no), "prompt.choices");
        format!("{} {}: ", styled_prompt, styled_choices)
    }

    /// Ask the user for a yes/no answer.
    ///
    /// Recognises `y`, `yes`, `true`, `1` as affirmative;
    /// `n`, `no`, `false`, `0` as negative.
    /// An empty input returns the default.
    ///
    /// # Errors
    ///
    /// Returns `PromptError::Cancelled` on EOF or Ctrl+C.
    pub fn ask(&self) -> Result<bool, PromptError> {
        loop {
            let prompt_str = self.make_confirm_prompt();
            self.base.write_output(&prompt_str)?;
            let value = self.base.read_line()?;
            match value.to_lowercase().as_str() {
                "" => return Ok(self.default),
                "y" | "yes" | "true" | "1" => return Ok(true),
                "n" | "no" | "false" | "0" => return Ok(false),
                _ => {
                    let _ =
                        self.base.write_output("Please answer y or n.\n");
                }
            }
        }
    }

    /// Convenience: create a confirmation prompt with the given default,
    /// ask, and return the result.
    pub fn ask_with(prompt: impl Into<String>, default: bool) -> Result<bool, PromptError> {
        Confirm::new(prompt, default).ask()
    }
}

// ---------------------------------------------------------------------------
// Select
// ---------------------------------------------------------------------------

/// Prompt the user to select from a list of named choices.
///
/// Each choice is a `(label, value)` pair. The user selects by number.
///
/// # Example
///
/// ```rust,no_run
/// use rusty_rich::Select;
///
/// let choice = Select::new("Pick a color")
///     .choice("Red", "red")
///     .choice("Green", "green")
///     .choice("Blue", "blue")
///     .ask()
///     .unwrap();
/// ```
pub struct Select<T> {
    base: PromptBase,
    choices: Vec<(String, T)>,
}

impl<T> Select<T> {
    /// Create a new select prompt.
    pub fn new(prompt: impl Into<String>) -> Self {
        Self {
            base: PromptBase::new(prompt),
            choices: Vec::new(),
        }
    }

    /// Builder: set the console.
    pub fn console(mut self, console: Console) -> Self {
        self.base.console = Some(console);
        self
    }

    /// Builder: add a choice with the given label and value.
    pub fn choice(mut self, label: impl Into<String>, value: T) -> Self {
        self.choices.push((label.into(), value));
        self
    }
}

impl<T: fmt::Display> Select<T> {
    /// Render the select prompt as a numbered list.
    ///
    /// Returns a multi-line string like:
    /// ```text
    /// Pick a color:
    ///   1) Red
    ///   2) Green
    ///   3) Blue
    /// Enter number [1-3]:
    /// ```
    pub fn render(&self) -> String {
        let mut output = String::new();
        let styled_prompt = apply_style(&self.base.prompt, "prompt");
        output.push_str(&styled_prompt);
        output.push('\n');

        for (i, (label, _)) in self.choices.iter().enumerate() {
            output.push_str(&format!("  {}) {}\n", i + 1, label));
        }

        let styled_choices = apply_style(
            &format!("Enter number [1-{}]", self.choices.len()),
            "prompt.choices",
        );
        output.push_str(&format!("{}: ", styled_choices));
        output
    }
}

impl<T: fmt::Display + Clone> Select<T> {
    /// Ask the user to select from the choices.
    ///
    /// Displays a numbered list, then prompts for a number.
    /// Loops until a valid number is entered.
    ///
    /// # Errors
    ///
    /// Returns `PromptError::Cancelled` on EOF or Ctrl+C.
    /// Returns `PromptError::InvalidResponse` if there are no choices.
    pub fn ask(&self) -> Result<T, PromptError> {
        if self.choices.is_empty() {
            return Err(PromptError::InvalidResponse(
                "no choices available".into(),
            ));
        }

        let prompt_str = self.render();
        self.base.write_output(&prompt_str)?;

        loop {
            let value = self.base.read_line()?;
            if value.is_empty() {
                continue;
            }
            match value.trim().parse::<usize>() {
                Ok(n) if n >= 1 && n <= self.choices.len() => {
                    return Ok(self.choices[n - 1].1.clone());
                }
                _ => {
                    let _ = self.base.write_output(&format!(
                        "Please enter a number between 1 and {}.\n",
                        self.choices.len()
                    ));
                }
            }
        }
    }
}

// ---------------------------------------------------------------------------
// Helper: apply a theme style name to text via ANSI escapes
// ---------------------------------------------------------------------------

/// Apply the ANSI style for the given theme key to `text`.
///
/// Falls back to plain text if no style is configured.
fn apply_style(text: &str, style_name: &str) -> String {
    let theme = crate::theme::default_theme();
    if let Some(style) = theme.get(style_name) {
        let ansi = style.to_ansi();
        if ansi.is_empty() {
            text.to_string()
        } else {
            format!("\x1b[{}m{}\x1b[0m", ansi, text)
        }
    } else {
        text.to_string()
    }
}

/// Apply a raw `Style` to text via ANSI escapes.
#[allow(dead_code)]
fn apply_raw_style(text: &str, style: &Style) -> String {
    let ansi = style.to_ansi();
    if ansi.is_empty() {
        text.to_string()
    } else {
        format!("\x1b[{}m{}\x1b[0m", ansi, text)
    }
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

#[cfg(test)]
mod tests {
    use super::*;

    // -- PromptBase tests ---------------------------------------------------

    #[test]
    fn test_make_prompt_no_choices() {
        let pb = PromptBase::new("Enter name");
        let result = pb.make_prompt();
        assert!(result.contains("Enter name"));
        assert!(result.ends_with(": "));
    }

    #[test]
    fn test_make_prompt_with_choices() {
        let pb = PromptBase::new("Choose").choices(vec!["a".into(), "b".into()]);
        let result = pb.make_prompt();
        assert!(result.contains("Choose"));
        assert!(result.contains("["));
        assert!(result.contains("a/b"));
        assert!(result.contains("]"));
    }

    #[test]
    fn test_render_default() {
        let pb = PromptBase::new("test");
        let rendered = pb.render_default("hello");
        assert!(rendered.contains("hello"));

        let pb_hidden = PromptBase::new("test").show_default(false);
        let rendered_hidden = pb_hidden.render_default("hello");
        assert_eq!(rendered_hidden, "");
    }

    #[test]
    fn test_check_choice_no_choices() {
        let pb = PromptBase::new("test");
        assert!(pb.check_choice("anything"));
    }

    #[test]
    fn test_check_choice_case_insensitive() {
        let pb = PromptBase::new("test")
            .choices(vec!["yes".into(), "no".into()])
            .case_sensitive(false);
        assert!(pb.check_choice("YES"));
        assert!(pb.check_choice("yes"));
        assert!(pb.check_choice("No"));
        assert!(!pb.check_choice("maybe"));
    }

    #[test]
    fn test_check_choice_case_sensitive() {
        let pb = PromptBase::new("test")
            .choices(vec!["Yes".into(), "No".into()])
            .case_sensitive(true);
        assert!(pb.check_choice("Yes"));
        assert!(!pb.check_choice("yes"));
    }

    // -- PromptError tests --------------------------------------------------

    #[test]
    fn test_prompt_error_display() {
        let err = PromptError::InvalidResponse("bad input".into());
        assert_eq!(format!("{}", err), "bad input");

        let err = PromptError::Cancelled;
        assert_eq!(format!("{}", err), "cancelled");

        let io_err = io::Error::new(io::ErrorKind::Other, "oh no");
        let err = PromptError::IOError(io_err);
        let msg = format!("{}", err);
        assert!(msg.contains("I/O error"));
    }

    #[test]
    fn test_prompt_error_source() {
        use std::error::Error;

        let err = PromptError::InvalidResponse("bad".into());
        assert!(err.source().is_none());

        let io_err = io::Error::new(io::ErrorKind::NotFound, "not found");
        let err = PromptError::IOError(io_err);
        assert!(err.source().is_some());
    }

    #[test]
    fn test_from_io_error() {
        let io_err = io::Error::new(io::ErrorKind::Other, "oh no");
        let err: PromptError = io_err.into();
        match err {
            PromptError::IOError(_) => {}
            _ => panic!("expected IOError"),
        }
    }

    // -- Confirm tests ------------------------------------------------------

    #[test]
    fn test_confirm_prompt_text_default_true() {
        let c = Confirm::new("Continue?", true);
        let prompt = c.make_confirm_prompt();
        assert!(prompt.contains("Continue?"));
        assert!(prompt.contains("[Y/n]"));
    }

    #[test]
    fn test_confirm_prompt_text_default_false() {
        let c = Confirm::new("Continue?", false);
        let prompt = c.make_confirm_prompt();
        assert!(prompt.contains("Continue?"));
        assert!(prompt.contains("[y/N]"));
    }

    // -- Select tests -------------------------------------------------------

    #[test]
    fn test_select_render() {
        let s: Select<&str> = Select::new("Pick")
            .choice("Option A", "a")
            .choice("Option B", "b");
        let rendered = s.render();
        assert!(rendered.contains("Pick"));
        assert!(rendered.contains("1) Option A"));
        assert!(rendered.contains("2) Option B"));
        assert!(rendered.contains("Enter number [1-2]"));
    }

    #[test]
    fn test_select_no_choices_error() {
        let s: Select<String> = Select::new("empty");
        let result = s.ask();
        match result {
            Err(PromptError::InvalidResponse(msg)) => {
                assert!(msg.contains("no choices"));
            }
            _ => panic!("expected InvalidResponse for no choices"),
        }
    }

    // -- Prompt builder tests -----------------------------------------------

    #[test]
    fn test_prompt_builder() {
        let p = Prompt::new("Enter value").password(false).show_choices(true);
        let rendered = p.render();
        assert!(rendered.contains("Enter value"));
    }

    #[test]
    fn test_prompt_render_default() {
        let pb = PromptBase::new("Name").show_default(true);
        assert!(pb.render_default("Alice").contains("Alice"));
    }

    // -- Style helper tests -------------------------------------------------

    #[test]
    fn test_apply_style_plain() {
        let result = apply_style("hello", "nonexistent.style");
        assert_eq!(result, "hello");
    }

    #[test]
    fn test_apply_style_with_theme() {
        let result = apply_style("hello", "prompt");
        assert!(result.contains("hello"));
    }

    #[test]
    fn test_apply_raw_style_empty() {
        let s = Style::new();
        let result = apply_raw_style("test", &s);
        assert_eq!(result, "test");
    }
}