coderlib 0.1.0

A Rust library for AI-powered code assistance and agentic system
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
//! Configuration integration for Edit
//!
//! This module provides seamless integration between CoderLib configuration
//! and Microsoft Edit's configuration system.

use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::path::{Path, PathBuf};
use tokio::fs;
use tracing::{debug, info};

use crate::core::{CoderLibConfig, CoderLibError};
use crate::core::error::ConfigError;
use crate::integration::EditHost;

/// Edit configuration integration
pub struct EditConfigIntegration {
    /// Edit configuration directory
    edit_config_dir: PathBuf,
    /// CoderLib configuration file path
    coderlib_config_path: PathBuf,
    /// Cached configuration
    cached_config: std::sync::RwLock<Option<EditIntegratedConfig>>,
    /// Configuration watchers
    watchers: std::sync::RwLock<Vec<ConfigWatcher>>,
}

/// Integrated configuration combining Edit and CoderLib settings
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct EditIntegratedConfig {
    /// CoderLib core configuration
    pub coderlib: CoderLibConfig,
    /// Edit-specific settings
    pub edit: EditSettings,
    /// UI integration settings
    pub ui: UIIntegrationSettings,
    /// Hotkey bindings
    pub hotkeys: HotkeyBindings,
    /// Plugin settings
    pub plugins: PluginSettings,
    /// Advanced settings
    pub advanced: AdvancedSettings,
}

/// Edit-specific settings
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct EditSettings {
    /// Auto-save interval in seconds
    pub auto_save_interval: u64,
    /// Show line numbers
    pub show_line_numbers: bool,
    /// Tab size
    pub tab_size: usize,
    /// Use spaces instead of tabs
    pub use_spaces: bool,
    /// Word wrap
    pub word_wrap: bool,
    /// Theme name
    pub theme: String,
    /// Font family
    pub font_family: String,
    /// Font size
    pub font_size: u32,
    /// Show whitespace
    pub show_whitespace: bool,
    /// Highlight current line
    pub highlight_current_line: bool,
}

/// UI integration settings
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct UIIntegrationSettings {
    /// AI assistant panel position
    pub ai_panel_position: PanelPosition,
    /// AI panel width (percentage)
    pub ai_panel_width: f32,
    /// AI panel height (percentage)
    pub ai_panel_height: f32,
    /// Show AI suggestions inline
    pub show_inline_suggestions: bool,
    /// Auto-show AI panel on errors
    pub auto_show_on_errors: bool,
    /// Show token usage
    pub show_token_usage: bool,
    /// Animation duration in milliseconds
    pub animation_duration: u32,
    /// Transparency level (0.0 to 1.0)
    pub transparency: f32,
}

/// Panel position options
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub enum PanelPosition {
    Right,
    Left,
    Bottom,
    Top,
    Floating { x: i32, y: i32 },
}

/// Hotkey bindings
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct HotkeyBindings {
    /// Activate AI assistant
    pub ai_assistant: String,
    /// Quick code explanation
    pub explain_code: String,
    /// Refactor selection
    pub refactor_selection: String,
    /// Generate tests
    pub generate_tests: String,
    /// Fix errors
    pub fix_errors: String,
    /// Format code
    pub format_code: String,
    /// Toggle AI panel
    pub toggle_ai_panel: String,
    /// Accept AI suggestion
    pub accept_suggestion: String,
    /// Reject AI suggestion
    pub reject_suggestion: String,
}

/// Plugin settings
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PluginSettings {
    /// Enable CoderLib plugin
    pub enabled: bool,
    /// Auto-start on Edit launch
    pub auto_start: bool,
    /// Plugin priority
    pub priority: i32,
    /// Allowed permissions
    pub allowed_permissions: Vec<String>,
    /// Resource limits
    pub resource_limits: ResourceLimits,
    /// Update settings
    pub updates: UpdateSettings,
}

/// Resource limits for the plugin
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ResourceLimits {
    /// Maximum memory usage in MB
    pub max_memory_mb: u64,
    /// Maximum CPU usage percentage
    pub max_cpu_percent: f32,
    /// Maximum network requests per minute
    pub max_network_requests: u32,
    /// Maximum file operations per minute
    pub max_file_operations: u32,
}

/// Update settings
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct UpdateSettings {
    /// Auto-check for updates
    pub auto_check: bool,
    /// Update channel (stable, beta, nightly)
    pub channel: String,
    /// Check interval in hours
    pub check_interval_hours: u32,
    /// Auto-install updates
    pub auto_install: bool,
}

/// Advanced settings
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AdvancedSettings {
    /// Debug mode
    pub debug_mode: bool,
    /// Log level
    pub log_level: String,
    /// Performance monitoring
    pub performance_monitoring: bool,
    /// Telemetry enabled
    pub telemetry_enabled: bool,
    /// Custom environment variables
    pub environment_variables: HashMap<String, String>,
    /// Feature flags
    pub feature_flags: HashMap<String, bool>,
    /// Experimental features
    pub experimental_features: Vec<String>,
}

/// Configuration watcher for live updates
pub struct ConfigWatcher {
    /// File path being watched
    pub path: PathBuf,
    /// Last modification time
    pub last_modified: std::time::SystemTime,
    /// Callback for changes
    pub callback: Box<dyn Fn(&Path) + Send + Sync>,
}

impl std::fmt::Debug for ConfigWatcher {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("ConfigWatcher")
            .field("path", &self.path)
            .field("last_modified", &self.last_modified)
            .field("callback", &"<callback function>")
            .finish()
    }
}

impl Default for EditSettings {
    fn default() -> Self {
        Self {
            auto_save_interval: 30,
            show_line_numbers: true,
            tab_size: 4,
            use_spaces: true,
            word_wrap: false,
            theme: "dark".to_string(),
            font_family: "Consolas".to_string(),
            font_size: 14,
            show_whitespace: false,
            highlight_current_line: true,
        }
    }
}

impl Default for UIIntegrationSettings {
    fn default() -> Self {
        Self {
            ai_panel_position: PanelPosition::Right,
            ai_panel_width: 40.0,
            ai_panel_height: 60.0,
            show_inline_suggestions: true,
            auto_show_on_errors: false,
            show_token_usage: true,
            animation_duration: 300,
            transparency: 0.95,
        }
    }
}

impl Default for HotkeyBindings {
    fn default() -> Self {
        Self {
            ai_assistant: "Ctrl+I".to_string(),
            explain_code: "Ctrl+Shift+E".to_string(),
            refactor_selection: "Ctrl+Shift+R".to_string(),
            generate_tests: "Ctrl+Shift+T".to_string(),
            fix_errors: "Ctrl+Shift+F".to_string(),
            format_code: "Ctrl+Shift+P".to_string(),
            toggle_ai_panel: "Ctrl+Alt+A".to_string(),
            accept_suggestion: "Tab".to_string(),
            reject_suggestion: "Escape".to_string(),
        }
    }
}

impl Default for PluginSettings {
    fn default() -> Self {
        Self {
            enabled: true,
            auto_start: true,
            priority: 100,
            allowed_permissions: vec![
                "file_read".to_string(),
                "file_write".to_string(),
                "network_access".to_string(),
            ],
            resource_limits: ResourceLimits::default(),
            updates: UpdateSettings::default(),
        }
    }
}

impl Default for ResourceLimits {
    fn default() -> Self {
        Self {
            max_memory_mb: 512,
            max_cpu_percent: 25.0,
            max_network_requests: 100,
            max_file_operations: 50,
        }
    }
}

impl Default for UpdateSettings {
    fn default() -> Self {
        Self {
            auto_check: true,
            channel: "stable".to_string(),
            check_interval_hours: 24,
            auto_install: false,
        }
    }
}

impl Default for AdvancedSettings {
    fn default() -> Self {
        Self {
            debug_mode: false,
            log_level: "info".to_string(),
            performance_monitoring: false,
            telemetry_enabled: true,
            environment_variables: HashMap::new(),
            feature_flags: HashMap::new(),
            experimental_features: Vec::new(),
        }
    }
}

impl EditConfigIntegration {
    /// Create a new configuration integration
    pub fn new(edit_config_dir: PathBuf) -> Self {
        let coderlib_config_path = edit_config_dir.join("coderlib.toml");
        
        Self {
            edit_config_dir,
            coderlib_config_path,
            cached_config: std::sync::RwLock::new(None),
            watchers: std::sync::RwLock::new(Vec::new()),
        }
    }

    /// Load the integrated configuration
    pub async fn load_config(&self) -> Result<EditIntegratedConfig, CoderLibError> {
        info!("Loading integrated configuration");

        // Check cache first
        if let Ok(cache) = self.cached_config.read() {
            if let Some(config) = cache.as_ref() {
                debug!("Using cached configuration");
                return Ok(config.clone());
            }
        }

        // Load CoderLib configuration
        let coderlib_config = if self.coderlib_config_path.exists() {
            self.load_coderlib_config().await?
        } else {
            info!("CoderLib config not found, using defaults");
            CoderLibConfig::default()
        };

        // Load Edit-specific settings
        let edit_settings = self.load_edit_settings().await?;
        let ui_settings = self.load_ui_settings().await?;
        let hotkeys = self.load_hotkey_bindings().await?;
        let plugins = self.load_plugin_settings().await?;
        let advanced = self.load_advanced_settings().await?;

        let integrated_config = EditIntegratedConfig {
            coderlib: coderlib_config,
            edit: edit_settings,
            ui: ui_settings,
            hotkeys,
            plugins,
            advanced,
        };

        // Cache the configuration
        if let Ok(mut cache) = self.cached_config.write() {
            *cache = Some(integrated_config.clone());
        }

        Ok(integrated_config)
    }

    /// Save the integrated configuration
    pub async fn save_config(&self, config: &EditIntegratedConfig) -> Result<(), CoderLibError> {
        info!("Saving integrated configuration");

        // Save CoderLib configuration
        self.save_coderlib_config(&config.coderlib).await?;

        // Save Edit-specific settings
        self.save_edit_settings(&config.edit).await?;
        self.save_ui_settings(&config.ui).await?;
        self.save_hotkey_bindings(&config.hotkeys).await?;
        self.save_plugin_settings(&config.plugins).await?;
        self.save_advanced_settings(&config.advanced).await?;

        // Update cache
        if let Ok(mut cache) = self.cached_config.write() {
            *cache = Some(config.clone());
        }

        info!("Configuration saved successfully");
        Ok(())
    }

    /// Load CoderLib configuration from file
    async fn load_coderlib_config(&self) -> Result<CoderLibConfig, CoderLibError> {
        let content = fs::read_to_string(&self.coderlib_config_path).await
            .map_err(|e| CoderLibError::Config(ConfigError::LoadFailed(format!("Failed to read config: {}", e))))?;

        toml::from_str(&content)
            .map_err(|e| CoderLibError::Config(ConfigError::ParseFailed(format!("Failed to parse config: {}", e))))
    }

    /// Save CoderLib configuration to file
    async fn save_coderlib_config(&self, config: &CoderLibConfig) -> Result<(), CoderLibError> {
        let content = toml::to_string_pretty(config)
            .map_err(|e| CoderLibError::Config(ConfigError::ParseFailed(format!("Failed to serialize config: {}", e))))?;

        // Ensure directory exists
        if let Some(parent) = self.coderlib_config_path.parent() {
            fs::create_dir_all(parent).await
                .map_err(|e| CoderLibError::Io(e))?;
        }

        fs::write(&self.coderlib_config_path, content).await
            .map_err(|e| CoderLibError::Io(e))?;

        Ok(())
    }

    /// Load Edit-specific settings
    async fn load_edit_settings(&self) -> Result<EditSettings, CoderLibError> {
        let settings_path = self.edit_config_dir.join("edit_settings.toml");

        if settings_path.exists() {
            let content = fs::read_to_string(&settings_path).await
                .map_err(|e| CoderLibError::Config(ConfigError::LoadFailed(format!("Failed to read Edit settings: {}", e))))?;

            toml::from_str(&content)
                .map_err(|e| CoderLibError::Config(ConfigError::ParseFailed(format!("Failed to parse Edit settings: {}", e))))
        } else {
            Ok(EditSettings::default())
        }
    }

    /// Save Edit-specific settings
    async fn save_edit_settings(&self, settings: &EditSettings) -> Result<(), CoderLibError> {
        let settings_path = self.edit_config_dir.join("edit_settings.toml");
        let content = toml::to_string_pretty(settings)
            .map_err(|e| CoderLibError::Config(ConfigError::ParseFailed(format!("Failed to serialize Edit settings: {}", e))))?;

        fs::write(&settings_path, content).await
            .map_err(|e| CoderLibError::Io(e))?;

        Ok(())
    }

    /// Load UI integration settings
    async fn load_ui_settings(&self) -> Result<UIIntegrationSettings, CoderLibError> {
        let settings_path = self.edit_config_dir.join("ui_integration.toml");

        if settings_path.exists() {
            let content = fs::read_to_string(&settings_path).await
                .map_err(|e| CoderLibError::Config(ConfigError::LoadFailed(format!("Failed to read UI settings: {}", e))))?;

            toml::from_str(&content)
                .map_err(|e| CoderLibError::Config(ConfigError::ParseFailed(format!("Failed to parse UI settings: {}", e))))
        } else {
            Ok(UIIntegrationSettings::default())
        }
    }

    /// Save UI integration settings
    async fn save_ui_settings(&self, settings: &UIIntegrationSettings) -> Result<(), CoderLibError> {
        let settings_path = self.edit_config_dir.join("ui_integration.toml");
        let content = toml::to_string_pretty(settings)
            .map_err(|e| CoderLibError::Config(ConfigError::ParseFailed(format!("Failed to serialize UI settings: {}", e))))?;

        fs::write(&settings_path, content).await
            .map_err(|e| CoderLibError::Io(e))?;

        Ok(())
    }

    /// Load hotkey bindings
    async fn load_hotkey_bindings(&self) -> Result<HotkeyBindings, CoderLibError> {
        let bindings_path = self.edit_config_dir.join("hotkeys.toml");

        if bindings_path.exists() {
            let content = fs::read_to_string(&bindings_path).await
                .map_err(|e| CoderLibError::Config(ConfigError::LoadFailed(format!("Failed to read hotkey bindings: {}", e))))?;

            toml::from_str(&content)
                .map_err(|e| CoderLibError::Config(ConfigError::ParseFailed(format!("Failed to parse hotkey bindings: {}", e))))
        } else {
            Ok(HotkeyBindings::default())
        }
    }

    /// Save hotkey bindings
    async fn save_hotkey_bindings(&self, bindings: &HotkeyBindings) -> Result<(), CoderLibError> {
        let bindings_path = self.edit_config_dir.join("hotkeys.toml");
        let content = toml::to_string_pretty(bindings)
            .map_err(|e| CoderLibError::Config(ConfigError::ParseFailed(format!("Failed to serialize hotkey bindings: {}", e))))?;

        fs::write(&bindings_path, content).await
            .map_err(|e| CoderLibError::Io(e))?;

        Ok(())
    }

    /// Load plugin settings
    async fn load_plugin_settings(&self) -> Result<PluginSettings, CoderLibError> {
        let settings_path = self.edit_config_dir.join("plugin_settings.toml");

        if settings_path.exists() {
            let content = fs::read_to_string(&settings_path).await
                .map_err(|e| CoderLibError::Config(ConfigError::LoadFailed(format!("Failed to read plugin settings: {}", e))))?;

            toml::from_str(&content)
                .map_err(|e| CoderLibError::Config(ConfigError::ParseFailed(format!("Failed to parse plugin settings: {}", e))))
        } else {
            Ok(PluginSettings::default())
        }
    }

    /// Save plugin settings
    async fn save_plugin_settings(&self, settings: &PluginSettings) -> Result<(), CoderLibError> {
        let settings_path = self.edit_config_dir.join("plugin_settings.toml");
        let content = toml::to_string_pretty(settings)
            .map_err(|e| CoderLibError::Config(ConfigError::ParseFailed(format!("Failed to serialize plugin settings: {}", e))))?;

        fs::write(&settings_path, content).await
            .map_err(|e| CoderLibError::Io(e))?;

        Ok(())
    }

    /// Load advanced settings
    async fn load_advanced_settings(&self) -> Result<AdvancedSettings, CoderLibError> {
        let settings_path = self.edit_config_dir.join("advanced_settings.toml");

        if settings_path.exists() {
            let content = fs::read_to_string(&settings_path).await
                .map_err(|e| CoderLibError::Config(ConfigError::LoadFailed(format!("Failed to read advanced settings: {}", e))))?;

            toml::from_str(&content)
                .map_err(|e| CoderLibError::Config(ConfigError::ParseFailed(format!("Failed to parse advanced settings: {}", e))))
        } else {
            Ok(AdvancedSettings::default())
        }
    }

    /// Save advanced settings
    async fn save_advanced_settings(&self, settings: &AdvancedSettings) -> Result<(), CoderLibError> {
        let settings_path = self.edit_config_dir.join("advanced_settings.toml");
        let content = toml::to_string_pretty(settings)
            .map_err(|e| CoderLibError::Config(ConfigError::ParseFailed(format!("Failed to serialize advanced settings: {}", e))))?;

        fs::write(&settings_path, content).await
            .map_err(|e| CoderLibError::Io(e))?;

        Ok(())
    }

    /// Start watching configuration files for changes
    pub async fn start_watching(&self) -> Result<(), CoderLibError> {
        info!("Starting configuration file watching");

        let config_files = vec![
            self.coderlib_config_path.clone(),
            self.edit_config_dir.join("edit_settings.toml"),
            self.edit_config_dir.join("ui_integration.toml"),
            self.edit_config_dir.join("hotkeys.toml"),
            self.edit_config_dir.join("plugin_settings.toml"),
            self.edit_config_dir.join("advanced_settings.toml"),
        ];

        let mut watchers = self.watchers.write().unwrap();

        for config_file in config_files {
            if config_file.exists() {
                let metadata = fs::metadata(&config_file).await
                    .map_err(|e| CoderLibError::Io(e))?;

                let last_modified = metadata.modified()
                    .map_err(|e| CoderLibError::Io(e))?;

                let watcher = ConfigWatcher {
                    path: config_file.clone(),
                    last_modified,
                    callback: Box::new(move |path| {
                        info!("Configuration file changed: {}", path.display());
                        // TODO: Implement actual file change handling
                    }),
                };

                watchers.push(watcher);
            }
        }

        info!("Configuration watching started for {} files", watchers.len());
        Ok(())
    }

    /// Stop watching configuration files
    pub fn stop_watching(&self) {
        let mut watchers = self.watchers.write().unwrap();
        watchers.clear();
        info!("Configuration watching stopped");
    }

    /// Check for configuration file changes
    pub async fn check_for_changes(&self) -> Result<Vec<PathBuf>, CoderLibError> {
        let mut changed_files = Vec::new();
        let mut watchers = self.watchers.write().unwrap();

        for watcher in watchers.iter_mut() {
            if watcher.path.exists() {
                let metadata = fs::metadata(&watcher.path).await
                    .map_err(|e| CoderLibError::Io(e))?;

                let current_modified = metadata.modified()
                    .map_err(|e| CoderLibError::Io(e))?;

                if current_modified > watcher.last_modified {
                    changed_files.push(watcher.path.clone());
                    watcher.last_modified = current_modified;
                    (watcher.callback)(&watcher.path);
                }
            }
        }

        if !changed_files.is_empty() {
            // Invalidate cache
            if let Ok(mut cache) = self.cached_config.write() {
                *cache = None;
            }
        }

        Ok(changed_files)
    }

    /// Apply configuration to Edit host
    pub async fn apply_to_edit_host(&self, edit_host: &mut EditHost, config: &EditIntegratedConfig) -> Result<(), CoderLibError> {
        info!("Applying configuration to Edit host");

        // Apply Edit settings
        // TODO: Implement actual Edit host configuration application
        debug!("Applied Edit settings: theme={}, font_size={}", config.edit.theme, config.edit.font_size);

        // Apply UI settings
        debug!("Applied UI settings: panel_position={:?}, panel_width={}", config.ui.ai_panel_position, config.ui.ai_panel_width);

        // Apply hotkey bindings
        debug!("Applied hotkey bindings: ai_assistant={}", config.hotkeys.ai_assistant);

        // Apply plugin settings
        debug!("Applied plugin settings: enabled={}, auto_start={}", config.plugins.enabled, config.plugins.auto_start);

        info!("Configuration applied successfully to Edit host");
        Ok(())
    }

    /// Validate configuration
    pub fn validate_config(&self, config: &EditIntegratedConfig) -> Result<(), CoderLibError> {
        // Validate Edit settings
        if config.edit.tab_size == 0 {
            return Err(CoderLibError::Config(ConfigError::InvalidValue("Tab size must be greater than 0".to_string())));
        }

        if config.edit.font_size < 8 || config.edit.font_size > 72 {
            return Err(CoderLibError::Config(ConfigError::InvalidValue("Font size must be between 8 and 72".to_string())));
        }

        // Validate UI settings
        if config.ui.ai_panel_width <= 0.0 || config.ui.ai_panel_width > 100.0 {
            return Err(CoderLibError::Config(ConfigError::InvalidValue("AI panel width must be between 0 and 100 percent".to_string())));
        }

        if config.ui.ai_panel_height <= 0.0 || config.ui.ai_panel_height > 100.0 {
            return Err(CoderLibError::Config(ConfigError::InvalidValue("AI panel height must be between 0 and 100 percent".to_string())));
        }

        if config.ui.transparency < 0.0 || config.ui.transparency > 1.0 {
            return Err(CoderLibError::Config(ConfigError::InvalidValue("Transparency must be between 0.0 and 1.0".to_string())));
        }

        // Validate resource limits
        if config.plugins.resource_limits.max_memory_mb == 0 {
            return Err(CoderLibError::Config(ConfigError::InvalidValue("Maximum memory must be greater than 0".to_string())));
        }

        if config.plugins.resource_limits.max_cpu_percent <= 0.0 || config.plugins.resource_limits.max_cpu_percent > 100.0 {
            return Err(CoderLibError::Config(ConfigError::InvalidValue("Maximum CPU percentage must be between 0 and 100".to_string())));
        }

        // Validate update settings
        if !["stable", "beta", "nightly"].contains(&config.plugins.updates.channel.as_str()) {
            return Err(CoderLibError::Config(ConfigError::InvalidValue("Update channel must be 'stable', 'beta', or 'nightly'".to_string())));
        }

        // Validate log level
        if !["error", "warn", "info", "debug", "trace"].contains(&config.advanced.log_level.as_str()) {
            return Err(CoderLibError::Config(ConfigError::InvalidValue("Log level must be one of: error, warn, info, debug, trace".to_string())));
        }

        Ok(())
    }

    /// Get configuration schema for UI generation
    pub fn get_config_schema(&self) -> serde_json::Value {
        serde_json::json!({
            "type": "object",
            "properties": {
                "edit": {
                    "type": "object",
                    "title": "Edit Settings",
                    "properties": {
                        "auto_save_interval": {
                            "type": "integer",
                            "title": "Auto-save interval (seconds)",
                            "minimum": 1,
                            "maximum": 3600,
                            "default": 30
                        },
                        "show_line_numbers": {
                            "type": "boolean",
                            "title": "Show line numbers",
                            "default": true
                        },
                        "tab_size": {
                            "type": "integer",
                            "title": "Tab size",
                            "minimum": 1,
                            "maximum": 16,
                            "default": 4
                        },
                        "theme": {
                            "type": "string",
                            "title": "Theme",
                            "enum": ["light", "dark", "auto"],
                            "default": "dark"
                        },
                        "font_family": {
                            "type": "string",
                            "title": "Font family",
                            "default": "Consolas"
                        },
                        "font_size": {
                            "type": "integer",
                            "title": "Font size",
                            "minimum": 8,
                            "maximum": 72,
                            "default": 14
                        }
                    }
                },
                "ui": {
                    "type": "object",
                    "title": "UI Integration",
                    "properties": {
                        "ai_panel_position": {
                            "type": "string",
                            "title": "AI panel position",
                            "enum": ["Right", "Left", "Bottom", "Top"],
                            "default": "Right"
                        },
                        "ai_panel_width": {
                            "type": "number",
                            "title": "AI panel width (%)",
                            "minimum": 10.0,
                            "maximum": 80.0,
                            "default": 40.0
                        },
                        "show_inline_suggestions": {
                            "type": "boolean",
                            "title": "Show inline suggestions",
                            "default": true
                        },
                        "show_token_usage": {
                            "type": "boolean",
                            "title": "Show token usage",
                            "default": true
                        }
                    }
                },
                "hotkeys": {
                    "type": "object",
                    "title": "Hotkey Bindings",
                    "properties": {
                        "ai_assistant": {
                            "type": "string",
                            "title": "Activate AI assistant",
                            "default": "Ctrl+I"
                        },
                        "explain_code": {
                            "type": "string",
                            "title": "Explain code",
                            "default": "Ctrl+Shift+E"
                        },
                        "refactor_selection": {
                            "type": "string",
                            "title": "Refactor selection",
                            "default": "Ctrl+Shift+R"
                        }
                    }
                }
            }
        })
    }

    /// Export configuration for backup
    pub async fn export_config(&self) -> Result<String, CoderLibError> {
        let config = self.load_config().await?;
        serde_json::to_string_pretty(&config)
            .map_err(|e| CoderLibError::Config(ConfigError::ParseFailed(format!("Failed to export config: {}", e))))
    }

    /// Import configuration from backup
    pub async fn import_config(&self, config_json: &str) -> Result<(), CoderLibError> {
        let config: EditIntegratedConfig = serde_json::from_str(config_json)
            .map_err(|e| CoderLibError::Config(ConfigError::ParseFailed(format!("Failed to parse imported config: {}", e))))?;

        self.validate_config(&config)?;
        self.save_config(&config).await?;

        info!("Configuration imported successfully");
        Ok(())
    }
}