opencrates 3.0.1

Enterprise-grade AI-powered Rust development companion with comprehensive automation, monitoring, and deployment capabilities
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
//! Configuration management for OpenCrates

use anyhow::{Context, Result};
use config::{Config, Environment, File};
use dialoguer::{theme::ColorfulTheme, Confirm, Input};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::env;
use std::path::{Path, PathBuf};
use std::sync::{Arc, RwLock};
use std::time::Duration;
use tracing::{debug, info};

/// Main configuration structure
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct OpenCratesConfig {
    pub environment: String,
    pub debug: bool,
    pub name: String,
    pub version: String,
    pub description: String,
    pub openai_api_key: String,
    pub default_model: String,
    pub default_output_dir: String,
    pub include_tests_by_default: bool,
    pub include_docs_by_default: bool,

    pub database: DatabaseConfig,
    pub redis: RedisConfig,
    pub server: ServerConfig,
    pub metrics: MetricsConfig,
    pub logging: LoggingConfig,
    pub tracing: TracingConfig,
    pub cache: CacheConfig,
    pub search: SearchConfig,
    pub templates: TemplatesConfig,
    #[serde(default, alias = "openai")]
    pub ai: AiConfig,
    pub features: FeaturesConfig,
    pub security: SecurityConfig,
    pub storage: StorageConfig,
    pub notifications: NotificationsConfig,
    pub webhooks: WebhooksConfig,
    pub monitoring: MonitoringConfig,
    pub experimental: ExperimentalConfig,
    #[serde(default)]
    pub health: HealthConfig,
    pub codex: CodexConfig,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DatabaseConfig {
    pub url: String,
    pub max_connections: u32,
    #[serde(default)]
    pub min_connections: u32,
    #[serde(default)]
    pub connection_timeout: Duration,
    #[serde(default)]
    pub idle_timeout: Duration,
    #[serde(default)]
    pub max_lifetime: Duration,
    pub enable_logging: bool,
    #[serde(default)]
    pub migration_path: String,

    // legacy
    #[serde(default)]
    pub pool_size: Option<u32>,
    #[serde(default)]
    pub timeout: Option<u64>,
    #[serde(default)]
    pub run_migrations: bool,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RedisConfig {
    pub url: String,
    pub max_connections: u32,
    pub connection_timeout: Duration,
    pub response_timeout: Duration,
    pub retry_attempts: u32,
    pub retry_delay: Duration,
    pub enable_cluster: bool,
    pub cluster_nodes: Vec<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ServerConfig {
    pub host: String,
    pub port: u16,
    pub workers: usize,
    pub keep_alive: u64,
    pub request_timeout: u64,
    pub body_limit: String,
    pub enable_cors: bool,
    pub enable_compression: bool,
    pub enable_request_id: bool,
    pub cors: CorsConfig,
    pub rate_limit: RateLimitConfig,
    pub tls: TlsConfig,

    // legacy fields expected by tests
    #[serde(default)]
    pub max_connections: Option<u32>,
    #[serde(default)]
    pub timeout: Option<u64>,
    #[serde(default)]
    pub cors_origins: Vec<String>,
    #[serde(default)]
    pub enable_swagger: bool,
    #[serde(default)]
    pub enable_metrics: bool,
    #[serde(default)]
    pub enable_health_checks: bool,
    #[serde(default)]
    pub enable_tracing: bool,
    #[serde(default)]
    pub log_level: Option<String>,
    #[serde(default)]
    pub max_payload_size: Option<u64>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CorsConfig {
    pub allow_origins: Vec<String>,
    pub allow_methods: Vec<String>,
    pub allow_headers: Vec<String>,
    pub expose_headers: Vec<String>,
    pub max_age: u64,
    pub allow_credentials: bool,
}

#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct RateLimitConfig {
    pub enabled: bool,
    pub requests_per_minute: u32,
    pub burst_size: u32,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TlsConfig {
    pub enabled: bool,
    pub cert_path: String,
    pub key_path: String,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MetricsConfig {
    pub enabled: bool,
    pub port: u16,
    pub path: String,
    pub include_golang_metrics: bool,
    pub include_process_metrics: bool,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LoggingConfig {
    pub level: String,
    pub format: String,
    pub enable_json: bool,
    pub enable_timestamps: bool,
    pub enable_file_info: bool,
    pub enable_thread_ids: bool,
    pub outputs: LoggingOutputs,
    pub rotation: LogRotationConfig,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LoggingOutputs {
    pub stdout: bool,
    pub file: Option<String>,
    pub syslog: bool,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LogRotationConfig {
    pub enabled: bool,
    pub max_size: String,
    pub max_age: u32,
    pub max_backups: u32,
    pub compress: bool,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TracingConfig {
    pub enabled: bool,
    pub service_name: String,
    pub endpoint: String,
    pub sample_rate: f64,
    pub propagation: String,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CacheConfig {
    #[serde(default)]
    pub backend: String,
    #[serde(default)]
    pub capacity: Option<usize>,
    #[serde(default)]
    pub ttl_seconds: Option<u64>,
    #[serde(default)]
    pub ttl: u64,
    #[serde(default)]
    pub max_size: usize,
    #[serde(default)]
    pub eviction_policy: String,
    #[serde(default)]
    pub redis: RedisCacheConfig,
}

impl Default for CacheConfig {
    fn default() -> Self {
        CacheConfig {
            backend: "memory".into(),
            capacity: None,
            ttl_seconds: None,
            ttl: 300,
            max_size: 1000,
            eviction_policy: "lru".to_string(),
            redis: RedisCacheConfig::default(),
        }
    }
}

#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct RedisCacheConfig {
    pub enabled: bool,
    pub prefix: String,
    pub ttl: u64,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SearchConfig {
    pub enabled: bool,
    pub provider: String,
    pub timeout: u64,
    pub max_results: usize,
    pub safe_search: bool,
    pub region: String,
    pub cache: SearchCacheConfig,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SearchCacheConfig {
    pub enabled: bool,
    pub ttl: u64,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TemplatesConfig {
    pub directory: String,
    pub custom_directory: String,
    pub cache_compiled: bool,
    pub auto_reload: bool,
}

#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct AiConfig {
    pub provider: String,
    pub model: String,
    pub temperature: f32,
    pub max_tokens: u32,

    // legacy (all #[serde(default)])
    #[serde(default)]
    pub top_p: Option<f32>,
    #[serde(default)]
    pub frequency_penalty: Option<f32>,
    #[serde(default)]
    pub presence_penalty: Option<f32>,
    #[serde(default)]
    pub timeout: Option<u64>,
    #[serde(default)]
    pub max_retries: Option<u32>,
    #[serde(default)]
    pub base_url: Option<String>,
    #[serde(default)]
    pub organization: Option<String>,
    #[serde(default)]
    pub api_version: Option<String>,
    #[serde(default)]
    pub retry_attempts: u32,
    #[serde(default)]
    pub retry_delay: u64,
    #[serde(default)]
    pub models: AiModelsConfig,
    #[serde(default)]
    pub prompts: PromptsConfig,
}

#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct AiModelsConfig {
    pub conceptualizer: String,
    pub architect: String,
    pub developer: String,
    pub reviewer: String,
}

#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct PromptsConfig {
    pub system_prompt: String,
    pub include_examples: bool,
    pub include_best_practices: bool,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FeaturesConfig {
    pub enable_web_ui: bool,
    pub enable_api: bool,
    pub enable_cli: bool,
    pub enable_webhooks: bool,
    pub enable_notifications: bool,
    pub enable_analytics: bool,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SecurityConfig {
    pub enable_auth: bool,
    pub enable_api_keys: bool,
    pub enable_rate_limiting: bool,
    pub enable_ip_whitelist: bool,
    pub ip_whitelist: Vec<String>,
    pub jwt: JwtConfig,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct JwtConfig {
    pub secret: String,
    pub expiration: u64,
    pub refresh_expiration: u64,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct StorageConfig {
    pub backend: String,
    pub path: String,
    pub max_file_size: String,
    pub allowed_extensions: Vec<String>,
    pub s3: S3Config,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct S3Config {
    pub enabled: bool,
    pub bucket: String,
    pub region: String,
    pub access_key: String,
    pub secret_key: String,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct NotificationsConfig {
    pub enabled: bool,
    pub providers: Vec<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct WebhooksConfig {
    pub enabled: bool,
    pub endpoints: Vec<String>,
    pub timeout: u64,
    pub retry_attempts: u32,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MonitoringConfig {
    pub health_check_interval: u64,
    pub enable_profiling: bool,
    pub enable_debugging: bool,

    // legacy
    #[serde(default)]
    pub enabled: bool,
    #[serde(default)]
    pub endpoint: Option<String>,
    #[serde(default)]
    pub interval: Option<u64>,
    #[serde(default)]
    pub retention: Option<u64>,
    #[serde(default)]
    pub alert_thresholds: Option<HashMap<String, u64>>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ExperimentalConfig {
    pub enable_wasm_plugins: bool,
    pub enable_gpu_acceleration: bool,
    pub enable_distributed_cache: bool,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct HealthConfig {
    pub check_interval: Option<u64>,
    pub enabled_checks: Vec<String>,

    // legacy
    #[serde(default)]
    pub enabled: bool,
    #[serde(default)]
    pub endpoint: Option<String>,
    #[serde(default)]
    pub timeout: Option<u64>,
}

impl Default for HealthConfig {
    fn default() -> Self {
        Self {
            check_interval: Some(30),
            enabled_checks: vec![
                "database".to_string(),
                "cache".to_string(),
                "api".to_string(),
            ],
            enabled: true,
            endpoint: None,
            timeout: Some(5),
        }
    }
}

/// Configuration manager
#[derive(Debug, Clone)]
pub struct ConfigManager {
    config: Arc<RwLock<OpenCratesConfig>>,
    config_path: PathBuf,
}

impl ConfigManager {
    pub fn new(config: OpenCratesConfig) -> Result<Self> {
        Ok(Self {
            config: Arc::new(RwLock::new(config)),
            config_path: PathBuf::from(""),
        })
    }

    /// Load configuration from multiple sources
    pub fn load() -> Result<Self> {
        // Try to load from default paths, but fall back to default config if none exist
        if let Ok(config) = Self::load_from_path(None) {
            Ok(config)
        } else {
            // If no config file exists, create a default configuration
            let default_config = OpenCratesConfig::default();
            let config_path = PathBuf::from("opencrates.toml");
            Ok(Self {
                config: Arc::new(RwLock::new(default_config)),
                config_path,
            })
        }
    }

    /// Get configuration - convenience method
    pub fn get(&self) -> std::sync::RwLockReadGuard<'_, OpenCratesConfig> {
        self.config.read().unwrap()
    }

    /// Get configuration reference - convenience method
    #[must_use]
    pub fn get_ref(&self) -> OpenCratesConfig {
        self.config.read().unwrap().clone()
    }

    /// Load configuration from specific path
    pub fn load_from_path(config_path: Option<&Path>) -> Result<Self> {
        let mut builder =
            Config::builder().add_source(Config::try_from(&OpenCratesConfig::default())?);

        // Add configuration files
        let config_files = vec![
            "config/default.toml",
            "config/development.toml",
            "config/production.toml",
            "opencrates.toml",
        ];

        for file in config_files {
            builder = builder.add_source(File::with_name(file).required(false));
        }

        // Add custom config file if specified
        if let Some(path) = config_path {
            builder = builder.add_source(File::from(path));
        }

        // Add environment variables
        builder = builder.add_source(
            Environment::with_prefix("OPENCRATES")
                .prefix_separator("_")
                .separator("__"),
        );

        let config = builder
            .build()
            .context("Failed to build configuration")?
            .try_deserialize::<OpenCratesConfig>()
            .context("Failed to deserialize configuration")?;

        info!("Configuration loaded successfully");
        debug!("Config: {:?}", config);

        Ok(Self {
            config: Arc::new(RwLock::new(config)),
            config_path: config_path
                .map(std::path::Path::to_path_buf)
                .unwrap_or_default(),
        })
    }

    /// Get configuration
    pub fn config(&self) -> std::sync::RwLockReadGuard<'_, OpenCratesConfig> {
        self.config.read().unwrap()
    }

    /// Validate configuration
    pub fn validate(&self) -> Result<()> {
        let config = self.config();

        // Validate required fields
        if config.openai_api_key.is_empty() && config.ai.provider == "openai" {
            return Err(anyhow::anyhow!(
                "OpenAI API key is required when using OpenAI provider"
            ));
        }

        // Validate database URL
        if config.database.url.is_empty() {
            return Err(anyhow::anyhow!("Database URL is required"));
        }

        // Validate server configuration
        if config.server.port == 0 {
            return Err(anyhow::anyhow!("Server port must be greater than 0"));
        }

        // Validate directories exist
        let template_dir = Path::new(&config.templates.directory);
        if !template_dir.exists() {
            return Err(anyhow::anyhow!(
                "Template directory does not exist: {}",
                template_dir.display()
            ));
        }

        info!("Configuration validation passed");
        Ok(())
    }

    /// Reload configuration
    pub fn reload(&self) -> Result<()> {
        let new_config = Self::load_from_path(Some(&self.config_path))?;
        *self.config.write().unwrap() = (*new_config.config.read().unwrap()).clone();
        info!("Configuration reloaded");
        Ok(())
    }

    /// Save current configuration to file
    pub fn save_to_file(&self, path: &Path) -> Result<()> {
        let toml_string = toml::to_string_pretty(&*self.config())?;

        std::fs::write(path, toml_string)?;

        info!("Configuration saved to {}", path.display());
        Ok(())
    }

    pub async fn get_config(&self) -> Result<OpenCratesConfig> {
        Ok(self.config().clone())
    }

    #[must_use]
    pub fn get_config_sync(&self) -> OpenCratesConfig {
        self.config().clone()
    }

    pub async fn set_api_key(&self, api_key: &str) -> Result<()> {
        let mut config = self.config.write().unwrap();
        config.openai_api_key = api_key.to_string();
        Ok(())
    }

    pub async fn set_redis_url(&self, redis_url: &str) -> Result<()> {
        let mut config = self.config.write().unwrap();
        config.redis.url = redis_url.to_string();
        Ok(())
    }

    pub async fn interactive_setup(&self) -> Result<()> {
        println!("OpenCrates Configuration Setup");

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

        let mut config = self.config.write().unwrap();
        config.openai_api_key = api_key;

        // Server Configuration
        let host: String = Input::with_theme(&ColorfulTheme::default())
            .with_prompt("Server host")
            .default("127.0.0.1".to_string())
            .interact_text()?;

        config.server.host = host;

        let port: u16 = Input::with_theme(&ColorfulTheme::default())
            .with_prompt("Server port")
            .default(8080)
            .interact()?;

        config.server.port = port;

        // Redis Configuration
        let use_redis = Confirm::with_theme(&ColorfulTheme::default())
            .with_prompt("Use Redis for caching?")
            .default(false)
            .interact()?;

        if use_redis {
            let redis_url: String = Input::with_theme(&ColorfulTheme::default())
                .with_prompt("Redis URL")
                .default("redis://localhost:6379".to_string())
                .interact_text()?;

            config.redis.url = redis_url;
        }

        println!("Configuration setup complete!");
        Ok(())
    }
}

/// Environment detection
#[derive(Debug, Clone, Copy)]
pub enum OpenCratesEnvironment {
    Development,
    Test,
    Staging,
    Production,
}

impl PartialEq for OpenCratesEnvironment {
    fn eq(&self, other: &Self) -> bool {
        matches!(
            (self, other),
            (Self::Development, Self::Development)
                | (Self::Test, Self::Test)
                | (Self::Staging, Self::Staging)
                | (Self::Production, Self::Production)
        )
    }
}

impl Eq for OpenCratesEnvironment {}

impl OpenCratesEnvironment {
    #[must_use]
    pub fn detect() -> Self {
        match std::env::var("OPENCRATES_ENV").as_deref() {
            Ok("production" | "prod") => Self::Production,
            Ok("staging" | "stage") => Self::Staging,
            Ok("test") => Self::Test,
            _ => Self::Development,
        }
    }

    #[must_use]
    pub fn is_production(&self) -> bool {
        matches!(self, Self::Production)
    }

    #[must_use]
    pub fn is_development(&self) -> bool {
        matches!(self, Self::Development)
    }
}

impl std::fmt::Display for OpenCratesEnvironment {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Development => write!(f, "development"),
            Self::Test => write!(f, "test"),
            Self::Staging => write!(f, "staging"),
            Self::Production => write!(f, "production"),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::io::Write;
    use tempfile::NamedTempFile;

    #[test]
    fn test_default_config() {
        let config = OpenCratesConfig::default();
        assert_eq!(config.environment, "development");
        assert_eq!(config.server.port, 8080);
        assert!(config.debug);
    }

    #[test]
    fn test_config_from_file() {
        let mut file = NamedTempFile::with_suffix(".toml").unwrap();
        writeln!(
            file,
            r#"
environment = "test"
debug = false

[server]
port = 9000
host = "0.0.0.0"
keep_alive = 60
        "#
        )
        .unwrap();

        let config = ConfigManager::load_from_path(Some(file.path())).unwrap();
        assert_eq!(config.config().environment, "test");
        assert_eq!(config.config().server.port, 9000);
        assert!(!config.config().debug);
    }

    #[test]
    fn test_environment_detection() {
        std::env::set_var("OPENCRATES_ENV", "production");
        assert_eq!(
            OpenCratesEnvironment::detect(),
            OpenCratesEnvironment::Production
        );
        assert!(OpenCratesEnvironment::detect().is_production());

        std::env::set_var("OPENCRATES_ENV", "development");
        assert_eq!(
            OpenCratesEnvironment::detect(),
            OpenCratesEnvironment::Development
        );
        assert!(OpenCratesEnvironment::detect().is_development());

        std::env::remove_var("OPENCRATES_ENV");
        assert_eq!(
            OpenCratesEnvironment::detect(),
            OpenCratesEnvironment::Development
        );
    }
}

pub type AppConfig = OpenCratesConfig;

impl OpenCratesConfig {
    /// Convert to more specific config structs
    #[must_use]
    pub fn to_openai_config(&self) -> OpenAIConfig {
        OpenAIConfig {
            api_key: Some(self.openai_api_key.clone()),
            model: self.ai.model.clone(),
            max_tokens: self.ai.max_tokens as usize,
            temperature: self.ai.temperature,
            top_p: self.ai.top_p,
            frequency_penalty: self.ai.frequency_penalty,
            presence_penalty: self.ai.presence_penalty,
            timeout: self.ai.timeout,
            max_retries: self.ai.max_retries,
            base_url: self.ai.base_url.clone(),
            organization: self.ai.organization.clone(),
            api_version: self.ai.api_version.clone(),
        }
    }

    #[must_use]
    pub fn to_cache_config(&self) -> crate::utils::cache::config::CacheConfig {
        crate::utils::cache::config::CacheConfig {
            max_entries: self.cache.max_size,
            default_ttl: Some(std::time::Duration::from_secs(self.cache.ttl)),
            ..crate::utils::cache::config::CacheConfig::default()
        }
    }

    #[must_use]
    pub fn to_server_config(&self) -> ServerConfig {
        self.server.clone()
    }

    #[must_use]
    pub fn to_database_config(&self) -> DatabaseConfig {
        self.database.clone()
    }
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct OpenAIConfig {
    pub api_key: Option<String>,
    pub model: String,
    pub max_tokens: usize,
    pub temperature: f32,
    #[serde(default)]
    pub top_p: Option<f32>,
    #[serde(default)]
    pub frequency_penalty: Option<f32>,
    #[serde(default)]
    pub presence_penalty: Option<f32>,
    #[serde(default)]
    pub timeout: Option<u64>,
    #[serde(default)]
    pub max_retries: Option<u32>,
    #[serde(default)]
    pub base_url: Option<String>,
    #[serde(default)]
    pub organization: Option<String>,
    #[serde(default)]
    pub api_version: Option<String>,
}

impl OpenAIConfig {
    #[must_use]
    pub fn new(api_key: String) -> Self {
        Self {
            api_key: Some(api_key),
            ..Default::default()
        }
    }
}

impl Default for OpenAIConfig {
    fn default() -> Self {
        Self {
            api_key: None,
            model: "gpt-4".into(),
            max_tokens: 256,
            temperature: 0.8,
            top_p: None,
            frequency_penalty: None,
            presence_penalty: None,
            timeout: None,
            max_retries: None,
            base_url: None,
            organization: None,
            api_version: None,
        }
    }
}

/// Configuration for the Codex provider
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CodexConfig {
    /// `OpenAI` API key for Codex access
    pub api_key: Option<String>,
    /// API base URL
    pub api_base: String,
    /// Model to use (e.g., "gpt-4o")
    pub model: String,
    /// Maximum tokens for completion
    pub max_tokens: u32,
    /// Temperature for sampling
    pub temperature: f32,
}

impl Default for CodexConfig {
    fn default() -> Self {
        Self {
            api_key: env::var("OPENAI_API_KEY").ok(),
            api_base: "https://api.openai.com/v1".to_string(),
            model: "gpt-4o".to_string(),
            max_tokens: 4096,
            temperature: 0.7,
        }
    }
}