vkteams-bot-cli 0.7.6

High-performance VK Teams Bot API toolkit with CLI and MCP server support
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
use crate::errors::prelude::{CliError, Result as CliResult};
use dashmap::DashMap;
use once_cell::sync::Lazy;
use serde::{Deserialize, Serialize};
use std::env;
use std::fs;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::time::{Duration, SystemTime};
use tokio::sync::RwLock;
use tokio::time::Instant;
use toml;

// Use constants from the constants module
use crate::constants::config::{CONFIG_FILE_NAME, DEFAULT_CONFIG_DIR, ENV_PREFIX};
pub static CONFIG: Lazy<Config> = Lazy::new(|| Config::load().expect("Failed to load config"));

/// Configuration structure for VK Teams Bot CLI
#[derive(Default, Debug, Clone, Serialize, Deserialize)]
pub struct Config {
    /// API Configuration
    #[serde(default)]
    pub api: ApiConfig,

    /// File handling configuration
    #[serde(default)]
    pub files: FileConfig,

    /// Logging configuration
    #[serde(default)]
    pub logging: LoggingConfig,

    /// UI Configuration including progress bars
    #[serde(default)]
    pub ui: UiConfig,

    /// Proxy configuration
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub proxy: Option<ProxyConfig>,

    /// Rate limiting configuration
    #[serde(default)]
    pub rate_limit: RateLimitConfig,
}

/// API Configuration options
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ApiConfig {
    /// API token for VK Teams Bot
    #[serde(skip_serializing_if = "Option::is_none")]
    pub token: Option<String>,

    /// Base URL for API requests
    #[serde(skip_serializing_if = "Option::is_none")]
    pub url: Option<String>,

    /// Timeout for API requests in seconds
    #[serde(default = "default_timeout")]
    pub timeout: u64,

    /// Maximum number of retries for API requests
    #[serde(default = "default_retries")]
    pub max_retries: u32,
}

impl Default for ApiConfig {
    fn default() -> Self {
        Self {
            token: None,
            url: None,
            timeout: default_timeout(),
            max_retries: default_retries(),
        }
    }
}

/// File handling configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FileConfig {
    /// Default directory for downloads
    #[serde(skip_serializing_if = "Option::is_none")]
    pub download_dir: Option<String>,

    /// Default directory for uploads
    #[serde(skip_serializing_if = "Option::is_none")]
    pub upload_dir: Option<String>,

    /// Maximum file size in bytes for uploads and downloads
    #[serde(default = "default_max_file_size")]
    pub max_file_size: usize,

    /// Buffer size in bytes for file streaming
    #[serde(default = "default_buffer_size")]
    pub buffer_size: usize,
}

impl Default for FileConfig {
    fn default() -> Self {
        Self {
            download_dir: None,
            upload_dir: None,
            max_file_size: default_max_file_size(),
            buffer_size: default_buffer_size(),
        }
    }
}

/// Logging configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LoggingConfig {
    /// Log level (error, warn, info, debug, trace)
    #[serde(default = "default_log_level")]
    pub level: String,

    /// Output format (json, text)
    #[serde(default = "default_log_format")]
    pub format: String,

    /// Enable or disable color output
    #[serde(default = "default_log_colors")]
    pub colors: bool,
}

impl Default for LoggingConfig {
    fn default() -> Self {
        Self {
            level: default_log_level(),
            format: default_log_format(),
            colors: default_log_colors(),
        }
    }
}

/// UI and progress indicator configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct UiConfig {
    /// Enable or disable progress bars
    #[serde(default = "default_show_progress")]
    pub show_progress: bool,

    /// Progress bar style (default, unicode, ascii)
    #[serde(default = "default_progress_style")]
    pub progress_style: String,

    /// Progress bar refresh rate in milliseconds
    #[serde(default = "default_progress_refresh_rate")]
    pub progress_refresh_rate: u64,
}

impl Default for UiConfig {
    fn default() -> Self {
        Self {
            show_progress: default_show_progress(),
            progress_style: default_progress_style(),
            progress_refresh_rate: default_progress_refresh_rate(),
        }
    }
}

/// Proxy configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ProxyConfig {
    /// Proxy URL
    #[serde(default)]
    pub url: String,

    /// Proxy user (if authentication is required)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub user: Option<String>,

    /// Proxy password (if authentication is required)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub password: Option<String>,
}

impl Default for ProxyConfig {
    fn default() -> Self {
        Self {
            url: "".to_string(),
            user: None,
            password: None,
        }
    }
}

// Default values functions
pub fn default_timeout() -> u64 {
    30
}

pub fn default_retries() -> u32 {
    3
}

pub fn default_max_file_size() -> usize {
    100 * 1024 * 1024 // 100MB
}

pub fn default_buffer_size() -> usize {
    64 * 1024 // 64KB
}

pub fn default_log_level() -> String {
    "info".to_string()
}

pub fn default_log_format() -> String {
    "text".to_string()
}

pub fn default_log_colors() -> bool {
    true
}

// Default values for UI configuration
pub fn default_show_progress() -> bool {
    true
}

pub fn default_progress_style() -> String {
    "unicode".to_string()
}

pub fn default_progress_refresh_rate() -> u64 {
    100
}

/// Rate limiting configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RateLimitConfig {
    /// Enable or disable rate limiting
    #[serde(default = "default_rate_limit_enabled")]
    pub enabled: bool,

    /// Maximum requests per time window
    #[serde(default = "default_rate_limit_limit")]
    pub limit: usize,

    /// Time window duration in seconds
    #[serde(default = "default_rate_limit_duration")]
    pub duration: u64,

    /// Delay between retry attempts in milliseconds
    #[serde(default = "default_rate_limit_retry_delay")]
    pub retry_delay: u64,

    /// Maximum number of retry attempts
    #[serde(default = "default_rate_limit_retry_attempts")]
    pub retry_attempts: u16,
}

impl Default for RateLimitConfig {
    fn default() -> Self {
        Self {
            enabled: default_rate_limit_enabled(),
            limit: default_rate_limit_limit(),
            duration: default_rate_limit_duration(),
            retry_delay: default_rate_limit_retry_delay(),
            retry_attempts: default_rate_limit_retry_attempts(),
        }
    }
}

/// Default values for rate limiting configuration
pub fn default_rate_limit_enabled() -> bool {
    false // Disabled by default for CLI usage
}

pub fn default_rate_limit_limit() -> usize {
    1000 // More generous limit for CLI
}

pub fn default_rate_limit_duration() -> u64 {
    60
}

pub fn default_rate_limit_retry_delay() -> u64 {
    500 // Shorter delay for CLI
}

pub fn default_rate_limit_retry_attempts() -> u16 {
    3
}

impl Config {
    /// Load configuration from all available sources
    ///
    /// # Errors
    /// - Returns `CliError::FileError` if there is an error reading the config file
    /// - Returns `CliError::UnexpectedError` if there is an error parsing the config
    pub fn load() -> CliResult<Self> {
        let mut config = Config::default();

        // Try to load from config file
        if let Ok(file_config) = Self::from_file() {
            config = Self::merge_configs(config, file_config);
        }

        // Overlay with environment variables
        let env_config = Self::from_env()?;
        config = Self::merge_configs(config, env_config);

        Ok(config)
    }

    /// Load configuration from all available sources asynchronously (preferred method)
    ///
    /// # Errors
    /// - Returns `CliError::FileError` if there is an error reading the config file
    /// - Returns `CliError::UnexpectedError` if there is an error parsing the config
    pub async fn load_async() -> CliResult<Self> {
        let manager = AsyncConfigManager::default();
        manager.load_config().await
    }

    /// Save configuration to file
    ///
    /// # Errors
    /// - Returns `CliError::FileError` if there is an error creating directories or writing the file
    /// - Returns `CliError::UnexpectedError` if there is an error serializing the config
    pub fn save(&self, path: Option<&Path>) -> CliResult<()> {
        let path = if let Some(p) = path {
            p.to_owned()
        } else {
            let mut p = dirs::home_dir().ok_or_else(|| {
                CliError::FileError("Could not determine home directory".to_string())
            })?;
            p.push(DEFAULT_CONFIG_DIR);
            fs::create_dir_all(&p).map_err(|e| {
                CliError::FileError(format!("Could not create config directory: {e}"))
            })?;
            p.push(CONFIG_FILE_NAME);
            p
        };

        let content = toml::to_string_pretty(self)
            .map_err(|e| CliError::UnexpectedError(format!("Could not serialize config: {e}")))?;

        fs::write(&path, content)
            .map_err(|e| CliError::FileError(format!("Could not write config file: {e}")))?;

        Ok(())
    }

    /// Save configuration to file asynchronously (preferred method)
    ///
    /// # Errors
    /// - Returns `CliError::FileError` if there is an error creating directories or writing the file
    /// - Returns `CliError::UnexpectedError` if there is an error serializing the config
    pub async fn save_async(&self, path: Option<&Path>) -> CliResult<()> {
        let path = if let Some(p) = path {
            p.to_owned()
        } else {
            let mut p = dirs::home_dir().ok_or_else(|| {
                CliError::FileError("Could not determine home directory".to_string())
            })?;
            p.push(DEFAULT_CONFIG_DIR);
            tokio::fs::create_dir_all(&p).await.map_err(|e| {
                CliError::FileError(format!("Could not create config directory: {e}"))
            })?;
            p.push(CONFIG_FILE_NAME);
            p
        };

        let config_clone = self.clone();
        let content = tokio::task::spawn_blocking(move || toml::to_string_pretty(&config_clone))
            .await
            .map_err(|e| CliError::UnexpectedError(format!("Task join error: {e}")))?
            .map_err(|e| CliError::UnexpectedError(format!("Could not serialize config: {e}")))?;

        tokio::fs::write(&path, content)
            .await
            .map_err(|e| CliError::FileError(format!("Could not write config file: {e}")))?;

        Ok(())
    }

    /// Load configuration from all available sources
    ///
    /// # Errors
    /// - Returns `CliError::FileError` if there is an error reading the config file
    /// - Returns `CliError::UnexpectedError` if there is an error parsing the config
    pub fn from_file() -> CliResult<Self> {
        let config_paths = crate::utils::config_helpers::get_config_paths();

        for path in config_paths {
            if path.exists() {
                return Self::from_path(&path);
            }
        }

        // Return default config if no file found
        Ok(toml::from_str::<Config>("").unwrap())
    }

    /// Load configuration from a specific path
    ///
    /// # Errors
    /// - Returns `CliError::FileError` if there is an error reading the config file
    /// - Returns `CliError::UnexpectedError` if there is an error parsing the config
    pub fn from_path(path: &Path) -> CliResult<Self> {
        let content = fs::read_to_string(path)
            .map_err(|e| CliError::FileError(format!("Could not read config file: {e}")))?;

        let config: Config = toml::from_str(&content)
            .map_err(|e| CliError::UnexpectedError(format!("Could not parse config file: {e}")))?;

        Ok(config)
    }

    /// Load configuration from a specific path asynchronously
    ///
    /// # Errors
    /// - Returns `CliError::FileError` if there is an error reading the config file
    /// - Returns `CliError::UnexpectedError` if there is an error parsing the config
    pub async fn from_path_async(path: &Path) -> CliResult<Self> {
        let content = tokio::fs::read_to_string(path)
            .await
            .map_err(|e| CliError::FileError(format!("Could not read config file: {e}")))?;

        let config = tokio::task::spawn_blocking(move || toml::from_str::<Config>(&content))
            .await
            .map_err(|e| CliError::UnexpectedError(format!("Task join error: {e}")))?
            .map_err(|e| CliError::UnexpectedError(format!("Could not parse config file: {e}")))?;

        Ok(config)
    }

    /// Load configuration from environment variables
    ///
    /// # Errors
    /// - Returns `CliError::FileError` if there is an error with file operations
    /// - Returns `CliError::UnexpectedError` for unexpected errors
    pub fn from_env() -> CliResult<Self> {
        let mut config = toml::from_str::<Config>("").unwrap();
        // API config
        if let Ok(token) = env::var(format!("{ENV_PREFIX}BOT_API_TOKEN")) {
            config.api.token = Some(token);
        }
        if let Ok(url) = env::var(format!("{ENV_PREFIX}BOT_API_URL")) {
            config.api.url = Some(url);
        }
        if let Ok(timeout_str) = env::var(format!("{ENV_PREFIX}TIMEOUT"))
            && let Ok(timeout_val) = timeout_str.parse::<u64>()
        {
            config.api.timeout = timeout_val;
        }
        // File config
        if let Ok(download_dir) = env::var(format!("{ENV_PREFIX}DOWNLOAD_DIR")) {
            config.files.download_dir = Some(download_dir);
        }
        if let Ok(upload_dir) = env::var(format!("{ENV_PREFIX}UPLOAD_DIR")) {
            config.files.upload_dir = Some(upload_dir);
        }
        if let Ok(max_file_size_str) = env::var(format!("{ENV_PREFIX}MAX_FILE_SIZE"))
            && let Ok(max_file_size_val) = max_file_size_str.parse::<usize>()
        {
            config.files.max_file_size = max_file_size_val;
        }
        // Logging config
        if let Ok(level) = env::var(format!("{ENV_PREFIX}LOG_LEVEL")) {
            config.logging.level = level;
        }
        if let Ok(format) = env::var(format!("{ENV_PREFIX}LOG_FORMAT")) {
            config.logging.format = format;
        }
        if let Ok(colors_str) = env::var(format!("{ENV_PREFIX}LOG_COLORS"))
            && let Ok(colors_val) = colors_str.parse::<bool>()
        {
            config.logging.colors = colors_val;
        }
        // UI config
        if let Ok(show_progress_str) = env::var(format!("{ENV_PREFIX}SHOW_PROGRESS"))
            && let Ok(show_progress_val) = show_progress_str.parse::<bool>()
        {
            config.ui.show_progress = show_progress_val;
        }

        if let Ok(progress_style) = env::var(format!("{ENV_PREFIX}PROGRESS_STYLE")) {
            config.ui.progress_style = progress_style;
        }

        if let Ok(refresh_rate_str) = env::var(format!("{ENV_PREFIX}PROGRESS_REFRESH_RATE"))
            && let Ok(refresh_rate_val) = refresh_rate_str.parse::<u64>()
        {
            config.ui.progress_refresh_rate = refresh_rate_val;
        }

        // Proxy config
        if let Ok(proxy_url) = env::var(format!("{ENV_PREFIX}PROXY")) {
            config.proxy = Some(ProxyConfig {
                url: proxy_url,
                user: env::var(format!("{ENV_PREFIX}PROXY_USER")).ok(),
                password: env::var(format!("{ENV_PREFIX}PROXY_PASSWORD")).ok(),
            });
        }

        // Rate limiting config
        if let Ok(enabled_str) = env::var(format!("{ENV_PREFIX}RATE_LIMIT_ENABLED"))
            && let Ok(enabled_val) = enabled_str.parse::<bool>()
        {
            config.rate_limit.enabled = enabled_val;
        }
        if let Ok(limit_str) = env::var(format!("{ENV_PREFIX}RATE_LIMIT_LIMIT"))
            && let Ok(limit_val) = limit_str.parse::<usize>()
        {
            config.rate_limit.limit = limit_val;
        }

        if let Ok(duration_str) = env::var(format!("{ENV_PREFIX}RATE_LIMIT_DURATION"))
            && let Ok(duration_val) = duration_str.parse::<u64>()
        {
            config.rate_limit.duration = duration_val;
        }

        Ok(config)
    }

    /// Merge two configurations, with the second taking precedence
    fn merge_configs(base: Self, overlay: Self) -> Self {
        Self {
            api: ApiConfig {
                token: overlay.api.token.or(base.api.token),
                url: overlay.api.url.or(base.api.url),
                timeout: if overlay.api.timeout == default_timeout() {
                    base.api.timeout
                } else {
                    overlay.api.timeout
                },
                max_retries: if overlay.api.max_retries == default_retries() {
                    base.api.max_retries
                } else {
                    overlay.api.max_retries
                },
            },
            files: FileConfig {
                download_dir: overlay.files.download_dir.or(base.files.download_dir),
                upload_dir: overlay.files.upload_dir.or(base.files.upload_dir),
                max_file_size: if overlay.files.max_file_size == default_max_file_size() {
                    base.files.max_file_size
                } else {
                    overlay.files.max_file_size
                },
                buffer_size: if overlay.files.buffer_size == default_buffer_size() {
                    base.files.buffer_size
                } else {
                    overlay.files.buffer_size
                },
            },
            logging: LoggingConfig {
                level: if overlay.logging.level == default_log_level() {
                    base.logging.level
                } else {
                    overlay.logging.level
                },
                format: if overlay.logging.format == default_log_format() {
                    base.logging.format
                } else {
                    overlay.logging.format
                },
                colors: if overlay.logging.colors == default_log_colors() {
                    base.logging.colors
                } else {
                    overlay.logging.colors
                },
            },
            ui: UiConfig {
                show_progress: if overlay.ui.show_progress == default_show_progress() {
                    base.ui.show_progress
                } else {
                    overlay.ui.show_progress
                },
                progress_style: if overlay.ui.progress_style == default_progress_style() {
                    base.ui.progress_style
                } else {
                    overlay.ui.progress_style
                },
                progress_refresh_rate: if overlay.ui.progress_refresh_rate
                    == default_progress_refresh_rate()
                {
                    base.ui.progress_refresh_rate
                } else {
                    overlay.ui.progress_refresh_rate
                },
            },
            proxy: overlay.proxy.or(base.proxy),
            rate_limit: crate::utils::config_helpers::merge_rate_limit_configs(
                base.rate_limit,
                overlay.rate_limit,
            ),
        }
    }
}

/// Async configuration manager with caching and file watching
#[derive(Debug)]
pub struct AsyncConfigManager {
    cache: Arc<RwLock<Option<(Config, SystemTime)>>>,
    cache_ttl: Duration,
    pub config_paths: Vec<PathBuf>,
}

/// Configuration change event
#[derive(Clone, Debug)]
pub enum ConfigChange {
    FileModified(PathBuf),
    EnvironmentChanged(String),
    ManualUpdate(Box<Config>),
}

/// Lock-free configuration cache for high-performance access
#[derive(Debug, Clone)]
pub struct LockFreeConfigCache {
    cache: Arc<DashMap<String, Arc<Config>>>,
    timestamps: Arc<DashMap<String, Instant>>,
    ttl: Duration,
}

impl Default for AsyncConfigManager {
    fn default() -> Self {
        Self::new(Duration::from_secs(300)) // 5 minutes TTL
    }
}

impl AsyncConfigManager {
    /// Create a new async config manager with specified TTL
    pub fn new(cache_ttl: Duration) -> Self {
        Self {
            cache: Arc::new(RwLock::new(None)),
            cache_ttl,
            config_paths: crate::utils::config_helpers::get_config_paths(),
        }
    }

    /// Load configuration asynchronously with caching
    pub async fn load_config(&self) -> CliResult<Config> {
        // Fast path: check cache first
        {
            let cache = self.cache.read().await;
            if let Some((config, timestamp)) = cache.as_ref()
                && timestamp.elapsed().unwrap_or(Duration::MAX) < self.cache_ttl
            {
                return Ok(config.clone());
            }
        }

        // Slow path: reload from disk asynchronously
        let config = self.load_from_sources().await?;

        // Update cache
        {
            let mut cache = self.cache.write().await;
            *cache = Some((config.clone(), SystemTime::now()));
        }

        Ok(config)
    }

    /// Load configuration from all sources in parallel
    pub async fn load_from_sources(&self) -> CliResult<Config> {
        // Load file configs in parallel
        let file_futures: Vec<_> = self
            .config_paths
            .iter()
            .filter(|path| path.exists())
            .map(|path| self.load_config_file_async(path.clone()))
            .collect();

        let file_configs = futures::future::join_all(file_futures)
            .await
            .into_iter()
            .filter_map(|result| result.ok())
            .collect::<Vec<_>>();

        // Load environment config
        let env_config = Self::from_env_async().await?;

        // Merge all configs efficiently
        let mut final_config = Config::default();
        for config in file_configs {
            final_config = Self::merge_configs_efficient(final_config, config);
        }
        final_config = Self::merge_configs_efficient(final_config, env_config);

        Ok(final_config)
    }

    /// Load a single config file asynchronously
    async fn load_config_file_async(&self, path: PathBuf) -> CliResult<Config> {
        let content = tokio::fs::read_to_string(&path)
            .await
            .map_err(|e| CliError::FileError(format!("Could not read config file: {e}")))?;

        // Parse TOML in a blocking task to avoid blocking the async runtime
        let config = tokio::task::spawn_blocking(move || toml::from_str::<Config>(&content))
            .await
            .map_err(|e| CliError::UnexpectedError(format!("Task join error: {e}")))?
            .map_err(|e| CliError::UnexpectedError(format!("Could not parse config file: {e}")))?;

        Ok(config)
    }

    /// Load environment variables asynchronously
    async fn from_env_async() -> CliResult<Config> {
        // Spawn environment parsing in blocking task
        tokio::task::spawn_blocking(Config::from_env)
            .await
            .map_err(|e| CliError::UnexpectedError(format!("Task join error: {e}")))?
    }

    /// Efficient config merging without intermediate allocations
    pub fn merge_configs_efficient(base: Config, overlay: Config) -> Config {
        Config {
            api: ApiConfig {
                token: overlay.api.token.or(base.api.token),
                url: overlay.api.url.or(base.api.url),
                timeout: if overlay.api.timeout != default_timeout() {
                    overlay.api.timeout
                } else {
                    base.api.timeout
                },
                max_retries: if overlay.api.max_retries != default_retries() {
                    overlay.api.max_retries
                } else {
                    base.api.max_retries
                },
            },
            files: FileConfig {
                download_dir: overlay.files.download_dir.or(base.files.download_dir),
                upload_dir: overlay.files.upload_dir.or(base.files.upload_dir),
                max_file_size: if overlay.files.max_file_size != default_max_file_size() {
                    overlay.files.max_file_size
                } else {
                    base.files.max_file_size
                },
                buffer_size: if overlay.files.buffer_size != default_buffer_size() {
                    overlay.files.buffer_size
                } else {
                    base.files.buffer_size
                },
            },
            logging: LoggingConfig {
                level: if overlay.logging.level != default_log_level() {
                    overlay.logging.level
                } else {
                    base.logging.level
                },
                format: if overlay.logging.format != default_log_format() {
                    overlay.logging.format
                } else {
                    base.logging.format
                },
                colors: if overlay.logging.colors != default_log_colors() {
                    overlay.logging.colors
                } else {
                    base.logging.colors
                },
            },
            ui: UiConfig {
                show_progress: if overlay.ui.show_progress != default_show_progress() {
                    overlay.ui.show_progress
                } else {
                    base.ui.show_progress
                },
                progress_style: if overlay.ui.progress_style != default_progress_style() {
                    overlay.ui.progress_style
                } else {
                    base.ui.progress_style
                },
                progress_refresh_rate: if overlay.ui.progress_refresh_rate
                    != default_progress_refresh_rate()
                {
                    overlay.ui.progress_refresh_rate
                } else {
                    base.ui.progress_refresh_rate
                },
            },
            proxy: overlay.proxy.or(base.proxy),
            rate_limit: overlay.rate_limit, // Use overlay rate_limit directly for simplicity
        }
    }
}

impl LockFreeConfigCache {
    /// Create a new lock-free config cache
    pub fn new(ttl: Duration) -> Self {
        Self {
            cache: Arc::new(DashMap::new()),
            timestamps: Arc::new(DashMap::new()),
            ttl,
        }
    }

    /// Get configuration from cache if valid, otherwise load and cache it
    pub async fn get_or_load<F, Fut>(&self, key: &str, loader: F) -> CliResult<Arc<Config>>
    where
        F: FnOnce() -> Fut,
        Fut: std::future::Future<Output = CliResult<Config>>,
    {
        // Check if we have a valid cached entry
        if let Some(config) = self.cache.get(key)
            && let Some(timestamp) = self.timestamps.get(key)
            && timestamp.elapsed() < self.ttl
        {
            return Ok(config.clone());
        }

        // Load fresh config
        let new_config = Arc::new(loader().await?);

        // Cache the result
        self.cache.insert(key.to_string(), new_config.clone());
        self.timestamps.insert(key.to_string(), Instant::now());

        Ok(new_config)
    }

    /// Invalidate cache entry
    pub fn invalidate(&self, key: &str) {
        self.cache.remove(key);
        self.timestamps.remove(key);
    }

    /// Clear all cache entries
    pub fn clear(&self) {
        self.cache.clear();
        self.timestamps.clear();
    }

    /// Get cache statistics
    pub fn stats(&self) -> (usize, usize) {
        (self.cache.len(), self.timestamps.len())
    }
}