mrapids 0.1.31

Your OpenAPI, but executable
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
#![allow(dead_code)]

use anyhow::{Context, Result};
use clap::Args;
use colored::*;
use std::collections::HashMap;
use std::fs;
use std::io::Write;
use std::path::{Path, PathBuf};

use crate::core::api::ApiError;
use crate::core::spec::UnifiedSpec;

/// Connect and configure authentication credentials
#[derive(Debug, Args)]
pub struct ConnectCommand {
    /// Name of the authentication scheme to configure
    pub scheme: Option<String>,

    /// Type of authentication (if not auto-detected)
    #[arg(long, value_enum)]
    pub auth_type: Option<AuthType>,

    /// Non-interactive mode (use environment variables)
    #[arg(long)]
    pub non_interactive: bool,

    /// Discover OIDC endpoints from well-known URL
    #[arg(long)]
    pub discover: bool,

    /// Force overwrite existing configuration
    #[arg(long)]
    pub force: bool,

    /// Store credentials in OS keychain (when available)
    #[arg(long)]
    pub keychain: bool,

    /// Path to OpenAPI specification
    #[arg(long)]
    pub spec: Option<String>,

    /// Environment to save credentials to (default: local)
    pub env: Option<String>,
}

#[derive(Debug, Clone, Copy, clap::ValueEnum)]
pub enum AuthType {
    ApiKey,
    Bearer,
    Basic,
    OAuth2,
    OpenIdConnect,
    MutualTls,
}

impl ConnectCommand {
    pub async fn execute(&self) -> Result<()> {
        println!("{}", "Authentication Setup".bold().cyan());
        println!("{}", "".repeat(60).cyan());

        // Load spec if available to get scheme details
        let spec = self.load_spec().await.ok();
        let schemes = spec.as_ref().map(|s| &s.security_schemes);

        // Determine which scheme to configure
        let scheme_name = if let Some(name) = &self.scheme {
            name.clone()
        } else {
            self.select_scheme(schemes)?
        };

        // Get scheme details if available
        let scheme_details = schemes.and_then(|s| s.get(&scheme_name));

        // Configure the authentication
        if self.non_interactive {
            self.configure_non_interactive(&scheme_name, scheme_details)
                .await?;
        } else {
            self.configure_interactive(&scheme_name, scheme_details)
                .await?;
        }

        println!(
            "\n{} Authentication configured successfully!",
            "".green().bold()
        );
        let env_name = self.env.as_deref().unwrap_or("local");
        let env_file = if env_name == "local" {
            ".env.local".to_string()
        } else if PathBuf::from("env").exists() {
            format!("env/.env.{}", env_name)
        } else {
            format!(".env.{}", env_name)
        };
        println!(
            "  Credentials saved to {} (use {})",
            env_file.green(),
            format!("${}_*", scheme_name.to_uppercase()).cyan()
        );
        self.print_next_steps(&scheme_name);

        Ok(())
    }

    async fn load_spec(&self) -> Result<UnifiedSpec> {
        let spec_path = self
            .spec
            .as_ref()
            .map(Path::new)
            .or_else(|| {
                for path in &[
                    "openapi.yaml",
                    "openapi.json",
                    "swagger.yaml",
                    "swagger.json",
                ] {
                    if Path::new(path).exists() {
                        return Some(Path::new(path));
                    }
                }
                None
            })
            .context("No OpenAPI specification found")?;

        UnifiedSpec::from_file(spec_path)
    }

    fn select_scheme(
        &self,
        schemes: Option<&HashMap<String, crate::core::spec::UnifiedSecurityScheme>>,
    ) -> Result<String> {
        if let Some(schemes) = schemes {
            if schemes.is_empty() {
                return Err(ApiError::AuthError(
                    "No authentication schemes found in specification".to_string(),
                )
                .into());
            }

            if schemes.len() == 1 {
                return Ok(schemes.keys().next().unwrap().clone());
            }

            // Interactive selection
            println!("\nAvailable authentication schemes:");
            let mut options: Vec<_> = schemes.keys().collect();
            options.sort();

            for (i, name) in options.iter().enumerate() {
                println!("  {}. {}", i + 1, name.bold());
            }

            print!("\nSelect scheme (1-{}): ", options.len());
            std::io::stdout().flush()?;

            let mut input = String::new();
            std::io::stdin().read_line(&mut input)?;

            let index: usize = input.trim().parse().context("Invalid selection")?;

            if index == 0 || index > options.len() {
                return Err(ApiError::ValidationError("Invalid selection".to_string()).into());
            }

            Ok(options[index - 1].to_string())
        } else {
            return Err(ApiError::ValidationError(
                "Please specify a scheme name with --scheme".to_string(),
            )
            .into());
        }
    }

    async fn configure_interactive(
        &self,
        scheme_name: &str,
        details: Option<&crate::core::spec::UnifiedSecurityScheme>,
    ) -> Result<()> {
        let auth_type = self.determine_auth_type(details)?;

        match auth_type {
            AuthType::ApiKey => self.setup_api_key_interactive(scheme_name, details).await,
            AuthType::Bearer => self.setup_bearer_interactive(scheme_name, details).await,
            AuthType::Basic => self.setup_basic_interactive(scheme_name).await,
            AuthType::OAuth2 => self.setup_oauth2_interactive(scheme_name, details).await,
            AuthType::OpenIdConnect => self.setup_oidc_interactive(scheme_name, details).await,
            AuthType::MutualTls => self.setup_mtls_interactive(scheme_name).await,
        }
    }

    async fn configure_non_interactive(
        &self,
        scheme_name: &str,
        details: Option<&crate::core::spec::UnifiedSecurityScheme>,
    ) -> Result<()> {
        let auth_type = self.determine_auth_type(details)?;

        match auth_type {
            AuthType::ApiKey => self.setup_api_key_env(scheme_name, details),
            AuthType::Bearer => self.setup_bearer_env(scheme_name),
            AuthType::Basic => self.setup_basic_env(scheme_name),
            AuthType::OAuth2 => self.setup_oauth2_env(scheme_name),
            AuthType::OpenIdConnect => self.setup_oidc_env(scheme_name),
            AuthType::MutualTls => self.setup_mtls_env(scheme_name),
        }
    }

    fn determine_auth_type(
        &self,
        details: Option<&crate::core::spec::UnifiedSecurityScheme>,
    ) -> Result<AuthType> {
        if let Some(auth_type) = self.auth_type {
            return Ok(auth_type);
        }

        if let Some(details) = details {
            match details.scheme_type.as_str() {
                "apiKey" => Ok(AuthType::ApiKey),
                "http" => {
                    if details.scheme.as_deref() == Some("bearer") {
                        Ok(AuthType::Bearer)
                    } else if details.scheme.as_deref() == Some("basic") {
                        Ok(AuthType::Basic)
                    } else {
                        Ok(AuthType::Bearer) // Default to bearer
                    }
                }
                "oauth2" => Ok(AuthType::OAuth2),
                "openIdConnect" => Ok(AuthType::OpenIdConnect),
                "mutualTLS" => Ok(AuthType::MutualTls),
                _ => Err(ApiError::ValidationError(format!(
                    "Unknown auth type: {}",
                    details.scheme_type
                ))
                .into()),
            }
        } else {
            Err(ApiError::ValidationError(
                "Cannot determine auth type. Please specify with --auth-type".to_string(),
            )
            .into())
        }
    }

    async fn setup_api_key_interactive(
        &self,
        scheme_name: &str,
        details: Option<&crate::core::spec::UnifiedSecurityScheme>,
    ) -> Result<()> {
        println!("\n{}", "API Key Configuration".yellow());

        let location = details
            .and_then(|d| d.location.as_deref())
            .unwrap_or("header");
        let param_name = details
            .and_then(|d| d.name.as_deref())
            .unwrap_or("X-API-Key");

        println!("Location: {}", location.bold());
        println!("Parameter: {}", param_name.bold());

        // Check if API key was provided via CLI (set as env var by main.rs)
        let api_key = if let Ok(key) = std::env::var("API_KEY") {
            std::env::remove_var("API_KEY"); // Clean up temp var
            key
        } else {
            print!("\nEnter API Key: ");
            std::io::stdout().flush()?;

            let key = rpassword::read_password().context("Failed to read API key")?;

            if key.trim().is_empty() {
                return Err(ApiError::AuthError("API key cannot be empty".to_string()).into());
            }
            key
        };

        // Save configuration
        self.save_api_key_config(scheme_name, &api_key, location, param_name)?;

        Ok(())
    }

    async fn setup_bearer_interactive(
        &self,
        scheme_name: &str,
        details: Option<&crate::core::spec::UnifiedSecurityScheme>,
    ) -> Result<()> {
        println!("\n{}", "Bearer Token Configuration".yellow());

        if let Some(format) = details.and_then(|d| d.bearer_format.as_deref()) {
            println!("Format: {}", format.bold());
        }

        // Check if token was provided via CLI (set as env var by main.rs)
        let token = if let Ok(t) = std::env::var("BEARER_TOKEN") {
            std::env::remove_var("BEARER_TOKEN"); // Clean up temp var
            t
        } else {
            print!("\nEnter Bearer Token: ");
            std::io::stdout().flush()?;

            let t = rpassword::read_password().context("Failed to read token")?;

            if t.trim().is_empty() {
                return Err(ApiError::AuthError("Token cannot be empty".to_string()).into());
            }
            t
        };

        // Save configuration
        self.save_bearer_config(scheme_name, &token)?;

        Ok(())
    }

    async fn setup_basic_interactive(&self, scheme_name: &str) -> Result<()> {
        println!("\n{}", "Basic Authentication Configuration".yellow());

        // Check if credentials were provided via CLI (set as env vars by main.rs)
        let (username, password) = if let (Ok(u), Ok(p)) = (
            std::env::var("BASIC_USERNAME"),
            std::env::var("BASIC_PASSWORD"),
        ) {
            std::env::remove_var("BASIC_USERNAME"); // Clean up temp vars
            std::env::remove_var("BASIC_PASSWORD");
            (u, p)
        } else {
            print!("Username: ");
            std::io::stdout().flush()?;

            let mut username = String::new();
            std::io::stdin().read_line(&mut username)?;
            let username = username.trim().to_string();

            print!("Password: ");
            std::io::stdout().flush()?;

            let password = rpassword::read_password().context("Failed to read password")?;

            if username.is_empty() || password.trim().is_empty() {
                return Err(ApiError::AuthError(
                    "Username and password cannot be empty".to_string(),
                )
                .into());
            }
            (username, password)
        };

        // Save configuration
        self.save_basic_config(scheme_name, &username, &password)?;

        Ok(())
    }

    async fn setup_oauth2_interactive(
        &self,
        scheme_name: &str,
        details: Option<&crate::core::spec::UnifiedSecurityScheme>,
    ) -> Result<()> {
        println!("\n{}", "OAuth2 Configuration".yellow());

        // Determine available flows
        let flows = self.get_oauth2_flows(details);

        if flows.is_empty() {
            return Err(ApiError::AuthError(
                "No OAuth2 flows configured in specification".to_string(),
            )
            .into());
        }

        println!("\nAvailable flows:");
        for (i, flow) in flows.iter().enumerate() {
            println!("  {}. {}", i + 1, flow.bold());
        }

        print!("\nSelect flow (1-{}): ", flows.len());
        std::io::stdout().flush()?;

        let mut input = String::new();
        std::io::stdin().read_line(&mut input)?;

        let index: usize = input.trim().parse().context("Invalid selection")?;

        if index == 0 || index > flows.len() {
            return Err(ApiError::ValidationError("Invalid selection".to_string()).into());
        }

        let selected_flow = &flows[index - 1];

        match selected_flow.as_str() {
            "client_credentials" => {
                self.setup_oauth2_client_credentials(scheme_name, details)
                    .await
            }
            "authorization_code" => self.setup_oauth2_auth_code(scheme_name, details).await,
            "device_code" => self.setup_oauth2_device_code(scheme_name, details).await,
            _ => {
                return Err(ApiError::ValidationError(format!(
                    "Flow {} not yet implemented",
                    selected_flow
                ))
                .into())
            }
        }
    }

    async fn setup_oauth2_client_credentials(
        &self,
        _scheme_name: &str,
        details: Option<&crate::core::spec::UnifiedSecurityScheme>,
    ) -> Result<()> {
        println!("\n{}", "Client Credentials Flow".cyan());

        print!("Client ID: ");
        std::io::stdout().flush()?;

        let mut client_id = String::new();
        std::io::stdin().read_line(&mut client_id)?;
        let _client_id = client_id.trim();

        print!("Client Secret: ");
        std::io::stdout().flush()?;

        let _client_secret = rpassword::read_password().context("Failed to read client secret")?;

        let token_url = details
            .and_then(|d| d.token_url.as_deref())
            .context("No token URL found in specification")?;

        println!("\nToken URL: {}", token_url.green());

        // TODO: Actually fetch the token using the client credentials
        println!("\n{} Would fetch token from: {}", "".yellow(), token_url);
        println!("  (Token fetching not yet implemented)");

        // Save configuration
        // TODO: Uncomment when save_oauth2_config is implemented
        // self.save_oauth2_config(scheme_name, &_client_id, &_client_secret, token_url)?;

        Ok(())
    }

    async fn setup_oauth2_auth_code(
        &self,
        _scheme_name: &str,
        details: Option<&crate::core::spec::UnifiedSecurityScheme>,
    ) -> Result<()> {
        println!("\n{}", "Authorization Code Flow".cyan());

        let auth_url = details
            .and_then(|d| d.authorization_url.as_deref())
            .context("No authorization URL found in specification")?;

        let token_url = details
            .and_then(|d| d.token_url.as_deref())
            .context("No token URL found in specification")?;

        println!("\nAuthorization URL: {}", auth_url.green());
        println!("Token URL: {}", token_url.green());

        print!("\nClient ID: ");
        std::io::stdout().flush()?;

        let mut client_id = String::new();
        std::io::stdin().read_line(&mut client_id)?;
        let _client_id = client_id.trim();

        print!("Client Secret (if required): ");
        std::io::stdout().flush()?;

        let _client_secret = rpassword::read_password().context("Failed to read client secret")?;

        // TODO: Implement actual OAuth2 flow with browser
        println!("\n{} Would open browser to: {}", "".yellow(), auth_url);
        println!("  (Browser flow not yet implemented)");

        Ok(())
    }

    async fn setup_oauth2_device_code(
        &self,
        _scheme_name: &str,
        _details: Option<&crate::core::spec::UnifiedSecurityScheme>,
    ) -> Result<()> {
        println!("\n{}", "Device Code Flow".cyan());
        println!("  (Not yet implemented)");
        return Err(
            ApiError::ValidationError("Device code flow not yet implemented".to_string()).into(),
        );
    }

    async fn setup_oidc_interactive(
        &self,
        scheme_name: &str,
        details: Option<&crate::core::spec::UnifiedSecurityScheme>,
    ) -> Result<()> {
        println!("\n{}", "OpenID Connect Configuration".yellow());

        if self.discover {
            if let Some(url) = details.and_then(|d| d.openid_connect_url.as_deref()) {
                println!("Discovering from: {}", url.green());
                // TODO: Implement OIDC discovery
                println!("  (OIDC discovery not yet implemented)");
            }
        }

        // For now, treat like OAuth2
        self.setup_oauth2_interactive(scheme_name, details).await
    }

    async fn setup_mtls_interactive(&self, scheme_name: &str) -> Result<()> {
        println!("\n{}", "Mutual TLS Configuration".yellow());

        print!("Client certificate path: ");
        std::io::stdout().flush()?;

        let mut cert_path = String::new();
        std::io::stdin().read_line(&mut cert_path)?;
        let cert_path = cert_path.trim();

        print!("Client key path: ");
        std::io::stdout().flush()?;

        let mut key_path = String::new();
        std::io::stdin().read_line(&mut key_path)?;
        let key_path = key_path.trim();

        // Validate paths exist
        if !Path::new(cert_path).exists() {
            return Err(
                ApiError::AuthError(format!("Certificate file not found: {}", cert_path)).into(),
            );
        }

        if !Path::new(key_path).exists() {
            return Err(ApiError::AuthError(format!("Key file not found: {}", key_path)).into());
        }

        // Save configuration
        self.save_mtls_config(scheme_name, cert_path, key_path)?;

        Ok(())
    }

    // Environment variable setup methods
    fn setup_api_key_env(
        &self,
        scheme_name: &str,
        details: Option<&crate::core::spec::UnifiedSecurityScheme>,
    ) -> Result<()> {
        let env_var = format!("{}_API_KEY", scheme_name.to_uppercase());

        let api_key = std::env::var(&env_var)
            .with_context(|| format!("Environment variable {} not set", env_var))?;

        let location = details
            .and_then(|d| d.location.as_deref())
            .unwrap_or("header");
        let param_name = details
            .and_then(|d| d.name.as_deref())
            .unwrap_or("X-API-Key");

        self.save_api_key_config(scheme_name, &api_key, location, param_name)?;

        println!("✓ Configured {} from ${}", scheme_name, env_var);
        Ok(())
    }

    fn setup_bearer_env(&self, scheme_name: &str) -> Result<()> {
        let env_var = format!("{}_TOKEN", scheme_name.to_uppercase());

        let token = std::env::var(&env_var)
            .with_context(|| format!("Environment variable {} not set", env_var))?;

        self.save_bearer_config(scheme_name, &token)?;

        println!("✓ Configured {} from ${}", scheme_name, env_var);
        Ok(())
    }

    fn setup_basic_env(&self, scheme_name: &str) -> Result<()> {
        let user_var = format!("{}_USERNAME", scheme_name.to_uppercase());
        let pass_var = format!("{}_PASSWORD", scheme_name.to_uppercase());

        let username = std::env::var(&user_var)
            .with_context(|| format!("Environment variable {} not set", user_var))?;

        let password = std::env::var(&pass_var)
            .with_context(|| format!("Environment variable {} not set", pass_var))?;

        self.save_basic_config(scheme_name, &username, &password)?;

        println!(
            "✓ Configured {} from ${} and ${}",
            scheme_name, user_var, pass_var
        );
        Ok(())
    }

    fn setup_oauth2_env(&self, scheme_name: &str) -> Result<()> {
        let id_var = format!("{}_CLIENT_ID", scheme_name.to_uppercase());
        let secret_var = format!("{}_CLIENT_SECRET", scheme_name.to_uppercase());

        let client_id = std::env::var(&id_var)
            .with_context(|| format!("Environment variable {} not set", id_var))?;

        let client_secret = std::env::var(&secret_var)
            .with_context(|| format!("Environment variable {} not set", secret_var))?;

        // For env setup, we need token URL from somewhere
        // This would typically come from the spec
        let token_url = std::env::var(format!("{}_TOKEN_URL", scheme_name.to_uppercase()))
            .unwrap_or_else(|_| "https://oauth.provider.com/token".to_string());

        self.save_oauth2_config(scheme_name, &client_id, &client_secret, &token_url)?;

        println!(
            "✓ Configured {} from ${} and ${}",
            scheme_name, id_var, secret_var
        );
        Ok(())
    }

    fn setup_oidc_env(&self, scheme_name: &str) -> Result<()> {
        // Similar to OAuth2
        self.setup_oauth2_env(scheme_name)
    }

    fn setup_mtls_env(&self, scheme_name: &str) -> Result<()> {
        let cert_var = format!("{}_CLIENT_CERT", scheme_name.to_uppercase());
        let key_var = format!("{}_CLIENT_KEY", scheme_name.to_uppercase());

        let cert_path = std::env::var(&cert_var)
            .with_context(|| format!("Environment variable {} not set", cert_var))?;

        let key_path = std::env::var(&key_var)
            .with_context(|| format!("Environment variable {} not set", key_var))?;

        self.save_mtls_config(scheme_name, &cert_path, &key_path)?;

        println!(
            "✓ Configured {} from ${} and ${}",
            scheme_name, cert_var, key_var
        );
        Ok(())
    }

    // Configuration saving methods
    fn save_api_key_config(
        &self,
        scheme_name: &str,
        api_key: &str,
        _location: &str,
        _param_name: &str,
    ) -> Result<()> {
        // Simply save to .env.local for now
        // In the future, could save to keychain or secure storage
        self.update_env_file(&format!("{}_API_KEY", scheme_name.to_uppercase()), api_key)?;
        println!("  → API key saved for scheme: {}", scheme_name.green());
        Ok(())
    }

    fn save_bearer_config(&self, scheme_name: &str, token: &str) -> Result<()> {
        // Simply save to .env.local for now
        self.update_env_file(&format!("{}_TOKEN", scheme_name.to_uppercase()), token)?;
        println!("  → Bearer token saved for scheme: {}", scheme_name.green());
        Ok(())
    }

    fn save_basic_config(&self, scheme_name: &str, username: &str, password: &str) -> Result<()> {
        // Save both username and password to .env.local
        self.update_env_file(
            &format!("{}_USERNAME", scheme_name.to_uppercase()),
            username,
        )?;
        self.update_env_file(
            &format!("{}_PASSWORD", scheme_name.to_uppercase()),
            password,
        )?;
        println!(
            "  → Basic auth credentials saved for scheme: {}",
            scheme_name.green()
        );
        Ok(())
    }

    fn save_oauth2_config(
        &self,
        scheme_name: &str,
        client_id: &str,
        client_secret: &str,
        token_url: &str,
    ) -> Result<()> {
        // Save OAuth2 credentials to .env.local
        self.update_env_file(
            &format!("{}_CLIENT_ID", scheme_name.to_uppercase()),
            client_id,
        )?;
        self.update_env_file(
            &format!("{}_CLIENT_SECRET", scheme_name.to_uppercase()),
            client_secret,
        )?;
        self.update_env_file(
            &format!("{}_TOKEN_URL", scheme_name.to_uppercase()),
            token_url,
        )?;
        println!(
            "  → OAuth2 credentials saved for scheme: {}",
            scheme_name.green()
        );
        Ok(())
    }

    fn save_mtls_config(&self, scheme_name: &str, cert_path: &str, key_path: &str) -> Result<()> {
        // Save mTLS paths to .env.local
        self.update_env_file(
            &format!("{}_CLIENT_CERT", scheme_name.to_uppercase()),
            cert_path,
        )?;
        self.update_env_file(
            &format!("{}_CLIENT_KEY", scheme_name.to_uppercase()),
            key_path,
        )?;
        println!(
            "  → mTLS configuration saved for scheme: {}",
            scheme_name.green()
        );
        Ok(())
    }

    #[allow(dead_code)]
    fn write_auth_config(&self, _scheme_name: &str, _content: &str) -> Result<()> {
        // Deprecated: We no longer create config/auth files
        // Everything goes to .env.local now
        Ok(())
    }

    fn update_env_file(&self, key: &str, value: &str) -> Result<()> {
        if self.keychain {
            // TODO: Implement keychain storage
            println!("  → Would store {} in keychain (not implemented)", key);
        } else {
            // Determine which env file to use based on the environment parameter
            let env_name = self.env.as_deref().unwrap_or("local");
            let env_file = if env_name == "local" {
                PathBuf::from(".env.local")
            } else {
                // Check if env directory exists, if so use it
                let env_dir = PathBuf::from("env");
                if env_dir.exists() {
                    env_dir.join(format!(".env.{}", env_name))
                } else {
                    PathBuf::from(format!(".env.{}", env_name))
                }
            };

            let mut content = if env_file.exists() {
                fs::read_to_string(&env_file)?
            } else {
                String::new()
            };

            // Check if key already exists
            let key_pattern = format!("{}=", key);
            if !content.contains(&key_pattern) {
                if !content.is_empty() && !content.ends_with('\n') {
                    content.push('\n');
                }
                content.push_str(&format!("{}={}\n", key, value));

                // Create parent directory if it doesn't exist
                if let Some(parent) = env_file.parent() {
                    fs::create_dir_all(parent)?;
                }

                fs::write(&env_file, content)?;
                println!("  → Saved to {}", env_file.display());
            }
        }

        Ok(())
    }

    fn get_oauth2_flows(
        &self,
        details: Option<&crate::core::spec::UnifiedSecurityScheme>,
    ) -> Vec<String> {
        let mut flows = Vec::new();

        if let Some(details) = details {
            // Check which flows are configured
            if details.token_url.is_some() {
                flows.push("client_credentials".to_string());
            }
            if details.authorization_url.is_some() && details.token_url.is_some() {
                flows.push("authorization_code".to_string());
            }
            // Device code would need a device_url extension
            // flows.push("device_code".to_string());
        }

        if flows.is_empty() {
            // Default flows if not specified
            flows.push("client_credentials".to_string());
            flows.push("authorization_code".to_string());
        }

        flows
    }

    fn print_next_steps(&self, scheme_name: &str) {
        println!("\n{}", "Next Steps:".bold().cyan());
        println!("  1. Validate configuration:");
        println!(
            "     {}",
            format!("mrapids auth validate --scheme {}", scheme_name).green()
        );
        println!("  2. Test with an API operation:");
        println!("     {}", "mrapids run <operation>".green());
        println!("     (Auth will be automatically used from environment variables)");
        println!("  3. View auth status:");
        println!("     {}", "mrapids auth detect --format table".green());
    }
}