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
use anyhow::Result;
use colored::Colorize;
use dialoguer::{theme::ColorfulTheme, Confirm, Input, Select};

use crate::auth::oauth::OAuthClient;
use crate::auth::token_storage;
use crate::cli::{AuthAction, AuthCommand};
use crate::config::Config;
use crate::output::progress;

/// Unified output helper for auth commands.
struct AuthOutput;

impl AuthOutput {
    fn header(&self, text: &str) {
        println!("\n{}", text.cyan().bold());
    }

    fn subheader(&self, text: &str) {
        println!("{}", text.dimmed());
    }

    fn success(&self, message: &str) {
        println!("{}", format!("{}", message).green().bold());
    }

    fn warning(&self, message: &str) {
        println!("{}", format!("{}", message).yellow());
    }

    fn error(&self, message: &str) {
        println!("{}", format!("{}", message).red().bold());
    }

    fn info(&self, message: &str) {
        println!("{}", message.cyan());
    }

    fn divider(&self) {
        println!("{}", "".repeat(40).dimmed());
    }

    fn section(&self, title: &str) {
        self.divider();
        println!("{}", title.cyan().bold());
        self.divider();
    }

    fn key_value(&self, key: &str, value: &str) {
        println!("  {}: {}", key.dimmed(), value);
    }
}

/// Execute auth command from CLI
pub async fn execute(cmd: AuthCommand) -> Result<()> {
    match cmd.action {
        AuthAction::Login => login().await,
        AuthAction::Logout => logout().await,
        AuthAction::Status => status().await,
    }
}

/// Login with interactive provider selection
async fn login() -> Result<()> {
    let out = AuthOutput;
    out.header("🚀 Welcome to Rusty Commit Authentication");
    out.divider();

    // Check if already authenticated
    if token_storage::has_valid_token() {
        let should_reauth = Confirm::with_theme(&ColorfulTheme::default())
            .with_prompt("You are already authenticated. Do you want to re-authenticate?")
            .default(false)
            .interact()?;

        if !should_reauth {
            out.success("Authentication unchanged");
            return Ok(());
        }
    }

    // Provider selection menu - all providers supported by OpenCode
    let providers = vec![
        (
            "Anthropic Claude",
            "Use Claude Pro/Max subscription or API key",
        ),
        (
            "OpenAI Codex (ChatGPT)",
            "Use ChatGPT Pro/Plus subscription via OAuth",
        ),
        (
            "GitHub Copilot",
            "Use GitHub Copilot subscription (recommended)",
        ),
        ("OpenAI", "GPT models with OpenAI API key"),
        ("Google Gemini", "Google Gemini and Vertex AI models"),
        ("OpenRouter", "Access 200+ models via OpenRouter"),
        (
            "Perplexity",
            "Cost-effective AI models with web search capabilities",
        ),
        ("Groq", "Fast inference with Groq API"),
        ("DeepSeek", "DeepSeek models and API"),
        ("Mistral", "Mistral AI models and API"),
        ("AWS Bedrock", "Amazon Bedrock AI models"),
        ("Azure OpenAI", "Azure-hosted OpenAI models"),
        ("Together AI", "Together AI platform"),
        ("DeepInfra", "DeepInfra hosted models"),
        ("Hugging Face", "Hugging Face Inference API"),
        ("GitHub Models", "GitHub hosted AI models"),
        ("Qwen (Alibaba)", "Qwen AI models via DashScope"),
        ("Ollama", "Local Ollama instance"),
        ("Other", "Custom OpenAI-compatible provider"),
    ];

    let selection = Select::with_theme(&ColorfulTheme::default())
        .with_prompt("🤖 Select AI provider")
        .items(
            providers
                .iter()
                .map(|(name, desc)| format!("{:<20} {}", name, desc.dimmed()))
                .collect::<Vec<_>>(),
        )
        .default(0)
        .interact()?;

    match selection {
        0 => handle_anthropic_auth().await,
        1 => handle_codex_auth().await,
        2 => handle_github_copilot_auth().await,
        3 => handle_openai_auth().await,
        4 => handle_gemini_auth().await,
        5 => handle_openrouter_auth().await,
        6 => handle_perplexity_auth().await,
        7 => handle_groq_auth().await,
        8 => handle_deepseek_auth().await,
        9 => handle_mistral_auth().await,
        10 => handle_aws_bedrock_auth().await,
        11 => handle_azure_auth().await,
        12 => handle_together_auth().await,
        13 => handle_deepinfra_auth().await,
        14 => handle_huggingface_auth().await,
        15 => handle_github_models_auth().await,
        16 => handle_qwen_auth().await,
        17 => handle_ollama_auth().await,
        18 => handle_manual_auth().await,
        _ => unreachable!(),
    }
}

/// Handle Anthropic/Claude authentication with multiple options
async fn handle_anthropic_auth() -> Result<()> {
    println!("\n{}", "🧠 Anthropic Claude Authentication".cyan().bold());

    let auth_methods = vec![
        "Claude Pro/Max (OAuth) - Recommended",
        "API Key (Console) - Create new key",
        "API Key (Manual) - Enter existing key",
    ];

    let method = Select::with_theme(&ColorfulTheme::default())
        .with_prompt("Choose authentication method")
        .items(&auth_methods)
        .default(0)
        .interact()?;

    match method {
        0 => handle_claude_oauth().await,
        1 => handle_claude_api_key_creation().await,
        2 => handle_manual_api_key("anthropic").await,
        _ => unreachable!(),
    }
}

/// Handle Claude OAuth authentication
async fn handle_claude_oauth() -> Result<()> {
    println!("\n{}", "🔐 Starting Claude OAuth authentication...".cyan());
    println!(
        "{}",
        "This will use your Claude Pro/Max subscription".dimmed()
    );

    let oauth_client = OAuthClient::new();
    let (auth_url, verifier) = oauth_client.get_authorization_url()?;

    println!(
        "\n{}",
        "Please visit the following URL to authenticate:".bold()
    );
    println!("{}", auth_url.blue().underline());

    // Try to open browser automatically
    if webbrowser::open(&auth_url).is_ok() {
        println!("\n{}", "✓ Browser opened automatically".green());
    } else {
        println!(
            "\n{}",
            "⚠ Could not open browser automatically. Please visit the URL above.".yellow()
        );
    }

    // Show progress spinner
    let pb = progress::oauth_wait_spinner();

    // Wait for callback
    match oauth_client.start_callback_server(verifier).await {
        Ok(token_response) => {
            pb.finish_and_clear();

            // Store tokens using the new storage method
            token_storage::store_tokens(
                &token_response.access_token,
                token_response.refresh_token.as_deref(),
                token_response.expires_in,
            )?;

            println!("{}", "✓ Authentication successful!".green().bold());
            println!("  You can now use Rusty Commit with your Claude account.");

            // Update config to use anthropic provider
            let mut config = Config::load()?;
            config.ai_provider = Some("anthropic".to_string());
            config.save()?;

            Ok(())
        }
        Err(e) => {
            pb.finish_and_clear();
            println!("{}", format!("✗ Authentication failed: {}", e).red().bold());
            Err(e)
        }
    }
}

/// Handle Claude API key creation through console
async fn handle_claude_api_key_creation() -> Result<()> {
    println!("\n{}", "🔑 Creating Claude API Key".cyan());
    println!(
        "{}",
        "This will create a new API key in your Claude Console".dimmed()
    );

    // For now, redirect to manual entry - API key creation requires additional OAuth flow
    println!(
        "{}",
        "⚠️  Automatic API key creation not yet implemented".yellow()
    );
    println!(
        "{}",
        "Please create an API key manually at: https://console.anthropic.com/settings/keys".cyan()
    );

    handle_manual_api_key("anthropic").await
}

/// Handle OpenAI Codex (ChatGPT) OAuth authentication
async fn handle_codex_auth() -> Result<()> {
    use crate::auth::codex_oauth::CodexOAuthClient;

    println!(
        "\n{}",
        "🔐 OpenAI Codex (ChatGPT) Authentication".cyan().bold()
    );
    println!(
        "{}",
        "This will use your ChatGPT Pro/Plus subscription".dimmed()
    );

    let oauth_client = CodexOAuthClient::new();
    let (auth_url, verifier) = oauth_client.get_authorization_url()?;

    println!(
        "\n{}",
        "Please visit the following URL to authenticate:".bold()
    );
    println!("{}", auth_url.blue().underline());

    // Try to open browser automatically
    if webbrowser::open(&auth_url).is_ok() {
        println!("\n{}", "✓ Browser opened automatically".green());
    } else {
        println!(
            "\n{}",
            "⚠ Could not open browser automatically. Please visit the URL above.".yellow()
        );
    }

    // Show progress spinner
    let pb = progress::oauth_wait_spinner();

    // Wait for callback
    match oauth_client.start_callback_server(verifier).await {
        Ok(token_response) => {
            pb.finish_and_clear();

            // Store tokens
            let expires_in = token_response.expires_in.unwrap_or(3600);
            crate::auth::token_storage::store_tokens(
                &token_response.access_token,
                Some(&token_response.refresh_token),
                Some(expires_in),
            )?;

            println!("{}", "✓ Authentication successful!".green().bold());
            println!("  You can now use Rusty Commit with your ChatGPT account.");

            // Update config to use codex provider
            let mut config = Config::load()?;
            config.ai_provider = Some("codex".to_string());
            config.model = Some("gpt-5.1-codex".to_string());
            config.api_url = Some("https://chatgpt.com/backend-api/codex/responses".to_string());
            config.save()?;

            Ok(())
        }
        Err(e) => {
            pb.finish_and_clear();
            println!("{}", format!("✗ Authentication failed: {}", e).red().bold());
            Err(e)
        }
    }
}

/// Handle OpenAI authentication
async fn handle_openai_auth() -> Result<()> {
    println!("\n{}", "🤖 OpenAI Authentication".cyan().bold());
    println!(
        "{}",
        "Get your API key from: https://platform.openai.com/api-keys".cyan()
    );

    handle_manual_api_key("openai").await
}

/// Handle Ollama authentication
async fn handle_ollama_auth() -> Result<()> {
    println!("\n{}", "🦙 Ollama Configuration".cyan().bold());

    let use_local = Confirm::with_theme(&ColorfulTheme::default())
        .with_prompt("Are you using a local Ollama instance?")
        .default(true)
        .interact()?;

    let mut config = Config::load()?;
    config.ai_provider = Some("ollama".to_string());

    if use_local {
        config.api_url = Some("http://localhost:11434".to_string());
        println!(
            "{}",
            "✓ Configured for local Ollama (http://localhost:11434)".green()
        );
        eprintln!(
            "{}",
            "Warning: Using HTTP for local Ollama. This is acceptable for localhost connections."
                .yellow()
        );
    } else {
        let url: String = Input::with_theme(&ColorfulTheme::default())
            .with_prompt("Enter Ollama URL")
            .default("http://localhost:11434".to_string())
            .interact_text()?;

        config.api_url = Some(url.clone());

        // Warn about HTTP usage for non-local URLs
        if url.starts_with("http://") && !url.contains("localhost") && !url.contains("127.0.0.1") {
            eprintln!(
                "{}",
                "Warning: Using insecure HTTP connection. Your API requests may be intercepted. \
                Consider using HTTPS for production use."
                    .red()
            );
        }

        println!(
            "{}",
            format!("✓ Configured for remote Ollama ({})", url).green()
        );
    }

    // Get available models (this would ideally query Ollama)
    let model: String = Input::with_theme(&ColorfulTheme::default())
        .with_prompt("Enter model name")
        .default("mistral".to_string())
        .interact_text()?;

    config.model = Some(model.clone());
    config.save()?;

    println!(
        "{}",
        format!("✓ Ollama configured with model: {}", model)
            .green()
            .bold()
    );
    Ok(())
}

/// Handle Gemini authentication
async fn handle_gemini_auth() -> Result<()> {
    println!("\n{}", "💎 Google Gemini Authentication".cyan().bold());
    println!(
        "{}",
        "Get your API key from: https://aistudio.google.com/app/apikey".cyan()
    );

    handle_manual_api_key("gemini").await
}

/// Handle Azure authentication
async fn handle_azure_auth() -> Result<()> {
    println!("\n{}", "☁️ Azure OpenAI Configuration".cyan().bold());

    let mut config = Config::load()?;
    config.ai_provider = Some("azure".to_string());

    let api_key: String = Input::with_theme(&ColorfulTheme::default())
        .with_prompt("Enter Azure OpenAI API key")
        .interact_text()?;

    let endpoint: String = Input::with_theme(&ColorfulTheme::default())
        .with_prompt("Enter Azure OpenAI endpoint")
        .default("https://your-resource.openai.azure.com".to_string())
        .interact_text()?;

    let deployment: String = Input::with_theme(&ColorfulTheme::default())
        .with_prompt("Enter deployment name")
        .default("gpt-35-turbo".to_string())
        .interact_text()?;

    config.api_key = Some(api_key);
    config.api_url = Some(endpoint);
    config.model = Some(deployment);
    config.save()?;

    println!(
        "{}",
        "✓ Azure OpenAI configured successfully".green().bold()
    );
    Ok(())
}

/// Handle manual API key entry
async fn handle_manual_api_key(provider: &str) -> Result<()> {
    let api_key: String = Input::with_theme(&ColorfulTheme::default())
        .with_prompt(format!("Enter {} API key", provider))
        .interact_text()?;

    if api_key.trim().is_empty() {
        println!("{}", "❌ API key cannot be empty".red());
        return Ok(());
    }

    let mut config = Config::load()?;
    config.api_key = Some(api_key);
    config.ai_provider = Some(provider.to_string());

    // Set default model and API URL based on provider
    match provider {
        "anthropic" => {
            config.model = Some("claude-3-5-haiku-20241022".to_string());
        }
        "openai" => {
            config.model = Some("gpt-4o-mini".to_string());
        }
        "gemini" => {
            config.model = Some("gemini-1.5-pro".to_string());
            config.api_url = Some("https://generativelanguage.googleapis.com/v1beta".to_string());
        }
        "openrouter" => {
            config.model = Some("openai/gpt-4o-mini".to_string());
            config.api_url = Some("https://openrouter.ai/api/v1".to_string());
        }
        "perplexity" => {
            config.model = Some("llama-3.1-sonar-small-128k-online".to_string());
            config.api_url = Some("https://api.perplexity.ai".to_string());
        }
        "groq" => {
            config.model = Some("llama-3.1-70b-versatile".to_string());
            config.api_url = Some("https://api.groq.com/openai/v1".to_string());
        }
        "deepseek" => {
            config.model = Some("deepseek-chat".to_string());
            config.api_url = Some("https://api.deepseek.com".to_string());
        }
        "mistral" => {
            config.model = Some("mistral-large-latest".to_string());
            config.api_url = Some("https://api.mistral.ai/v1".to_string());
        }
        "together" => {
            config.model = Some("meta-llama/Llama-3.2-3B-Instruct-Turbo".to_string());
            config.api_url = Some("https://api.together.xyz/v1".to_string());
        }
        "deepinfra" => {
            config.model = Some("meta-llama/Llama-3.2-3B-Instruct".to_string());
            config.api_url = Some("https://api.deepinfra.com/v1/openai".to_string());
        }
        "huggingface" => {
            config.model = Some("meta-llama/Llama-3.2-3B-Instruct".to_string());
            config.api_url = Some("https://api-inference.huggingface.co/v1".to_string());
        }
        "github-models" => {
            config.model = Some("gpt-4o".to_string());
            config.api_url = Some("https://models.inference.ai.azure.com".to_string());
        }
        _ => {}
    }

    config.save()?;

    println!(
        "{}",
        format!("{} API key configured successfully", provider)
            .green()
            .bold()
    );
    Ok(())
}

/// Handle GitHub Copilot authentication
async fn handle_github_copilot_auth() -> Result<()> {
    println!("\n{}", "🐙 GitHub Copilot Authentication".cyan().bold());
    println!(
        "{}",
        "GitHub Copilot provides free AI assistance to subscribers".dimmed()
    );

    // TODO: Implement GitHub OAuth device flow
    println!(
        "{}",
        "⚠️  GitHub OAuth device flow not yet implemented".yellow()
    );
    println!("{}", "Please use GitHub CLI: gh auth login".cyan());

    let mut config = Config::load()?;
    config.ai_provider = Some("github-copilot".to_string());
    config.model = Some("gpt-4o".to_string());
    config.save()?;

    println!(
        "{}",
        "✓ GitHub Copilot configured (requires GitHub CLI auth)"
            .green()
            .bold()
    );
    Ok(())
}

/// Handle OpenRouter authentication
async fn handle_openrouter_auth() -> Result<()> {
    println!("\n{}", "🔄 OpenRouter Authentication".cyan().bold());
    println!(
        "{}",
        "Get your API key from: https://openrouter.ai/keys".cyan()
    );

    let mut config = Config::load()?;
    config.ai_provider = Some("openrouter".to_string());
    config.model = Some("openai/gpt-4o".to_string());
    config.api_url = Some("https://openrouter.ai/api/v1".to_string());

    handle_manual_api_key("openrouter").await
}

/// Handle Groq authentication
async fn handle_groq_auth() -> Result<()> {
    println!("\n{}", "⚡ Groq Authentication".cyan().bold());
    println!(
        "{}",
        "Get your API key from: https://console.groq.com/keys".cyan()
    );

    let mut config = Config::load()?;
    config.ai_provider = Some("groq".to_string());
    config.model = Some("llama-3.1-70b-versatile".to_string());
    config.api_url = Some("https://api.groq.com/openai/v1".to_string());

    handle_manual_api_key("groq").await
}

/// Handle DeepSeek authentication
async fn handle_deepseek_auth() -> Result<()> {
    println!("\n{}", "🧠 DeepSeek Authentication".cyan().bold());
    println!(
        "{}",
        "Get your API key from: https://platform.deepseek.com/api_keys".cyan()
    );

    let mut config = Config::load()?;
    config.ai_provider = Some("deepseek".to_string());
    config.model = Some("deepseek-chat".to_string());
    config.api_url = Some("https://api.deepseek.com".to_string());

    handle_manual_api_key("deepseek").await
}

/// Handle Mistral authentication
async fn handle_mistral_auth() -> Result<()> {
    println!("\n{}", "🌪️ Mistral AI Authentication".cyan().bold());
    println!(
        "{}",
        "Get your API key from: https://console.mistral.ai/".cyan()
    );

    let mut config = Config::load()?;
    config.ai_provider = Some("mistral".to_string());
    config.model = Some("mistral-large-latest".to_string());
    config.api_url = Some("https://api.mistral.ai/v1".to_string());

    handle_manual_api_key("mistral").await
}

/// Handle Qwen AI (Alibaba DashScope) authentication
async fn handle_qwen_auth() -> Result<()> {
    println!(
        "\n{}",
        "🌟 Qwen AI (Alibaba DashScope) Authentication"
            .cyan()
            .bold()
    );
    println!(
        "{}",
        "Get your API key from: https://dashscope.console.aliyun.com/".cyan()
    );

    let mut config = Config::load()?;
    config.ai_provider = Some("qwen".to_string());
    config.model = Some("qwen3-coder:480b".to_string());
    config.api_url = Some("https://dashscope.aliyuncs.com/compatible-mode/v1".to_string());

    handle_manual_api_key("qwen").await
}

/// Handle AWS Bedrock authentication
async fn handle_aws_bedrock_auth() -> Result<()> {
    println!("\n{}", "☁️ AWS Bedrock Authentication".cyan().bold());
    println!(
        "{}",
        "AWS Bedrock supports multiple authentication methods".dimmed()
    );

    let auth_methods = vec![
        "API Key (Bedrock) - Recommended for quick setup",
        "AWS Profile - Use configured AWS profile",
        "Environment Variables - AWS_ACCESS_KEY_ID & AWS_SECRET_ACCESS_KEY",
        "IAM Role - For EC2/Lambda environments",
    ];

    let method = Select::with_theme(&ColorfulTheme::default())
        .with_prompt("Choose AWS authentication method")
        .items(&auth_methods)
        .default(0)
        .interact()?;

    let mut config = Config::load()?;
    config.ai_provider = Some("amazon-bedrock".to_string());
    config.model = Some("us.anthropic.claude-3-5-haiku-20241022-v1:0".to_string());

    match method {
        0 => {
            println!(
                "{}",
                "Enter your AWS Bedrock API key (new feature in 2025)".cyan()
            );
            println!(
                "{}",
                "This will be stored in AWS_BEARER_TOKEN_BEDROCK".dimmed()
            );
            handle_manual_api_key_with_env("amazon-bedrock", "AWS_BEARER_TOKEN_BEDROCK").await
        }
        1 => {
            let profile: String = Input::with_theme(&ColorfulTheme::default())
                .with_prompt("Enter AWS profile name")
                .default("default".to_string())
                .interact_text()?;

            std::env::set_var("AWS_PROFILE", &profile);
            println!(
                "{}",
                format!("✓ AWS Bedrock configured with profile: {}", profile)
                    .green()
                    .bold()
            );
            config.save()?;
            Ok(())
        }
        2 => {
            println!("{}", "Please set these environment variables:".cyan());
            println!("  export AWS_ACCESS_KEY_ID=your_access_key");
            println!("  export AWS_SECRET_ACCESS_KEY=your_secret_key");
            println!("  export AWS_REGION=us-east-1  # optional");
            println!(
                "{}",
                "✓ AWS Bedrock configured for environment variables"
                    .green()
                    .bold()
            );
            config.save()?;
            Ok(())
        }
        3 => {
            println!("{}", "✓ AWS Bedrock configured for IAM role".green().bold());
            println!("  Ensure your EC2/Lambda role has bedrock:InvokeModel permissions");
            config.save()?;
            Ok(())
        }
        _ => unreachable!(),
    }
}

/// Handle Together AI authentication
async fn handle_together_auth() -> Result<()> {
    println!("\n{}", "🤝 Together AI Authentication".cyan().bold());
    println!(
        "{}",
        "Get your API key from: https://api.together.xyz/settings/api-keys".cyan()
    );

    let mut config = Config::load()?;
    config.ai_provider = Some("together".to_string());
    config.model = Some("meta-llama/Llama-3.2-3B-Instruct-Turbo".to_string());
    config.api_url = Some("https://api.together.xyz/v1".to_string());

    handle_manual_api_key("together").await
}

/// Handle DeepInfra authentication
async fn handle_deepinfra_auth() -> Result<()> {
    println!("\n{}", "🏗️ DeepInfra Authentication".cyan().bold());
    println!(
        "{}",
        "Get your API key from: https://deepinfra.com/dash/api_keys".cyan()
    );

    let mut config = Config::load()?;
    config.ai_provider = Some("deepinfra".to_string());
    config.model = Some("meta-llama/Llama-3.2-3B-Instruct".to_string());
    config.api_url = Some("https://api.deepinfra.com/v1/openai".to_string());

    handle_manual_api_key("deepinfra").await
}

/// Handle Hugging Face authentication
async fn handle_huggingface_auth() -> Result<()> {
    println!("\n{}", "🤗 Hugging Face Authentication".cyan().bold());
    println!(
        "{}",
        "Get your API key from: https://huggingface.co/settings/tokens".cyan()
    );

    let mut config = Config::load()?;
    config.ai_provider = Some("huggingface".to_string());
    config.model = Some("meta-llama/Llama-3.2-3B-Instruct".to_string());
    config.api_url = Some("https://api-inference.huggingface.co/v1".to_string());

    handle_manual_api_key("huggingface").await
}

/// Handle GitHub Models authentication
async fn handle_github_models_auth() -> Result<()> {
    println!("\n{}", "🐙 GitHub Models Authentication".cyan().bold());
    println!(
        "{}",
        "Get your token from: https://github.com/settings/personal-access-tokens".cyan()
    );
    println!("{}", "Requires 'Model Inference' permission".dimmed());

    let mut config = Config::load()?;
    config.ai_provider = Some("github-models".to_string());
    config.model = Some("gpt-4o".to_string());
    config.api_url = Some("https://models.inference.ai.azure.com".to_string());

    handle_manual_api_key("github-models").await
}

/// Handle manual API key entry with custom environment variable
async fn handle_manual_api_key_with_env(provider: &str, env_var: &str) -> Result<()> {
    let api_key: String = Input::with_theme(&ColorfulTheme::default())
        .with_prompt(format!("Enter {} API key", provider))
        .interact_text()?;

    if api_key.trim().is_empty() {
        println!("{}", "❌ API key cannot be empty".red());
        return Ok(());
    }

    // Set environment variable
    std::env::set_var(env_var, &api_key);

    let mut config = Config::load()?;
    // For environment variable based auth, we don't store the key in config
    config.ai_provider = Some(provider.to_string());
    config.save()?;

    println!(
        "{}",
        format!(
            "{} configured with environment variable {}",
            provider, env_var
        )
        .green()
        .bold()
    );
    println!(
        "{}",
        format!(
            "  Environment variable {} has been set for this session",
            env_var
        )
        .dimmed()
    );
    Ok(())
}

/// Handle manual/other provider configuration
async fn handle_manual_auth() -> Result<()> {
    println!("\n{}", "🔧 Custom Provider Configuration".cyan().bold());
    println!("{}", "Configure any OpenAI-compatible provider".dimmed());

    let provider: String = Input::with_theme(&ColorfulTheme::default())
        .with_prompt("Enter provider name")
        .interact_text()?;

    let api_url: String = Input::with_theme(&ColorfulTheme::default())
        .with_prompt("Enter API base URL")
        .default("https://api.openai.com/v1".to_string())
        .interact_text()?;

    let model: String = Input::with_theme(&ColorfulTheme::default())
        .with_prompt("Enter default model name")
        .default("gpt-3.5-turbo".to_string())
        .interact_text()?;

    let mut config = Config::load()?;
    config.ai_provider = Some(provider.clone());
    config.api_url = Some(api_url);
    config.model = Some(model);
    config.save()?;

    handle_manual_api_key(&provider).await
}

/// Logout and remove stored tokens
async fn logout() -> Result<()> {
    let out = AuthOutput;
    out.info("Logging out...");

    // Remove stored tokens
    token_storage::delete_tokens()?;

    out.success("Successfully logged out");
    println!("  Your authentication tokens have been removed.");

    Ok(())
}

/// Check authentication status
async fn status() -> Result<()> {
    let out = AuthOutput;
    out.section("Authentication Status");

    let config = Config::load()?;

    // Check for API key
    if config.api_key.is_some() {
        out.success("API Key configured");
        out.key_value(
            "Provider",
            config.ai_provider.as_deref().unwrap_or("openai"),
        );
        return Ok(());
    }

    // Check for OAuth tokens
    if let Some(tokens) = token_storage::get_tokens()? {
        out.success("Authenticated with Claude OAuth");

        // Check token expiry
        if tokens.is_expired() {
            out.warning("Token expired - please re-authenticate");
        } else if let Some(expires_at) = tokens.expires_at {
            let now = std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .unwrap()
                .as_secs();

            let remaining = expires_at - now;
            let hours = remaining / 3600;
            let minutes = (remaining % 3600) / 60;
            out.key_value("Token expires in", &format!("{}h {}m", hours, minutes));
        }

        if tokens.refresh_token.is_some() {
            out.key_value("Refresh token", "Available");
        }

        // Show where tokens are stored
        #[cfg(feature = "secure-storage")]
        if crate::config::secure_storage::is_available() {
            out.key_value("Storage", "System Keychain");
        } else {
            out.key_value("Storage", "~/.config/rustycommit/auth.json");
        }

        #[cfg(not(feature = "secure-storage"))]
        {
            out.key_value("Storage", "~/.config/rustycommit/auth.json");
        }
    } else {
        out.error("Not authenticated");
        out.subheader("To authenticate, run one of:");
        println!(
            "{} - Use Claude OAuth (recommended for Pro/Max users)",
            "rco auth login".cyan()
        );
        println!(
            "{} - Use API key",
            "rco config set RCO_API_KEY=<your_key>".cyan()
        );
    }

    println!("\n{}", "Storage Information:".bold());
    #[cfg(feature = "secure-storage")]
    println!("  {}", crate::config::secure_storage::status_message());

    #[cfg(not(feature = "secure-storage"))]
    println!("  Using file-based storage at ~/.config/rustycommit/auth.json");

    Ok(())
}

/// Automatically refresh token if needed
#[allow(dead_code)]
pub async fn auto_refresh_token() -> Result<()> {
    // Check if we have tokens and they're expiring soon
    if let Some(tokens) = token_storage::get_tokens()? {
        if tokens.expires_soon() {
            if let Some(refresh_token) = &tokens.refresh_token {
                let oauth_client = OAuthClient::new();
                match oauth_client.refresh_token(refresh_token).await {
                    Ok(token_response) => {
                        // Update stored tokens
                        token_storage::store_tokens(
                            &token_response.access_token,
                            token_response
                                .refresh_token
                                .as_deref()
                                .or(Some(refresh_token)),
                            token_response.expires_in,
                        )?;

                        tracing::debug!("Successfully refreshed OAuth token");
                    }
                    Err(e) => {
                        // Log both to trace and print a user-visible warning
                        tracing::warn!(
                            "Failed to refresh token: {}. User may need to re-authenticate.",
                            e
                        );
                        eprintln!(
                            "{}",
                            format!(
                                "Warning: Failed to refresh OAuth token. You may need to run 'rco auth login' again. Error: {}",
                                e
                            ).red()
                        );
                    }
                }
            }
        }
    }

    Ok(())
}

/// Handle Perplexity authentication
async fn handle_perplexity_auth() -> Result<()> {
    println!("\n{}", "🔍 Perplexity Authentication".cyan().bold());
    println!(
        "{}",
        "Get your API key from: https://www.perplexity.ai/settings/api".cyan()
    );

    let mut config = Config::load()?;
    config.ai_provider = Some("perplexity".to_string());
    config.model = Some("llama-3.1-sonar-small-128k-online".to_string());
    config.api_url = Some("https://api.perplexity.ai".to_string());

    handle_manual_api_key("perplexity").await
}