rusty-commit 1.0.27

Rust-powered AI commit message generator - Write impressive commits in seconds
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
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
use anyhow::Result;
use colored::Colorize;
use dialoguer::{Confirm, Input, Select};

use crate::cli::SetupCommand;
use crate::config::Config;

/// Provider option for the setup wizard
struct ProviderOption {
    name: &'static str,
    display: &'static str,
    default_model: &'static str,
    requires_key: bool,
    category: ProviderCategory,
}

#[derive(Clone, Copy, PartialEq)]
enum ProviderCategory {
    Popular,
    Local,
    Cloud,
    Enterprise,
    Specialized,
}

impl ProviderOption {
    fn all() -> Vec<Self> {
        vec![
            // ═════════════════════════════════════════════════════════════════
            // Popular providers
            // ═════════════════════════════════════════════════════════════════
            ProviderOption {
                name: "openai",
                display: "OpenAI (GPT-4o, GPT-4o-mini, GPT-5)",
                default_model: "gpt-4o-mini",
                requires_key: true,
                category: ProviderCategory::Popular,
            },
            ProviderOption {
                name: "anthropic",
                display: "Anthropic (Claude 3.5/4 Sonnet, Haiku, Opus)",
                default_model: "claude-3-5-haiku-20241022",
                requires_key: true,
                category: ProviderCategory::Popular,
            },
            ProviderOption {
                name: "gemini",
                display: "Google Gemini (2.5 Flash, 2.5 Pro)",
                default_model: "gemini-2.5-flash",
                requires_key: true,
                category: ProviderCategory::Popular,
            },
            // ═════════════════════════════════════════════════════════════════
            // Local/Self-hosted
            // ═════════════════════════════════════════════════════════════════
            ProviderOption {
                name: "ollama",
                display: "Ollama (Local models - free, private)",
                default_model: "llama3.2",
                requires_key: false,
                category: ProviderCategory::Local,
            },
            ProviderOption {
                name: "lmstudio",
                display: "LM Studio (Local GUI for LLMs)",
                default_model: "local-model",
                requires_key: false,
                category: ProviderCategory::Local,
            },
            ProviderOption {
                name: "llamacpp",
                display: "llama.cpp (Local inference)",
                default_model: "local-model",
                requires_key: false,
                category: ProviderCategory::Local,
            },
            // ═════════════════════════════════════════════════════════════════
            // Cloud providers - Fast Inference
            // ═════════════════════════════════════════════════════════════════
            ProviderOption {
                name: "groq",
                display: "Groq (Ultra-fast inference)",
                default_model: "llama-3.3-70b-versatile",
                requires_key: true,
                category: ProviderCategory::Cloud,
            },
            ProviderOption {
                name: "cerebras",
                display: "Cerebras (Fast inference)",
                default_model: "llama-3.3-70b",
                requires_key: true,
                category: ProviderCategory::Cloud,
            },
            ProviderOption {
                name: "sambanova",
                display: "SambaNova (Fast inference)",
                default_model: "Meta-Llama-3.3-70B-Instruct",
                requires_key: true,
                category: ProviderCategory::Cloud,
            },
            ProviderOption {
                name: "nebius",
                display: "Nebius (GPU cloud inference)",
                default_model: "meta-llama/Llama-3.3-70B-Instruct",
                requires_key: true,
                category: ProviderCategory::Cloud,
            },
            // ═════════════════════════════════════════════════════════════════
            // Cloud providers - General
            // ═════════════════════════════════════════════════════════════════
            ProviderOption {
                name: "xai",
                display: "xAI (Grok)",
                default_model: "grok-2",
                requires_key: true,
                category: ProviderCategory::Cloud,
            },
            ProviderOption {
                name: "deepseek",
                display: "DeepSeek (V3, R1 Reasoner)",
                default_model: "deepseek-chat",
                requires_key: true,
                category: ProviderCategory::Cloud,
            },
            ProviderOption {
                name: "openrouter",
                display: "OpenRouter (Access 100+ models)",
                default_model: "anthropic/claude-3.5-haiku",
                requires_key: true,
                category: ProviderCategory::Cloud,
            },
            ProviderOption {
                name: "mistral",
                display: "Mistral AI",
                default_model: "mistral-small-latest",
                requires_key: true,
                category: ProviderCategory::Cloud,
            },
            ProviderOption {
                name: "perplexity",
                display: "Perplexity AI",
                default_model: "sonar",
                requires_key: true,
                category: ProviderCategory::Cloud,
            },
            ProviderOption {
                name: "together",
                display: "Together AI",
                default_model: "meta-llama/Llama-3.3-70B-Instruct-Turbo",
                requires_key: true,
                category: ProviderCategory::Cloud,
            },
            ProviderOption {
                name: "fireworks",
                display: "Fireworks AI",
                default_model: "accounts/fireworks/models/llama-v3p3-70b-instruct",
                requires_key: true,
                category: ProviderCategory::Cloud,
            },
            ProviderOption {
                name: "replicate",
                display: "Replicate",
                default_model: "meta/meta-llama-3-70b-instruct",
                requires_key: true,
                category: ProviderCategory::Cloud,
            },
            // ═════════════════════════════════════════════════════════════════
            // Enterprise
            // ═════════════════════════════════════════════════════════════════
            ProviderOption {
                name: "azure",
                display: "Azure OpenAI",
                default_model: "gpt-4o",
                requires_key: true,
                category: ProviderCategory::Enterprise,
            },
            ProviderOption {
                name: "bedrock",
                display: "AWS Bedrock",
                default_model: "anthropic.claude-3-haiku-20240307-v1:0",
                requires_key: true,
                category: ProviderCategory::Enterprise,
            },
            ProviderOption {
                name: "vertex",
                display: "Google Vertex AI",
                default_model: "gemini-2.5-flash-001",
                requires_key: true,
                category: ProviderCategory::Enterprise,
            },
            ProviderOption {
                name: "cohere",
                display: "Cohere",
                default_model: "command-r",
                requires_key: true,
                category: ProviderCategory::Enterprise,
            },
            ProviderOption {
                name: "ai21",
                display: "AI21 Labs (Jamba)",
                default_model: "jamba-1.5-mini",
                requires_key: true,
                category: ProviderCategory::Enterprise,
            },
            // ═════════════════════════════════════════════════════════════════
            // China-based Providers
            // ═════════════════════════════════════════════════════════════════
            ProviderOption {
                name: "siliconflow",
                display: "SiliconFlow (China)",
                default_model: "deepseek-ai/DeepSeek-V3",
                requires_key: true,
                category: ProviderCategory::Cloud,
            },
            ProviderOption {
                name: "zhipu",
                display: "Zhipu AI / ChatGLM (China)",
                default_model: "glm-4-flash",
                requires_key: true,
                category: ProviderCategory::Cloud,
            },
            ProviderOption {
                name: "moonshot",
                display: "Moonshot AI / Kimi (China)",
                default_model: "moonshot-v1-8k",
                requires_key: true,
                category: ProviderCategory::Cloud,
            },
            // ═════════════════════════════════════════════════════════════════
            // Specialized Providers
            // ═════════════════════════════════════════════════════════════════
            ProviderOption {
                name: "jina",
                display: "Jina AI (Embeddings & LLMs)",
                default_model: "jina-embeddings-v3",
                requires_key: true,
                category: ProviderCategory::Specialized,
            },
            ProviderOption {
                name: "helicone",
                display: "Helicone (LLM Observability)",
                default_model: "gpt-4o-mini",
                requires_key: true,
                category: ProviderCategory::Specialized,
            },
        ]
    }

    #[allow(dead_code)]
    fn by_name(name: &str) -> Option<Self> {
        Self::all().into_iter().find(|p| p.name == name)
    }
}

/// Commit format options
#[derive(Clone, Copy)]
enum CommitFormat {
    Conventional,
    Gitmoji,
    Simple,
}

impl CommitFormat {
    fn display(&self) -> &'static str {
        match self {
            CommitFormat::Conventional => "Conventional Commits (feat:, fix:, docs:, etc.)",
            CommitFormat::Gitmoji => "GitMoji (✨ feat:, 🐛 fix:, 📝 docs:, etc.)",
            CommitFormat::Simple => "Simple (no prefix)",
        }
    }

    fn as_str(&self) -> &'static str {
        match self {
            CommitFormat::Conventional => "conventional",
            CommitFormat::Gitmoji => "gitmoji",
            CommitFormat::Simple => "simple",
        }
    }

    fn all() -> Vec<Self> {
        vec![
            CommitFormat::Conventional,
            CommitFormat::Gitmoji,
            CommitFormat::Simple,
        ]
    }
}

/// Language options
struct LanguageOption {
    code: &'static str,
    display: &'static str,
}

impl LanguageOption {
    fn all() -> Vec<Self> {
        vec![
            LanguageOption {
                code: "en",
                display: "English",
            },
            LanguageOption {
                code: "zh",
                display: "Chinese (中文)",
            },
            LanguageOption {
                code: "es",
                display: "Spanish (Español)",
            },
            LanguageOption {
                code: "fr",
                display: "French (Français)",
            },
            LanguageOption {
                code: "de",
                display: "German (Deutsch)",
            },
            LanguageOption {
                code: "ja",
                display: "Japanese (日本語)",
            },
            LanguageOption {
                code: "ko",
                display: "Korean (한국어)",
            },
            LanguageOption {
                code: "ru",
                display: "Russian (Русский)",
            },
            LanguageOption {
                code: "pt",
                display: "Portuguese (Português)",
            },
            LanguageOption {
                code: "it",
                display: "Italian (Italiano)",
            },
            LanguageOption {
                code: "other",
                display: "Other (specify)",
            },
        ]
    }
}

pub async fn execute(cmd: SetupCommand) -> Result<()> {
    print_welcome_header();

    // Determine if we're doing quick or advanced setup
    let is_advanced = if cmd.defaults {
        // Non-interactive defaults mode
        return apply_defaults().await;
    } else if cmd.advanced {
        true
    } else {
        // Ask user which mode they prefer
        println!();
        println!("{}", "Choose your setup mode:".bold());
        println!();

        let modes = vec![
            "🚀 Quick Setup - Just the essentials (recommended)",
            "⚙️  Advanced Setup - Full configuration options",
        ];

        let selection = Select::new()
            .with_prompt("Select mode")
            .items(&modes)
            .default(0)
            .interact()?;

        selection == 1
    };

    if is_advanced {
        run_advanced_setup().await
    } else {
        run_quick_setup().await
    }
}

fn print_welcome_header() {
    println!();
    println!(
        "{} {}",
        "🚀".green(),
        "Welcome to Rusty Commit Setup!".bold().white()
    );
    println!();
    println!(
        "{}",
        "   Let's get you set up with AI-powered commit messages.".dimmed()
    );
    println!();
}

async fn run_quick_setup() -> Result<()> {
    let mut config = Config::load()?;

    // Step 1: Provider selection
    let provider = select_provider_quick()?;
    config.ai_provider = Some(provider.name.to_string());
    config.model = Some(provider.default_model.to_string());

    // Step 2: API key (if needed)
    if provider.requires_key {
        let api_key = prompt_for_api_key(provider.name)?;
        if !api_key.is_empty() {
            config.api_key = Some(api_key);
        }
    } else {
        println!();
        println!(
            "{} {} doesn't require an API key - great for privacy!",
            "ℹ️".blue(),
            provider.name.bright_cyan()
        );
    }

    // Step 3: Commit format
    let format = select_commit_format()?;
    config.commit_type = Some(format.as_str().to_string());
    config.emoji = Some(matches!(format, CommitFormat::Gitmoji));

    // Save configuration
    config.save()?;

    print_completion_message(&config, false);
    Ok(())
}

async fn run_advanced_setup() -> Result<()> {
    let mut config = Config::load()?;

    // Section 1: AI Provider Configuration
    print_section_header("🤖 AI Provider Configuration");

    let provider = select_provider_advanced()?;
    config.ai_provider = Some(provider.name.to_string());

    // Custom model selection
    let default_model = provider.default_model;
    let use_custom_model = Confirm::new()
        .with_prompt(format!(
            "Use default model ({}), or specify a custom one?",
            default_model.bright_cyan()
        ))
        .default(true)
        .interact()?;

    if use_custom_model {
        config.model = Some(default_model.to_string());
    } else {
        let custom_model: String = Input::new()
            .with_prompt("Enter model name")
            .default(default_model.to_string())
            .interact()?;
        config.model = Some(custom_model);
    }

    // API key or custom endpoint
    if provider.requires_key {
        let api_key = prompt_for_api_key(provider.name)?;
        if !api_key.is_empty() {
            config.api_key = Some(api_key);
        }

        // Custom API URL option
        let use_custom_url = Confirm::new()
            .with_prompt("Use a custom API endpoint URL?")
            .default(false)
            .interact()?;

        if use_custom_url {
            let custom_url: String = Input::new()
                .with_prompt("Enter custom API URL")
                .default(format!("https://api.{}.com/v1", provider.name))
                .interact()?;
            config.api_url = Some(custom_url);
        }
    }

    // Section 2: Commit Message Style
    print_section_header("📝 Commit Message Style");

    let format = select_commit_format()?;
    config.commit_type = Some(format.as_str().to_string());
    config.emoji = Some(matches!(format, CommitFormat::Gitmoji));

    // Capitalization
    config.description_capitalize = Some(
        Confirm::new()
            .with_prompt("Capitalize the first letter of commit messages?")
            .default(true)
            .interact()?,
    );

    // Period at end
    config.description_add_period = Some(
        Confirm::new()
            .with_prompt("Add period at the end of commit messages?")
            .default(false)
            .interact()?,
    );

    // Max length
    let max_length: usize = Input::new()
        .with_prompt("Maximum commit message length")
        .default(100)
        .validate_with(|input: &usize| -> Result<(), &str> {
            if *input >= 50 && *input <= 200 {
                Ok(())
            } else {
                Err("Please enter a value between 50 and 200")
            }
        })
        .interact()?;
    config.description_max_length = Some(max_length);

    // Language selection
    let language = select_language()?;
    config.language = Some(language.to_string());

    // Section 3: Behavior Settings
    print_section_header("⚙️  Behavior Settings");

    // Generate count
    let generate_count: u8 = Input::new()
        .with_prompt("Number of commit variations to generate (1-5)")
        .default(1)
        .validate_with(|input: &u8| -> Result<(), &str> {
            if *input >= 1 && *input <= 5 {
                Ok(())
            } else {
                Err("Please enter a value between 1 and 5")
            }
        })
        .interact()?;
    config.generate_count = Some(generate_count);

    // Git push option
    config.gitpush = Some(
        Confirm::new()
            .with_prompt("Automatically push commits to remote?")
            .default(false)
            .interact()?,
    );

    // One-line commits
    config.one_line_commit = Some(
        Confirm::new()
            .with_prompt("Always use one-line commits (no body)?")
            .default(false)
            .interact()?,
    );

    // Enable commit body
    config.enable_commit_body = Some(
        Confirm::new()
            .with_prompt("Allow multi-line commit messages with body?")
            .default(false)
            .interact()?,
    );

    // Section 4: Advanced Features
    print_section_header("🔧 Advanced Features");

    // Learn from history
    config.learn_from_history = Some(
        Confirm::new()
            .with_prompt("Learn commit style from repository history?")
            .default(false)
            .interact()?,
    );

    if config.learn_from_history == Some(true) {
        let history_count: usize = Input::new()
            .with_prompt("Number of commits to analyze for style")
            .default(50)
            .validate_with(|input: &usize| -> Result<(), &str> {
                if *input >= 10 && *input <= 200 {
                    Ok(())
                } else {
                    Err("Please enter a value between 10 and 200")
                }
            })
            .interact()?;
        config.history_commits_count = Some(history_count);
    }

    // Clipboard on timeout
    config.clipboard_on_timeout = Some(
        Confirm::new()
            .with_prompt("Copy commit message to clipboard on timeout/error?")
            .default(true)
            .interact()?,
    );

    // Hook settings
    config.hook_strict = Some(
        Confirm::new()
            .with_prompt("Strict hook mode (fail on hook errors)?")
            .default(true)
            .interact()?,
    );

    let hook_timeout: u64 = Input::new()
        .with_prompt("Hook timeout (milliseconds)")
        .default(30000)
        .validate_with(|input: &u64| -> Result<(), &str> {
            if *input >= 1000 && *input <= 300000 {
                Ok(())
            } else {
                Err("Please enter a value between 1000 and 300000")
            }
        })
        .interact()?;
    config.hook_timeout_ms = Some(hook_timeout);

    // Section 5: Token Limits (for advanced users)
    print_section_header("🎯 Token Limits (Optional)");

    let configure_tokens = Confirm::new()
        .with_prompt("Configure token limits? (Most users can skip this)")
        .default(false)
        .interact()?;

    if configure_tokens {
        let max_input: usize = Input::new()
            .with_prompt("Maximum input tokens")
            .default(4096)
            .interact()?;
        config.tokens_max_input = Some(max_input);

        let max_output: u32 = Input::new()
            .with_prompt("Maximum output tokens")
            .default(500)
            .interact()?;
        config.tokens_max_output = Some(max_output);
    }

    // Save configuration
    config.save()?;

    print_completion_message(&config, true);
    Ok(())
}

fn select_provider_quick() -> Result<ProviderOption> {
    println!();
    println!("{}", "Select your AI provider:".bold());
    println!(
        "{}",
        "   This determines which AI will generate your commit messages.".dimmed()
    );
    println!();

    let providers = ProviderOption::all();
    let _popular: Vec<_> = providers
        .iter()
        .filter(|p| p.category == ProviderCategory::Popular)
        .map(|p| p.display)
        .collect();

    let _local: Vec<_> = providers
        .iter()
        .filter(|p| p.category == ProviderCategory::Local)
        .map(|p| p.display)
        .collect();

    let _cloud: Vec<_> = providers
        .iter()
        .filter(|p| p.category == ProviderCategory::Cloud)
        .map(|p| p.display)
        .collect();

    let _enterprise: Vec<_> = providers
        .iter()
        .filter(|p| p.category == ProviderCategory::Enterprise)
        .map(|p| p.display)
        .collect();

    let specialized: Vec<_> = providers
        .iter()
        .filter(|p| p.category == ProviderCategory::Specialized)
        .map(|p| p.display)
        .collect();

    let mut all_displays = Vec::new();
    let mut provider_indices: Vec<usize> = Vec::new();

    // Popular section
    all_displays.push("─── Popular Providers ───".dimmed().to_string());
    for (idx, p) in providers.iter().enumerate() {
        if p.category == ProviderCategory::Popular {
            all_displays.push(p.display.to_string());
            provider_indices.push(idx);
        }
    }

    // Local section
    all_displays.push("─── Local/Private ───".dimmed().to_string());
    for (idx, p) in providers.iter().enumerate() {
        if p.category == ProviderCategory::Local {
            all_displays.push(p.display.to_string());
            provider_indices.push(idx);
        }
    }

    // Cloud section
    all_displays.push("─── Cloud Providers ───".dimmed().to_string());
    for (idx, p) in providers.iter().enumerate() {
        if p.category == ProviderCategory::Cloud {
            all_displays.push(p.display.to_string());
            provider_indices.push(idx);
        }
    }

    // Enterprise section
    all_displays.push("─── Enterprise ───".dimmed().to_string());
    for (idx, p) in providers.iter().enumerate() {
        if p.category == ProviderCategory::Enterprise {
            all_displays.push(p.display.to_string());
            provider_indices.push(idx);
        }
    }

    // Specialized section
    if !specialized.is_empty() {
        all_displays.push("─── Specialized ───".dimmed().to_string());
        for (idx, p) in providers.iter().enumerate() {
            if p.category == ProviderCategory::Specialized {
                all_displays.push(p.display.to_string());
                provider_indices.push(idx);
            }
        }
    }

    let selection = Select::new()
        .with_prompt("AI Provider")
        .items(&all_displays)
        .default(1) // First real item (after header)
        .interact()?;

    // Count headers before the selected item to determine actual provider index
    let header_count = all_displays[..=selection]
        .iter()
        .filter(|s| s.starts_with(''))
        .count();

    let provider_idx = if selection > 0 {
        selection.saturating_sub(header_count)
    } else {
        0
    };

    let provider = if provider_idx < provider_indices.len() {
        providers
            .into_iter()
            .nth(provider_indices[provider_idx])
            .unwrap()
    } else {
        // Fallback to first popular provider
        providers
            .into_iter()
            .find(|p| p.category == ProviderCategory::Popular)
            .unwrap()
    };

    println!();
    println!(
        "{} Selected: {} {}",
        "".green(),
        provider.name.bright_cyan(),
        format!("(model: {})", provider.default_model).dimmed()
    );

    Ok(provider)
}

fn select_provider_advanced() -> Result<ProviderOption> {
    println!();
    println!("{}", "Select your AI provider:".bold());
    println!();

    let providers = ProviderOption::all();
    let items: Vec<_> = providers.iter().map(|p| p.display).collect();

    let selection = Select::new()
        .with_prompt("AI Provider")
        .items(&items)
        .default(0)
        .interact()?;

    let provider = providers.into_iter().nth(selection).unwrap();

    println!();
    println!("{} Selected: {}", "".green(), provider.name.bright_cyan());

    Ok(provider)
}

fn prompt_for_api_key(provider_name: &str) -> Result<String> {
    println!();
    println!("{}", "API Key Configuration".bold());
    println!(
        "{}",
        format!(
            "   Get your API key from the {} dashboard",
            provider_name.bright_cyan()
        )
        .dimmed()
    );
    println!(
        "{}",
        "   Your key will be stored securely in your system's keychain.".dimmed()
    );
    println!();

    let api_key: String = Input::new()
        .with_prompt(format!(
            "Enter your {} API key",
            provider_name.bright_cyan()
        ))
        .allow_empty(true)
        .interact()?;

    let trimmed = api_key.trim();

    if trimmed.is_empty() {
        println!();
        println!(
            "{} No API key provided. You can set it later with: {}",
            "⚠️".yellow(),
            "rco config set RCO_API_KEY=<your_key>".bright_cyan()
        );
    } else {
        // Show last 4 characters for confirmation
        let masked = if trimmed.len() > 4 {
            format!("{}****", &trimmed[trimmed.len() - 4..])
        } else {
            "****".to_string()
        };
        println!();
        println!("{} API key saved: {}", "".green(), masked.dimmed());
    }

    Ok(trimmed.to_string())
}

fn select_commit_format() -> Result<CommitFormat> {
    println!();
    println!("{}", "Commit Message Format".bold());
    println!(
        "{}",
        "   Choose how your commit messages should be formatted.".dimmed()
    );
    println!();

    let formats = CommitFormat::all();
    let items: Vec<_> = formats.iter().map(|f| f.display()).collect();

    let selection = Select::new()
        .with_prompt("Commit format")
        .items(&items)
        .default(0)
        .interact()?;

    let format = formats.into_iter().nth(selection).unwrap();

    println!();
    println!(
        "{} Selected: {}",
        "".green(),
        format.as_str().bright_cyan()
    );

    // Show example
    let example = match format {
        CommitFormat::Conventional => "feat(auth): Add login functionality",
        CommitFormat::Gitmoji => "✨ feat(auth): Add login functionality",
        CommitFormat::Simple => "Add login functionality",
    };
    println!("  Example: {}", example.dimmed());

    Ok(format)
}

fn select_language() -> Result<String> {
    println!();
    println!("{}", "Output Language".bold());
    println!(
        "{}",
        "   What language should commit messages be generated in?".dimmed()
    );
    println!();

    let languages = LanguageOption::all();
    let items: Vec<_> = languages.iter().map(|l| l.display).collect();

    let selection = Select::new()
        .with_prompt("Language")
        .items(&items)
        .default(0)
        .interact()?;

    let lang = &languages[selection];

    if lang.code == "other" {
        let custom: String = Input::new()
            .with_prompt("Enter language code (e.g., 'nl' for Dutch)")
            .interact()?;
        Ok(custom)
    } else {
        Ok(lang.code.to_string())
    }
}

fn print_section_header(title: &str) {
    println!();
    println!(
        "{}",
        "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━".dimmed()
    );
    println!("{}", title.bold());
    println!(
        "{}",
        "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━".dimmed()
    );
}

fn print_completion_message(config: &Config, is_advanced: bool) {
    println!();
    println!(
        "{}",
        "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━".dimmed()
    );
    println!();
    println!("{} Setup complete! 🎉", "".green().bold());
    println!();

    // Show summary
    println!("{}", "Configuration Summary:".bold());
    println!();

    if let Some(provider) = &config.ai_provider {
        println!("  {} Provider: {}", "".cyan(), provider.bright_white());
    }
    if let Some(model) = &config.model {
        println!("  {} Model: {}", "".cyan(), model.bright_white());
    }
    if let Some(commit_type) = &config.commit_type {
        println!(
            "  {} Commit format: {}",
            "".cyan(),
            commit_type.bright_white()
        );
    }
    if let Some(language) = &config.language {
        if language != "en" {
            println!("  {} Language: {}", "".cyan(), language.bright_white());
        }
    }

    println!();
    println!("{} You're ready to go!", "".cyan());
    println!();
    println!("   Try it now:  {}", "rco".bold().bright_cyan().underline());
    println!();

    if is_advanced {
        println!("   Make a commit:  {}", "git add . && rco".dimmed());
        println!();
        println!(
            "{} Modify settings anytime: {}",
            "".cyan(),
            "rco setup --advanced".bright_cyan()
        );
        println!(
            "{} Or use: {}",
            "".cyan(),
            "rco config set <key>=<value>".bright_cyan()
        );
    } else {
        println!(
            "   Want more options? Run: {}",
            "rco setup --advanced".bright_cyan()
        );
    }

    println!();
    println!(
        "{}",
        "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━".dimmed()
    );
}

async fn apply_defaults() -> Result<()> {
    let mut config = Config::load()?;

    // Apply sensible defaults without prompting
    config.ai_provider = Some("openai".to_string());
    config.model = Some("gpt-4o-mini".to_string());
    config.commit_type = Some("conventional".to_string());
    config.description_capitalize = Some(true);
    config.description_add_period = Some(false);
    config.description_max_length = Some(100);
    config.language = Some("en".to_string());
    config.generate_count = Some(1);
    config.emoji = Some(false);
    config.gitpush = Some(false);
    config.one_line_commit = Some(false);
    config.enable_commit_body = Some(false);
    config.learn_from_history = Some(false);
    config.clipboard_on_timeout = Some(true);
    config.hook_strict = Some(true);
    config.hook_timeout_ms = Some(30000);
    config.tokens_max_input = Some(4096);
    config.tokens_max_output = Some(500);

    config.save()?;

    println!();
    println!("{} Default configuration applied!", "".green().bold());
    println!();
    println!("   Provider: openai (gpt-4o-mini)");
    println!("   Format: conventional commits");
    println!();
    println!(
        "   Set your API key: {}",
        "rco config set RCO_API_KEY=<your_key>".bright_cyan()
    );
    println!();

    Ok(())
}