thag_rs 0.2.0

A versatile cross-platform playground and REPL for Rust snippets, expressions and programs. Accepts a script file or dynamic options.
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
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
/*[toml]
[dependencies]
clap = "4.5"
thag_rs = { version = "0.2, thag-auto", default-features = false, features = ["build", "simplelog", "tools"] }
thag_styling = { version = "0.2, thag-auto" }
*/

/// Basic prompted front-end to build and run a `thag` command.
//# Purpose: Simplify running `thag`.
//# Categories: cli, interactive, thag_front_ends, tools
use arboard::Clipboard;
use clap::{self, CommandFactory};
use inquire::{set_global_render_config, MultiSelect};
use std::collections::HashMap;
use std::fmt::Write as _; // import without risk of name clashing
use std::process::Command;
use std::string::ToString;
use thag_styling::{
    auto_help, file_navigator, help_system::check_help_and_exit, sprtln, themed_inquire_config,
    Role, Style, Styleable, StyledPrint,
};

// Import the Cli struct from the main crate
use thag_rs::cmd_args::Cli;

file_navigator! {}

#[derive(Debug, Clone)]
struct OptionInfo {
    name: String,
    short: Option<char>,
    long: String,
    help: String,
    takes_value: bool,
    group: Option<String>,
}

#[derive(Debug, Clone)]
struct OptionGroup {
    name: String,
    options: Vec<OptionInfo>,
    multiple: bool,
}

fn get_clap_groups() -> HashMap<String, Vec<String>> {
    let cmd = Cli::command();
    let mut group_members: HashMap<String, Vec<String>> = HashMap::new();

    // Extract clap argument groups
    for group in cmd.get_groups() {
        let group_name = group.get_id().to_string();
        let mut members = Vec::new();

        for arg_id in group.get_args() {
            members.push(arg_id.to_string());
        }

        group_members.insert(group_name, members);
    }

    group_members
}

#[allow(clippy::too_many_lines)]
fn extract_clap_metadata() -> Vec<OptionGroup> {
    let cmd = Cli::command();
    let clap_groups = get_clap_groups();

    // Pre-define logical groups based on the help headings and argument groups
    let mut output_options = Vec::new();
    let mut processing_options = Vec::new();
    let mut dynamic_options = Vec::new();
    let mut filter_options = Vec::new();
    let mut norun_options = Vec::new();
    let mut verbosity_options = Vec::new();

    // Extract all arguments
    for arg in cmd.get_arguments() {
        let option_info = OptionInfo {
            name: arg.get_id().to_string(),
            short: arg.get_short(),
            long: arg.get_long().unwrap_or("").to_string(),
            help: arg.get_help().map_or_else(String::new, ToString::to_string),
            takes_value: arg.get_action().takes_values(),
            group: arg.get_help_heading().map(ToString::to_string),
        };

        // First categorize by help heading, then override with clap groups for mutual exclusivity
        let mut categorized = false;

        // Categorize by help heading first
        match option_info.group.as_deref() {
            Some("Output Options") => {
                output_options.push(option_info.clone());
                categorized = true;
            }
            Some("Processing Options") => {
                processing_options.push(option_info.clone());
                categorized = true;
            }
            Some("Dynamic Options (no script)") => {
                dynamic_options.push(option_info.clone());
                categorized = true;
            }
            Some("Filter Options") => {
                filter_options.push(option_info.clone());
                categorized = true;
            }
            Some("No-run Options") => {
                norun_options.push(option_info.clone());
                categorized = true;
            }
            _ => {}
        }

        // Check if this option belongs to a clap argument group (for mutual exclusivity)
        let mut in_clap_group = false;
        for (group_name, members) in &clap_groups {
            if members.contains(&option_info.name) {
                in_clap_group = true;
                match group_name.as_str() {
                    "commands" => {
                        // Move to dynamic options if not already categorized properly
                        if !categorized
                            || !matches!(
                                option_info.group.as_deref(),
                                Some("Dynamic Options (no script)")
                            )
                        {
                            dynamic_options.push(option_info.clone());
                        }
                    }
                    "verbosity" => {
                        verbosity_options.push(option_info.clone());
                    }
                    "norun_options" => {
                        // Keep in no-run options
                        if !categorized {
                            norun_options.push(option_info.clone());
                        }
                    }
                    _ => {
                        if !categorized {
                            processing_options.push(option_info.clone());
                        }
                    }
                }
                break;
            }
        }

        // If not categorized yet, use fallback logic
        if !categorized && !in_clap_group {
            // Handle verbosity options specially
            if matches!(
                option_info.name.as_str(),
                "verbose" | "quiet" | "normal_verbosity"
            ) {
                verbosity_options.push(option_info);
            } else if !matches!(
                option_info.name.as_str(),
                "script" | "args" | "help" | "version"
            ) {
                // Add other options to processing by default
                processing_options.push(option_info);
            }
        }
    }

    vec![
        OptionGroup {
            name: "Command Type".to_string(),
            options: dynamic_options,
            multiple: false,
        },
        OptionGroup {
            name: "Processing Options".to_string(),
            options: processing_options,
            multiple: true,
        },
        OptionGroup {
            name: "Filter Options".to_string(),
            options: filter_options,
            multiple: true,
        },
        OptionGroup {
            name: "Output Options".to_string(),
            options: output_options,
            multiple: true,
        },
        OptionGroup {
            name: "Verbosity".to_string(),
            options: verbosity_options,
            multiple: false,
        },
        OptionGroup {
            name: "No-run Options".to_string(),
            options: norun_options,
            multiple: true,
        },
    ]
}

fn format_option_display(option: &OptionInfo) -> String {
    let mut display = String::new();

    if let Some(short) = option.short {
        let _ = writeln!(display, "-{}", short);
        if !option.long.is_empty() {
            let _ = writeln!(display, ", --{}", option.long);
        }
    } else if !option.long.is_empty() {
        let _ = writeln!(display, "--{}", option.long);
    }

    if !option.help.is_empty() {
        // Truncate help text to fit better in the display
        let help_text = if option.help.len() > 60 {
            format!("{}...", &option.help[..57])
        } else {
            option.help.clone()
        };
        let _ = writeln!(display, " - {help_text}");
    }

    display
}

fn is_interactive() -> bool {
    use std::io::{self, IsTerminal};
    io::stdin().is_terminal()
}

#[allow(clippy::cognitive_complexity, clippy::too_many_lines)]
fn main() -> Result<(), Box<dyn std::error::Error>> {
    // Check for help first - automatically extracts from source comments
    let help = auto_help!();
    check_help_and_exit(&help);

    set_global_render_config(themed_inquire_config());

    sprtln!(
        Style::for_role(Role::Heading3),
        "🚀 Thag Prompt - Interactive Thag Builder",
    );
    println!("{}\n", "".repeat(41));

    // Check for test mode environment variable
    if let Ok(test_mode) = std::env::var("THAG_PROMPT_TEST") {
        return run_test_mode(&test_mode);
    }

    if !is_interactive() {
        eprintln!("Error: This tool requires an interactive terminal.");
        eprintln!("Please run it directly from a terminal, not through pipes or redirects.");
        eprintln!("Tip: Set THAG_PROMPT_TEST=repl to test REPL mode");
        std::process::exit(1);
    }

    let option_groups = extract_clap_metadata();
    let mut selected_options = Vec::new();
    let mut selected_values = HashMap::new();

    // Step 1: Ask user to choose between dynamic mode or script mode
    let mode_choice = Select::new(
        "Choose mode:",
        vec![
            "Dynamic mode (no script needed)",
            "Script mode (run a script file)",
        ],
    )
    .with_help_message("Dynamic mode: expressions, REPL, filters, etc. Script mode: run .rs files")
    .prompt()?;

    let (script_path, use_dynamic_mode) = if mode_choice == "Dynamic mode (no script needed)" {
        (None, true)
    } else {
        // Script mode - select a file
        let mut navigator = FileNavigator::new();
        sprtln!(
            Style::for_role(Role::Emphasis),
            "\nStep: Select a script file"
        );

        if let Ok(path) = select_file(&mut navigator, Some("rs"), false) {
            (Some(path), false)
        } else {
            println!("No file selected. Exiting.");
            return Ok(());
        }
    };

    // Step 2: If dynamic mode, select the dynamic option
    if use_dynamic_mode {
        let dynamic_group = option_groups
            .iter()
            .find(|g| g.name == "Command Type")
            .unwrap();

        eprintln!("dynamic_group={dynamic_group:#?}");

        if !dynamic_group.options.is_empty() {
            let dynamic_choices: Vec<&OptionInfo> = dynamic_group
                .options
                .iter()
                .filter(|v| v.name != "script")
                .collect();

            let dynamic_choice_names: Vec<String> = dynamic_choices
                .iter()
                .copied()
                .map(format_option_display)
                .collect();

            if let Ok(choice) = Select::new("Select dynamic option:", dynamic_choice_names.clone())
                .with_help_message("Choose what type of dynamic execution you want")
                .prompt()
            {
                let idx = dynamic_choice_names
                    .iter()
                    .position(|c| c == &choice)
                    .unwrap();
                let selected_option = &dynamic_choices[idx];
                dbg!(&selected_option.name);
                selected_options.push(selected_option.name.clone());

                // Handle options that take values
                match selected_option.name.as_str() {
                    "expression" => {
                        let expr = Text::new("Enter Rust expression:")
                            .with_help_message(r#"e.g. 5 + 3, "Hi", println!("Hello world!");, std::env::args().collect::<Vec<_>>(), '(1..=20).product::<usize>()' "#)
                            .prompt()?;
                        selected_values.insert(selected_option.name.clone(), expr);
                    }
                    "filter" => {
                        let filter = Text::new("Enter filter expression:")
                            .with_help_message(r#"e.g. line.contains("error"), line.len() > 10"#)
                            .prompt()?;
                        selected_values.insert(selected_option.name.clone(), filter);
                    }
                    _ => {}
                }
            }
        }
    }

    // Step 3: Select other options
    for group in &option_groups {
        if group.name == "Command Type" || group.name == "Output Options" {
            continue; // Already handled
        }

        // Skip Filter Options if filter is not selected
        if group.name == "Filter Options" && !selected_options.contains(&"filter".to_string()) {
            continue;
        }

        // Handle verbosity specially - it's a single choice with count options
        if group.name == "Verbosity" {
            let verbosity_choices = vec![
                "Default: Normal verbosity (-n)",
                "Verbose (-v)",
                "Debug (-vv)",
                "Quiet (-q)",
                "Very quiet (-qq)",
            ];

            if let Ok(Some(selection)) = Select::new("Select verbosity level:", verbosity_choices)
                .with_help_message("Choose output verbosity level")
                .prompt_skippable()
            {
                match selection {
                    "Verbose (-v)" => {
                        selected_options.push("verbose".to_string());
                        selected_values.insert("verbose".to_string(), "1".to_string());
                    }
                    "Debug (-vv)" => {
                        selected_options.push("verbose".to_string());
                        selected_values.insert("verbose".to_string(), "2".to_string());
                    }
                    "Quiet (-q)" => {
                        selected_options.push("quiet".to_string());
                        selected_values.insert("quiet".to_string(), "1".to_string());
                    }
                    "Very quiet (-qq)" => {
                        selected_options.push("quiet".to_string());
                        selected_values.insert("quiet".to_string(), "2".to_string());
                    }
                    "Normal verbosity" => {
                        selected_options.push("normal_verbosity".to_string());
                    }
                    _ => {}
                }
            }
            continue;
        }

        // Handle input and environment setup (thag_prompt-specific features)
        if group.name == "Processing Options" {
            let choices: Vec<String> = group.options.iter().map(format_option_display).collect();

            // Add input file and environment variable options to the choices
            let mut extended_choices = choices.clone();
            extended_choices.push("📁 Input file (pipe from file)".to_string());
            extended_choices.push("🌍 Environment variables".to_string());

            if let Ok(Some(selections)) =
                MultiSelect::new(&format!("Select {}:", group.name), extended_choices.clone())
                    .with_help_message("Use space to select, enter to confirm, ESC to skip")
                    .prompt_skippable()
            {
                for selection in selections {
                    if selection == "📁 Input file (pipe from file)" {
                        let input_file = Text::new("Input file to pipe to stdin:")
                            .with_help_message(
                                "File path (e.g. data.txt) - alternative to shell redirection",
                            )
                            .prompt()?;
                        selected_options.push("input_file".to_string());
                        selected_values.insert("input_file".to_string(), input_file);
                    } else if selection == "🌍 Environment variables" {
                        let env_vars =
                            Text::new("Environment variables (KEY=VALUE, comma-separated):")
                                .with_help_message(
                                    "e.g. RUST_LOG=debug,MY_VAR=$PWD (supports $VAR expansion)",
                                )
                                .prompt()?;
                        selected_options.push("env_vars".to_string());
                        selected_values.insert("env_vars".to_string(), env_vars);
                    } else {
                        let idx = choices.iter().position(|c| c == &selection).unwrap();
                        let selected_option = &group.options[idx];
                        selected_options.push(selected_option.name.clone());

                        // Handle options that take values
                        if selected_option.takes_value {
                            match selected_option.name.as_str() {
                                "features" => {
                                    let features =
                                        Text::new("Enter features (comma-separated):").prompt()?;
                                    selected_values.insert(selected_option.name.clone(), features);
                                }
                                "infer" => {
                                    let infer_options = ["none", "min", "config", "max"];
                                    let infer_choice = Select::new(
                                        "Dependency inference level:",
                                        infer_options.to_vec(),
                                    )
                                    .prompt()?;
                                    selected_values.insert(
                                        selected_option.name.clone(),
                                        infer_choice.to_string(),
                                    );
                                }
                                _ => {}
                            }
                        }
                    }
                }
            }
            continue;
        }

        if group.options.is_empty() {
            continue;
        }

        let choices: Vec<String> = group.options.iter().map(format_option_display).collect();

        if group.multiple {
            if let Ok(Some(selections)) =
                MultiSelect::new(&format!("Select {}:", group.name), choices.clone())
                    .with_help_message("Use space to select, enter to confirm, ESC to skip")
                    .prompt_skippable()
            {
                for selection in selections {
                    let idx = choices.iter().position(|c| c == &selection).unwrap();
                    let selected_option = &group.options[idx];
                    selected_options.push(selected_option.name.clone());

                    // Handle options that take values
                    if selected_option.takes_value {
                        match selected_option.name.as_str() {
                            "features" => {
                                let features =
                                    Text::new("Enter features (comma-separated):").prompt()?;
                                selected_values.insert(selected_option.name.clone(), features);
                            }
                            "infer" => {
                                let infer_options = ["none", "min", "config", "max"];
                                let infer_choice = Select::new(
                                    "Dependency inference level:",
                                    infer_options.to_vec(),
                                )
                                .prompt()?;
                                selected_values
                                    .insert(selected_option.name.clone(), infer_choice.to_string());
                            }
                            "toml" => {
                                let toml_input =
                                    Text::new("Enter manifest info (Cargo.toml format):")
                                        .with_help_message(
                                            r#"e.g. [dependencies]
serde = "1.0""#,
                                        )
                                        .prompt()?;
                                selected_values.insert(selected_option.name.clone(), toml_input);
                            }
                            "begin" => {
                                let begin_input = Text::new("Enter pre-loop Rust statements:")
                                    .with_help_message("e.g. let mut count = 0;")
                                    .prompt()?;
                                selected_values.insert(selected_option.name.clone(), begin_input);
                            }
                            "end" => {
                                let end_input = Text::new("Enter post-loop Rust statements:")
                                    .with_help_message("e.g. println!(\"Total: {}\", count);")
                                    .prompt()?;
                                selected_values.insert(selected_option.name.clone(), end_input);
                            }
                            _ => {}
                        }
                    }
                }
            } else if let Ok(Some(selection)) =
                Select::new(&format!("Select {}:", group.name), choices.clone())
                    .with_help_message("Press ESC to skip")
                    .prompt_skippable()
            {
                let idx = choices.iter().position(|c| c == &selection).unwrap();
                let selected_option = &group.options[idx];
                selected_options.push(selected_option.name.clone());

                // Handle options that take values
                if selected_option.takes_value {
                    match selected_option.name.as_str() {
                        "filter" => {
                            let filter = Text::new("Enter filter expression:")
                                .with_help_message("e.g. line.contains(\"error\"), line.len() > 10")
                                .prompt()?;
                            selected_values.insert(selected_option.name.clone(), filter);
                        }
                        "toml" => {
                            let toml_input = Text::new("Enter manifest info (Cargo.toml format):")
                                .with_help_message("e.g. [dependencies]\nserde = \"1.0\"")
                                .prompt()?;
                            selected_values.insert(selected_option.name.clone(), toml_input);
                        }
                        "begin" => {
                            let begin_input = Text::new("Enter pre-loop Rust statements:")
                                .with_help_message("e.g. let mut count = 0;")
                                .prompt()?;
                            selected_values.insert(selected_option.name.clone(), begin_input);
                        }
                        "end" => {
                            let end_input = Text::new("Enter post-loop Rust statements:")
                                .with_help_message("e.g. println!(\"Total: {}\", count);")
                                .prompt()?;
                            selected_values.insert(selected_option.name.clone(), end_input);
                        }
                        "features" => {
                            let features =
                                Text::new("Enter features (comma-separated):").prompt()?;
                            selected_values.insert(selected_option.name.clone(), features);
                        }
                        "infer" => {
                            let infer_options = ["none", "min", "config", "max"];
                            let infer_choice =
                                Select::new("Dependency inference level:", infer_options.to_vec())
                                    .prompt()?;
                            selected_values
                                .insert(selected_option.name.clone(), infer_choice.to_string());
                        }
                        _ => {}
                    }
                }
            }
        }
    }

    // Step 4: Handle script arguments if script is selected
    let script_args = if script_path.is_some() {
        if let Ok(Some(args_input)) = Text::new("Enter script arguments (optional):")
            .with_help_message("Arguments to pass to the script (-- will be added automatically)")
            .prompt_skippable()
        {
            if args_input.trim().is_empty() {
                Vec::new()
            } else {
                let mut args = vec!["--".to_string()];
                args.extend(args_input.split_whitespace().map(ToString::to_string));
                args
            }
        } else {
            Vec::new()
        }
    } else {
        Vec::new()
    };

    // Step 5: Handle additional input and environment options
    let mut input_file_option = None;
    let mut env_vars_option = None;

    // Ask for input file if not already selected
    if !selected_values.contains_key("input_file") {
        if let Ok(Some(input_file)) = Text::new("Input file (optional):")
            .with_help_message("File to pipe to stdin (leave empty to skip)")
            .prompt_skippable()
        {
            if !input_file.trim().is_empty() {
                input_file_option = Some(input_file);
            }
        }
    }

    // Ask for environment variables if not already selected
    if !selected_values.contains_key("env_vars") {
        if let Ok(Some(env_vars)) = Text::new("Environment variables (optional):")
            .with_help_message("KEY=VALUE pairs, comma-separated (supports $VAR expansion)")
            .prompt_skippable()
        {
            if !env_vars.trim().is_empty() {
                env_vars_option = Some(env_vars);
            }
        }
    }

    // Step 6: Ask about output format
    let output_choices = vec![
        "Execute command",
        "Copy command to clipboard",
        "Print command to stdout",
    ];

    let output_choice = Select::new("How would you like to proceed?", output_choices)
        .with_help_message("Choose execution method")
        .prompt()?;

    // Step 7: Build the command
    let mut cmd = Command::new("thag");

    // eprintln!("selected_options={selected_options:#?}");

    // Add selected options as arguments
    for option in &selected_options {
        match option.as_str() {
            "expression" => {
                cmd.arg("-e");
                if let Some(expr) = selected_values.get(option) {
                    eprintln!("expr={expr}");
                    // cmd.arg(expr);
                    // cmd.arg(expr.strip_prefix("'").unwrap_or(expr).strip_suffix("'"));
                    cmd.arg(expr.trim_matches('\''));
                }
            }
            "filter" => {
                cmd.arg("-l");
                if let Some(filter) = selected_values.get(option) {
                    cmd.arg(filter);
                }
            }
            "toml" => {
                cmd.arg("-M");
                if let Some(toml_val) = selected_values.get(option) {
                    cmd.arg(toml_val);
                }
            }
            "begin" => {
                cmd.arg("-B");
                if let Some(begin_val) = selected_values.get(option) {
                    cmd.arg(begin_val);
                }
            }
            "end" => {
                cmd.arg("-E");
                if let Some(end_val) = selected_values.get(option) {
                    cmd.arg(end_val);
                }
            }
            "repl" => {
                cmd.arg("-r");
            }
            "stdin" => {
                cmd.arg("-s");
            }
            "edit" => {
                cmd.arg("-d");
            }
            "config" => {
                cmd.arg("-C");
            }
            "verbose" => {
                if let Some(count) = selected_values.get(option) {
                    let count: u8 = count.parse().unwrap_or(1);
                    // for _ in 0..count {
                    //     cmd.arg("--verbose");
                    // }
                    if count > 1 {
                        cmd.arg("-vv");
                    }
                } else {
                    cmd.arg("-v");
                }
            }
            "quiet" => {
                if let Some(count) = selected_values.get(option) {
                    let count: u8 = count.parse().unwrap_or(1);
                    // for _ in 0..count {
                    //     cmd.arg("--quiet");
                    // }
                    if count > 1 {
                        cmd.arg("-qq");
                    }
                } else {
                    cmd.arg("-q");
                }
            }
            "normal_verbosity" => {
                cmd.arg("-n");
            }
            "force" => {
                cmd.arg("-f");
            }
            "generate" => {
                cmd.arg("-g");
            }
            "build" => {
                cmd.arg("-b");
            }
            "check" => {
                cmd.arg("-c");
            }
            "executable" => {
                cmd.arg("-x");
            }
            "expand" => {
                cmd.arg("-X");
            }
            "cargo" => {
                cmd.arg("-A");
            }
            "test_only" => {
                cmd.arg("-T");
            }
            "multimain" => {
                cmd.arg("-m");
            }
            "timings" => {
                cmd.arg("-t");
            }
            "features" => {
                cmd.arg("--features");
                if let Some(features) = selected_values.get(option) {
                    cmd.arg(features);
                }
            }
            "infer" => {
                cmd.arg("-i");
                if let Some(infer) = selected_values.get(option) {
                    cmd.arg(infer);
                }
            }
            "unquote" => {
                cmd.arg("-u");
            }
            _ => {} // Handle other options as needed
        }
    }

    // Add script path if selected
    if let Some(script) = script_path {
        cmd.arg(script);
    }

    // Add script arguments
    if !script_args.is_empty() {
        cmd.args(&script_args);
    }

    // Handle input file` - either from selection or prompt
    let input_file_path = selected_values
        .get("input_file")
        .cloned()
        .or(input_file_option);
    let input_file_info = input_file_path
        .as_ref()
        .map(|input_file| format!(" < {}", input_file));

    // Handle environment variables - either from selection or prompt
    let env_input = selected_values.get("env_vars").cloned().or(env_vars_option);
    let mut env_vars_display = Vec::new();

    if let Some(env_input) = &env_input {
        for env_pair in env_input.split(',') {
            let env_pair = env_pair.trim();
            if let Some((key, value)) = env_pair.split_once('=') {
                let expanded_value = expand_env_vars(value.trim());
                env_vars_display.push(format!("{}={}", key.trim(), expanded_value));
            } else {
                eprintln!("Warning: Invalid environment variable format: {}", env_pair);
                eprintln!("Expected format: KEY=VALUE");
            }
        }
    }

    let env_vars_info = if env_vars_display.is_empty() {
        None
    } else {
        Some(format!(" (env: {})", env_vars_display.join(", ")))
    };

    // Build command display string
    let mut cmd_display = format_command_display(&cmd);
    if let Some(input_info) = input_file_info {
        cmd_display.push_str(&input_info);
    }
    if let Some(env_info) = env_vars_info {
        cmd_display.push_str(&env_info);
    }

    // Handle environment variables prefix for shell execution
    let env_prefix = if env_vars_display.is_empty() {
        String::new()
    } else {
        env_vars_display.join(" ")
    };

    match output_choice {
        "Execute command" => {
            // Set up stdin redirection if specified
            if let Some(input_file) = input_file_path {
                use std::fs::File;
                use std::process::Stdio;

                let file = File::open(&input_file)
                    .map_err(|e| format!("Failed to open input file '{}': {}", input_file, e))?;
                cmd.stdin(Stdio::from(file));
            }

            // Set environment variables
            if let Some(env_input) = env_input {
                for env_pair in env_input.split(',') {
                    let env_pair = env_pair.trim();
                    if let Some((key, value)) = env_pair.split_once('=') {
                        let expanded_value = expand_env_vars(value.trim());
                        cmd.env(key.trim(), expanded_value);
                    }
                }
            }

            "\nRunning:".heading3().bold().println();
            cmd_display.code().println();

            let status = cmd.status()?;

            if !status.success() {
                sprtln!(
                    Style::for_role(Role::Error),
                    "\nError: Command failed with exit code: {:?}",
                    status.code()
                );
            }
        }
        "Copy command to clipboard" => {
            let shell_command = format!("{}{}", env_prefix, cmd_display);
            sprtln!(
                Style::for_role(Role::Info),
                "\nInfo: Command copied to clipboard:",
            );
            sprtln!(Style::for_role(Role::Code), "{shell_command}");

            // Try to copy to clipboard (cross-platform)
            if let Err(e) = copy_to_clipboard(&shell_command) {
                sprtln!(
                    Style::for_role(Role::Warning),
                    "Warning: Failed to copy to clipboard: {e}"
                );
                println!("Please copy the command above manually.");
            }
        }
        "Print command to stdout" => {
            let shell_command = format!("{}{}", env_prefix, cmd_display);
            sprtln!(Style::for_role(Role::Code), "{shell_command}");
        }
        _ => {}
    }

    Ok(())
}

#[allow(clippy::too_many_lines)]
fn run_test_mode(test_mode: &str) -> Result<(), Box<dyn std::error::Error>> {
    println!("Running in test mode: {test_mode}");

    let mut cmd = Command::new("thag");

    match test_mode {
        "repl" => {
            cmd.arg("--repl");
        }
        "expr" => {
            cmd.arg("--expr").arg("2 + 2");
        }
        "expr_string" => {
            cmd.arg("--expr").arg(r#""Hello world""#);
        }
        "expr_complex" => {
            cmd.arg("--expr")
                .arg("std::env::args().collect::<Vec<_>>()");
        }
        "stdin" => {
            cmd.arg("--stdin");
        }
        "script_with_args" => {
            cmd.arg("demo/hello.rs")
                .arg("--")
                .arg("--name")
                .arg("World")
                .arg("--verbose");
        }
        "filter_simple" => {
            cmd.arg("--loop").arg("line.len() > 3");
        }
        "filter_with_options" => {
            cmd.arg("--loop")
                .arg("if line.len() > 3 { count += 1; true } else { false }")
                .arg("--begin")
                .arg("let mut count = 0;")
                .arg("--end")
                .arg(r#"println!("Total: {}", count);"#)
                .arg("--toml")
                .arg(
                    r#"[dependencies]
regex = "1.11""#,
                );
        }
        "debug_groups" => {
            // Test the option grouping
            let option_groups = extract_clap_metadata();
            println!("=== DEBUG: Option Groups ===");
            for group in &option_groups {
                println!("Group: {} (multiple: {})", group.name, group.multiple);
                for option in &group.options {
                    println!(
                        "  - {}: takes_value={}, help={}",
                        option.name, option.takes_value, option.help
                    );
                }
                println!();
            }
            return Ok(());
        }
        "test_input_file" => {
            // Simulate selecting input file and env vars
            let mut test_values = HashMap::new();
            test_values.insert("input_file".to_string(), "demo/hello.rs".to_string());
            test_values.insert(
                "env_vars".to_string(),
                "TEST_VAR=hello,DEBUG=$PWD".to_string(),
            );

            cmd.arg("--loop").arg("line.len() > 0");

            // Apply input file
            if let Some(input_file) = test_values.get("input_file") {
                use std::fs::File;
                use std::process::Stdio;
                let file = File::open(input_file)?;
                cmd.stdin(Stdio::from(file));
            }

            // Apply env vars with expansion
            if let Some(env_input) = test_values.get("env_vars") {
                for env_pair in env_input.split(',') {
                    let env_pair = env_pair.trim();
                    if let Some((key, value)) = env_pair.split_once('=') {
                        let expanded_value = expand_env_vars(value.trim());
                        cmd.env(key.trim(), expanded_value);
                    }
                }
            }
        }
        "test_env_vars" => {
            cmd.arg("--expr")
                .arg(r#"std::env::var("CUSTOM_VAR").unwrap_or_else(|_| "not set".to_string())"#)
                .env("CUSTOM_VAR", "hello_world")
                .env("DEBUG", "1");
        }
        "test_env_expansion" => {
            // Test environment variable expansion like $PWD
            std::env::set_var("TEST_EXPAND", "expanded_value");
            cmd.arg("--expr")
                .arg("println!(\"Environment variable resolved\")")
                .env("SIMPLE_VAR", expand_env_vars("$PWD"))
                .env(
                    "COMPLEX_VAR",
                    expand_env_vars("prefix_${TEST_EXPAND}_suffix"),
                );
        }
        "test_display_enhanced" => {
            // Test enhanced command display with input file and env vars
            cmd.arg("--loop").arg("line.contains(\"hello\")");

            // Simulate input file redirection
            if let Ok(file) = std::fs::File::open("demo/hello.rs") {
                cmd.stdin(std::process::Stdio::from(file));
            }

            // Add environment variables
            cmd.env("RUST_LOG", "debug");
            cmd.env("MY_PATH", "/custom/path");

            // This would show: thag --loop 'line.contains("hello")' < demo/hello.rs (env: RUST_LOG=debug, MY_PATH=/custom/path)
        }
        "test_verbosity_double" => {
            cmd.arg("--expr")
                .arg("println!(\"Testing debug verbosity\")")
                .arg("--verbose")
                .arg("--verbose"); // Test -vv
        }
        "test_no_script_args" => {
            cmd.arg("demo/hello.rs");
            // Test that no -- is added when script_args is empty
        }
        "test_clipboard" => {
            // Test clipboard functionality
            let test_text = "thag --expr 'println!(\"Hello from clipboard test!\")'";
            match copy_to_clipboard(test_text) {
                Ok(()) => println!("Clipboard test successful"),
                Err(e) => println!("Clipboard test failed: {}", e),
            }
            return Ok(());
        }
        _ => {
            eprintln!("Unknown test mode: {}", test_mode);
            eprintln!(
                "Available modes: repl, expr, expr_string, expr_complex, stdin, script_with_args, filter_simple, filter_with_options, debug_groups, test_input_file, test_env_vars, test_env_expansion, test_verbosity_double, test_no_script_args, test_display_enhanced"
            );
            std::process::exit(1);
        }
    }

    let cmd_display = format_command_display(&cmd);
    println!("Would execute: {}", cmd_display);

    Ok(())
}

/// Copy text to clipboard using arboard (cross-platform)
fn copy_to_clipboard(text: &str) -> Result<(), Box<dyn std::error::Error>> {
    let mut clipboard = Clipboard::new()?;
    clipboard.set_text(text)?;
    Ok(())
}

/// Expand environment variables in a string (e.g., $PWD, ${HOME})
fn expand_env_vars(input: &str) -> String {
    let mut result = input.to_string();

    // Handle ${VAR} format
    while let Some(start) = result.find("${") {
        if let Some(end) = result[start..].find('}') {
            let var_name = &result[start + 2..start + end];
            let replacement = std::env::var(var_name).unwrap_or_else(|_| {
                eprintln!(
                    "Warning: Environment variable '{}' not found, using empty string",
                    var_name
                );
                String::new()
            });
            result.replace_range(start..=(start + end), &replacement);
        } else {
            break; // Malformed ${...} - stop processing
        }
    }

    // Handle $VAR format (stops at word boundaries)
    let re = regex::Regex::new(r"\$([A-Za-z_][A-Za-z0-9_]*)").unwrap();
    let result = re.replace_all(&result, |caps: &regex::Captures| {
        let var_name = &caps[1];
        std::env::var(var_name).unwrap_or_else(|_| {
            eprintln!(
                "Warning: Environment variable '{}' not found, using empty string",
                var_name
            );
            String::new()
        })
    });

    result.to_string()
}

fn format_command_display(cmd: &Command) -> String {
    let mut display = String::from("thag");

    for arg in cmd.get_args() {
        let arg_str = arg.to_string_lossy();
        display.push(' ');

        // eprintln!("arg_str={arg_str}");

        // Quote arguments that contain spaces or special characters
        let in_single_quotes = arg_str.starts_with('\'') && arg_str.ends_with('\'');
        if in_single_quotes {
            // let arg_str = arg_str.trim_matches('\'');
            let _ = writeln!(display, "'{arg_str}'");
            // eprintln!("1. display={display}");
        } else if arg_str.contains(' ') || arg_str.contains('"') || arg_str.contains('\'') {
            display.push('\'');
            display.push_str(&arg_str.replace('\'', r#"'"'"'"#));
            display.push('\'');
            // eprintln!("2. display={display}");
        } else {
            let _ = writeln!(display, "'{arg_str}'");
            // eprintln!("3. display={display}");
        }
    }

    display
}