runmat 0.0.17

High-performance MATLAB/Octave runtime with Jupyter kernel support
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
//! Configuration system for RunMat
//!
//! Supports multiple configuration sources with proper precedence:
//! 1. Command-line arguments (highest priority)
//! 2. Environment variables  
//! 3. Configuration files (.runmat.yaml, .runmat.json, etc.)
//! 4. Built-in defaults (lowest priority)

use anyhow::{Context, Result};
use clap::ValueEnum;
use log::{debug, info};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::env;
use std::fs;
use std::path::{Path, PathBuf};

/// Main RunMat configuration
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct RunMatConfig {
    /// Runtime configuration
    pub runtime: RuntimeConfig,
    /// JIT compiler configuration
    pub jit: JitConfig,
    /// Garbage collector configuration
    pub gc: GcConfig,
    /// Plotting configuration
    pub plotting: PlottingConfig,
    /// Kernel configuration
    pub kernel: KernelConfig,
    /// Logging configuration
    pub logging: LoggingConfig,
    /// Package manager configuration
    #[serde(default)]
    pub packages: PackagesConfig,
}

/// Runtime execution configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RuntimeConfig {
    /// Execution timeout in seconds
    #[serde(default = "default_timeout")]
    pub timeout: u64,
    /// Enable verbose output
    #[serde(default)]
    pub verbose: bool,
    /// Snapshot file to preload
    pub snapshot_path: Option<PathBuf>,
}

/// JIT compiler configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct JitConfig {
    /// Enable JIT compilation
    #[serde(default = "default_true")]
    pub enabled: bool,
    /// JIT compilation threshold
    #[serde(default = "default_jit_threshold")]
    pub threshold: u32,
    /// JIT optimization level
    #[serde(default)]
    pub optimization_level: JitOptLevel,
}

/// GC configuration
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct GcConfig {
    /// GC preset
    pub preset: Option<GcPreset>,
    /// Young generation size in MB
    pub young_size_mb: Option<usize>,
    /// Number of GC threads
    pub threads: Option<usize>,
    /// Enable GC statistics collection
    #[serde(default)]
    pub collect_stats: bool,
}

/// Plotting configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PlottingConfig {
    /// Plotting mode
    #[serde(default)]
    pub mode: PlotMode,
    /// Force headless mode
    #[serde(default)]
    pub force_headless: bool,
    /// Default plot backend
    #[serde(default)]
    pub backend: PlotBackend,
    /// GUI settings
    pub gui: Option<GuiConfig>,
    /// Export settings
    pub export: Option<ExportConfig>,
}

/// GUI configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GuiConfig {
    /// Window width
    #[serde(default = "default_window_width")]
    pub width: u32,
    /// Window height
    #[serde(default = "default_window_height")]
    pub height: u32,
    /// Enable VSync
    #[serde(default = "default_true")]
    pub vsync: bool,
    /// Enable maximized window
    #[serde(default)]
    pub maximized: bool,
}

/// Export configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ExportConfig {
    /// Default export format
    #[serde(default)]
    pub format: ExportFormat,
    /// Default DPI for raster exports
    #[serde(default = "default_dpi")]
    pub dpi: u32,
    /// Default output directory
    pub output_dir: Option<PathBuf>,
    /// Jupyter notebook configuration
    pub jupyter: Option<JupyterConfig>,
}

/// Jupyter notebook integration configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct JupyterConfig {
    /// Default output format for Jupyter cells
    #[serde(default)]
    pub output_format: JupyterOutputFormat,
    /// Enable interactive widgets
    #[serde(default = "default_true")]
    pub enable_widgets: bool,
    /// Enable static image fallback
    #[serde(default = "default_true")]
    pub enable_static_fallback: bool,
    /// Widget configuration
    pub widget: Option<JupyterWidgetConfig>,
    /// Static export configuration
    pub static_export: Option<JupyterStaticConfig>,
    /// Performance settings
    pub performance: Option<JupyterPerformanceConfig>,
}

/// Jupyter widget configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct JupyterWidgetConfig {
    /// Enable client-side rendering (WebAssembly)
    #[serde(default = "default_true")]
    pub client_side_rendering: bool,
    /// Enable server-side streaming
    #[serde(default)]
    pub server_side_streaming: bool,
    /// Widget cache size in MB
    #[serde(default = "default_widget_cache_size")]
    pub cache_size_mb: u32,
    /// Update frequency for animations (FPS)
    #[serde(default = "default_widget_fps")]
    pub update_fps: u32,
    /// Enable GPU acceleration in browser
    #[serde(default = "default_true")]
    pub gpu_acceleration: bool,
}

/// Jupyter static export configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct JupyterStaticConfig {
    /// Image width in pixels
    #[serde(default = "default_jupyter_width")]
    pub width: u32,
    /// Image height in pixels
    #[serde(default = "default_jupyter_height")]
    pub height: u32,
    /// Image quality (0.0-1.0)
    #[serde(default = "default_jupyter_quality")]
    pub quality: f32,
    /// Include metadata in exports
    #[serde(default = "default_true")]
    pub include_metadata: bool,
    /// Preferred formats in order of preference
    #[serde(default)]
    pub preferred_formats: Vec<JupyterOutputFormat>,
}

/// Jupyter performance configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct JupyterPerformanceConfig {
    /// Maximum render time per frame (ms)
    #[serde(default = "default_max_render_time")]
    pub max_render_time_ms: u32,
    /// Enable progressive rendering
    #[serde(default = "default_true")]
    pub progressive_rendering: bool,
    /// LOD (Level of Detail) threshold
    #[serde(default = "default_lod_threshold")]
    pub lod_threshold: u32,
    /// Enable texture compression
    #[serde(default = "default_true")]
    pub texture_compression: bool,
}

/// Kernel configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct KernelConfig {
    /// Default IP address
    #[serde(default = "default_kernel_ip")]
    pub ip: String,
    /// Authentication key
    pub key: Option<String>,
    /// Port configuration
    pub ports: Option<KernelPorts>,
}

/// Kernel port configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct KernelPorts {
    pub shell: Option<u16>,
    pub iopub: Option<u16>,
    pub stdin: Option<u16>,
    pub control: Option<u16>,
    pub heartbeat: Option<u16>,
}

/// Package manager configuration
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct PackagesConfig {
    /// Enable package manager
    #[serde(default = "default_true")]
    pub enabled: bool,
    /// Registries to search for packages (first match wins)
    #[serde(default = "default_registries")]
    pub registries: Vec<Registry>,
    /// Dependencies declared by the workspace (name -> spec)
    #[serde(default)]
    pub dependencies: HashMap<String, PackageSpec>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Registry {
    /// Registry logical name
    pub name: String,
    /// Base URL for index/API (e.g., https://packages.runmat.org)
    pub url: String,
}

/// Package specification
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "source", rename_all = "kebab-case")]
pub enum PackageSpec {
    /// Resolve from a registry by name
    Registry {
        /// Semver range (e.g. "^1.2"), or exact version
        version: String,
        /// Optional registry override (defaults to first registry)
        #[serde(default)]
        registry: Option<String>,
        /// Optional feature flags
        #[serde(default)]
        features: Vec<String>,
        /// Optional mark for optional dependency
        #[serde(default)]
        optional: bool,
    },
    /// Git repository
    Git {
        url: String,
        #[serde(default)]
        rev: Option<String>,
        #[serde(default)]
        features: Vec<String>,
        #[serde(default)]
        optional: bool,
    },
    /// Local path dependency (useful for development)
    Path {
        path: String,
        #[serde(default)]
        features: Vec<String>,
        #[serde(default)]
        optional: bool,
    },
}

/// Logging configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LoggingConfig {
    /// Log level
    #[serde(default)]
    pub level: LogLevel,
    /// Enable debug logging
    #[serde(default)]
    pub debug: bool,
    /// Log file path
    pub file: Option<PathBuf>,
}

/// Plotting mode enumeration
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, ValueEnum)]
#[serde(rename_all = "lowercase")]
pub enum PlotMode {
    /// Automatic detection based on environment
    Auto,
    /// Force GUI mode
    Gui,
    /// Force headless/static mode
    Headless,
    /// Jupyter notebook mode
    Jupyter,
}

/// Plot backend enumeration
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, ValueEnum)]
#[serde(rename_all = "lowercase")]
pub enum PlotBackend {
    /// Automatic backend selection
    Auto,
    /// WGPU GPU-accelerated backend
    Wgpu,
    /// Static plotters backend
    Static,
    /// Web/browser backend
    Web,
}

/// Export format enumeration
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum ExportFormat {
    Png,
    Svg,
    Pdf,
    Html,
}

/// Jupyter-specific output formats
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum JupyterOutputFormat {
    /// Interactive HTML widget with WebAssembly
    Widget,
    /// Static PNG image
    Png,
    /// Static SVG image
    Svg,
    /// Base64-encoded image
    Base64,
    /// Plotly-compatible JSON
    PlotlyJson,
    /// Auto-detect based on environment
    Auto,
}

/// JIT optimization level
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum JitOptLevel {
    None,
    Size,
    Speed,
    Aggressive,
}

/// GC preset
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum GcPreset {
    LowLatency,
    HighThroughput,
    LowMemory,
    Debug,
}

/// Log level
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum LogLevel {
    Error,
    Warn,
    Info,
    Debug,
    Trace,
}

// Default value functions
fn default_timeout() -> u64 {
    300
}
fn default_true() -> bool {
    true
}
fn default_jit_threshold() -> u32 {
    10
}
fn default_window_width() -> u32 {
    1200
}
fn default_window_height() -> u32 {
    800
}
fn default_dpi() -> u32 {
    300
}
fn default_kernel_ip() -> String {
    "127.0.0.1".to_string()
}

fn default_widget_cache_size() -> u32 {
    64 // 64MB cache
}

fn default_widget_fps() -> u32 {
    30 // 30 FPS for smooth animations
}

fn default_jupyter_width() -> u32 {
    800
}

fn default_jupyter_height() -> u32 {
    600
}

fn default_jupyter_quality() -> f32 {
    0.9 // High quality (0.0-1.0)
}

fn default_max_render_time() -> u32 {
    16 // 16ms for 60 FPS
}

fn default_lod_threshold() -> u32 {
    10000 // Points threshold for LOD
}

fn default_registries() -> Vec<Registry> {
    vec![Registry {
        name: "runmat".to_string(),
        url: "https://packages.runmat.org".to_string(),
    }]
}

impl Default for RuntimeConfig {
    fn default() -> Self {
        Self {
            timeout: default_timeout(),
            verbose: false,
            snapshot_path: None,
        }
    }
}

impl Default for JitConfig {
    fn default() -> Self {
        Self {
            enabled: true,
            threshold: default_jit_threshold(),
            optimization_level: JitOptLevel::Speed,
        }
    }
}

impl Default for PlottingConfig {
    fn default() -> Self {
        Self {
            mode: PlotMode::Auto,
            force_headless: false,
            backend: PlotBackend::Auto,
            gui: Some(GuiConfig::default()),
            export: Some(ExportConfig::default()),
        }
    }
}

impl Default for GuiConfig {
    fn default() -> Self {
        Self {
            width: default_window_width(),
            height: default_window_height(),
            vsync: true,
            maximized: false,
        }
    }
}

impl Default for ExportConfig {
    fn default() -> Self {
        Self {
            format: ExportFormat::Png,
            dpi: default_dpi(),
            output_dir: None,
            jupyter: Some(JupyterConfig::default()),
        }
    }
}

impl Default for KernelConfig {
    fn default() -> Self {
        Self {
            ip: default_kernel_ip(),
            key: None,
            ports: None,
        }
    }
}

impl Default for LoggingConfig {
    fn default() -> Self {
        Self {
            level: LogLevel::Info,
            debug: false,
            file: None,
        }
    }
}

impl Default for PlotMode {
    fn default() -> Self {
        Self::Auto
    }
}

impl Default for PlotBackend {
    fn default() -> Self {
        Self::Auto
    }
}

impl Default for ExportFormat {
    fn default() -> Self {
        Self::Png
    }
}

impl Default for JitOptLevel {
    fn default() -> Self {
        Self::Speed
    }
}

impl Default for LogLevel {
    fn default() -> Self {
        Self::Info
    }
}

impl Default for JupyterOutputFormat {
    fn default() -> Self {
        Self::Auto
    }
}

impl Default for JupyterConfig {
    fn default() -> Self {
        Self {
            output_format: JupyterOutputFormat::default(),
            enable_widgets: true,
            enable_static_fallback: true,
            widget: Some(JupyterWidgetConfig::default()),
            static_export: Some(JupyterStaticConfig::default()),
            performance: Some(JupyterPerformanceConfig::default()),
        }
    }
}

impl Default for JupyterWidgetConfig {
    fn default() -> Self {
        Self {
            client_side_rendering: true,
            server_side_streaming: false,
            cache_size_mb: default_widget_cache_size(),
            update_fps: default_widget_fps(),
            gpu_acceleration: true,
        }
    }
}

impl Default for JupyterStaticConfig {
    fn default() -> Self {
        Self {
            width: default_jupyter_width(),
            height: default_jupyter_height(),
            quality: default_jupyter_quality(),
            include_metadata: true,
            preferred_formats: vec![
                JupyterOutputFormat::Widget,
                JupyterOutputFormat::Png,
                JupyterOutputFormat::Svg,
            ],
        }
    }
}

impl Default for JupyterPerformanceConfig {
    fn default() -> Self {
        Self {
            max_render_time_ms: default_max_render_time(),
            progressive_rendering: true,
            lod_threshold: default_lod_threshold(),
            texture_compression: true,
        }
    }
}

/// Configuration loader with multiple source support
pub struct ConfigLoader;

impl ConfigLoader {
    /// Load configuration from all sources with proper precedence
    pub fn load() -> Result<RunMatConfig> {
        let mut config = Self::load_from_files()?;
        Self::apply_environment_variables(&mut config)?;
        Ok(config)
    }

    /// Find and load configuration from files
    fn load_from_files() -> Result<RunMatConfig> {
        // Try to find config file in order of preference
        let config_paths = Self::find_config_files();

        for path in config_paths {
            if path.exists() {
                info!("Loading configuration from: {}", path.display());
                return Self::load_from_file(&path);
            }
        }

        debug!("No configuration file found, using defaults");
        Ok(RunMatConfig::default())
    }

    /// Find potential configuration file paths
    fn find_config_files() -> Vec<PathBuf> {
        let mut paths = Vec::new();

        // 1. Environment variable override
        if let Ok(config_path) = env::var("RUSTMAT_CONFIG") {
            paths.push(PathBuf::from(config_path));
        }

        // 2. Current directory
        let current_dir_configs = [
            ".runmat", // preferred single-file format
            ".runmat.yaml",
            ".runmat.yml",
            ".runmat.json",
            ".runmat.toml",
            "runmat.config.yaml",
            "runmat.config.yml",
            "runmat.config.json",
            "runmat.config.toml",
        ];

        for name in &current_dir_configs {
            if let Ok(current_dir) = env::current_dir() {
                paths.push(current_dir.join(name));
            }
        }

        // 3. Home directory
        if let Some(home_dir) = dirs::home_dir() {
            paths.push(home_dir.join(".runmat"));
            paths.push(home_dir.join(".runmat.yaml"));
            paths.push(home_dir.join(".runmat.yml"));
            paths.push(home_dir.join(".runmat.json"));
            paths.push(home_dir.join(".config/runmat/config.yaml"));
            paths.push(home_dir.join(".config/runmat/config.yml"));
            paths.push(home_dir.join(".config/runmat/config.json"));
        }

        // 4. System-wide configurations
        #[cfg(unix)]
        {
            paths.push(PathBuf::from("/etc/runmat/config.yaml"));
            paths.push(PathBuf::from("/etc/runmat/config.yml"));
            paths.push(PathBuf::from("/etc/runmat/config.json"));
        }

        paths
    }

    /// Load configuration from a specific file
    pub fn load_from_file(path: &Path) -> Result<RunMatConfig> {
        let content = fs::read_to_string(path)
            .with_context(|| format!("Failed to read config file: {}", path.display()))?;

        let config = match path.extension().and_then(|ext| ext.to_str()) {
            // `.runmat` is a TOML alias by default (single canonical format)
            None if path.file_name().and_then(|n| n.to_str()) == Some(".runmat") => {
                toml::from_str(&content).with_context(|| {
                    format!("Failed to parse .runmat (TOML) config: {}", path.display())
                })?
            }
            Some("runmat") => toml::from_str(&content).with_context(|| {
                format!("Failed to parse .runmat (TOML) config: {}", path.display())
            })?,
            Some("yaml") | Some("yml") => serde_yaml::from_str(&content)
                .with_context(|| format!("Failed to parse YAML config: {}", path.display()))?,
            Some("json") => serde_json::from_str(&content)
                .with_context(|| format!("Failed to parse JSON config: {}", path.display()))?,
            Some("toml") => toml::from_str(&content)
                .with_context(|| format!("Failed to parse TOML config: {}", path.display()))?,
            _ => {
                // Try auto-detect (prefer TOML for unknown/no extension)
                if let Ok(config) = toml::from_str(&content) {
                    config
                } else if let Ok(config) = serde_yaml::from_str(&content) {
                    config
                } else if let Ok(config) = serde_json::from_str(&content) {
                    config
                } else {
                    return Err(anyhow::anyhow!(
                        "Could not parse config file {} (tried TOML, YAML, JSON)",
                        path.display()
                    ));
                }
            }
        };

        Ok(config)
    }

    /// Apply environment variable overrides
    fn apply_environment_variables(config: &mut RunMatConfig) -> Result<()> {
        // Runtime settings
        if let Ok(timeout) = env::var("RUSTMAT_TIMEOUT") {
            if let Ok(timeout) = timeout.parse() {
                config.runtime.timeout = timeout;
            }
        }

        if let Ok(verbose) = env::var("RUSTMAT_VERBOSE") {
            config.runtime.verbose = parse_bool(&verbose).unwrap_or(false);
        }

        if let Ok(snapshot) = env::var("RUSTMAT_SNAPSHOT_PATH") {
            config.runtime.snapshot_path = Some(PathBuf::from(snapshot));
        }

        // JIT settings
        if let Ok(jit_enabled) = env::var("RUSTMAT_JIT_ENABLE") {
            config.jit.enabled = parse_bool(&jit_enabled).unwrap_or(true);
        }

        if let Ok(jit_disabled) = env::var("RUSTMAT_JIT_DISABLE") {
            if parse_bool(&jit_disabled).unwrap_or(false) {
                config.jit.enabled = false;
            }
        }

        if let Ok(threshold) = env::var("RUSTMAT_JIT_THRESHOLD") {
            if let Ok(threshold) = threshold.parse() {
                config.jit.threshold = threshold;
            }
        }

        if let Ok(opt_level) = env::var("RUSTMAT_JIT_OPT_LEVEL") {
            config.jit.optimization_level = match opt_level.to_lowercase().as_str() {
                "none" => JitOptLevel::None,
                "size" => JitOptLevel::Size,
                "speed" => JitOptLevel::Speed,
                "aggressive" => JitOptLevel::Aggressive,
                _ => config.jit.optimization_level,
            };
        }

        // GC settings
        if let Ok(preset) = env::var("RUSTMAT_GC_PRESET") {
            config.gc.preset = match preset.to_lowercase().as_str() {
                "low-latency" => Some(GcPreset::LowLatency),
                "high-throughput" => Some(GcPreset::HighThroughput),
                "low-memory" => Some(GcPreset::LowMemory),
                "debug" => Some(GcPreset::Debug),
                _ => config.gc.preset,
            };
        }

        if let Ok(young_size) = env::var("RUSTMAT_GC_YOUNG_SIZE") {
            if let Ok(young_size) = young_size.parse() {
                config.gc.young_size_mb = Some(young_size);
            }
        }

        if let Ok(threads) = env::var("RUSTMAT_GC_THREADS") {
            if let Ok(threads) = threads.parse() {
                config.gc.threads = Some(threads);
            }
        }

        if let Ok(stats) = env::var("RUSTMAT_GC_STATS") {
            config.gc.collect_stats = parse_bool(&stats).unwrap_or(false);
        }

        // Plotting settings
        if let Ok(plot_mode) = env::var("RUSTMAT_PLOT_MODE") {
            config.plotting.mode = match plot_mode.to_lowercase().as_str() {
                "auto" => PlotMode::Auto,
                "gui" => PlotMode::Gui,
                "headless" => PlotMode::Headless,
                "jupyter" => PlotMode::Jupyter,
                _ => config.plotting.mode,
            };
        }

        if let Ok(headless) = env::var("RUSTMAT_PLOT_HEADLESS") {
            config.plotting.force_headless = parse_bool(&headless).unwrap_or(false);
        }

        if let Ok(backend) = env::var("RUSTMAT_PLOT_BACKEND") {
            config.plotting.backend = match backend.to_lowercase().as_str() {
                "auto" => PlotBackend::Auto,
                "wgpu" => PlotBackend::Wgpu,
                "static" => PlotBackend::Static,
                "web" => PlotBackend::Web,
                _ => config.plotting.backend,
            };
        }

        // Logging settings
        if let Ok(debug) = env::var("RUSTMAT_DEBUG") {
            config.logging.debug = parse_bool(&debug).unwrap_or(false);
        }

        if let Ok(log_level) = env::var("RUSTMAT_LOG_LEVEL") {
            config.logging.level = match log_level.to_lowercase().as_str() {
                "error" => LogLevel::Error,
                "warn" => LogLevel::Warn,
                "info" => LogLevel::Info,
                "debug" => LogLevel::Debug,
                "trace" => LogLevel::Trace,
                _ => config.logging.level,
            };
        }

        // Kernel settings
        if let Ok(ip) = env::var("RUSTMAT_KERNEL_IP") {
            config.kernel.ip = ip;
        }

        if let Ok(key) = env::var("RUSTMAT_KERNEL_KEY") {
            config.kernel.key = Some(key);
        }

        Ok(())
    }

    /// Save configuration to a file
    pub fn save_to_file(config: &RunMatConfig, path: &Path) -> Result<()> {
        let content = match path.extension().and_then(|ext| ext.to_str()) {
            Some("yaml") | Some("yml") => {
                serde_yaml::to_string(config).context("Failed to serialize config to YAML")?
            }
            Some("json") => serde_json::to_string_pretty(config)
                .context("Failed to serialize config to JSON")?,
            Some("toml") => {
                toml::to_string_pretty(config).context("Failed to serialize config to TOML")?
            }
            _ => {
                // Default to YAML
                serde_yaml::to_string(config).context("Failed to serialize config to YAML")?
            }
        };

        fs::write(path, content)
            .with_context(|| format!("Failed to write config file: {}", path.display()))?;

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

    /// Generate a sample configuration file
    pub fn generate_sample_config() -> String {
        let config = RunMatConfig::default();
        serde_yaml::to_string(&config).unwrap_or_else(|_| "# Failed to generate config".to_string())
    }
}

/// Parse a boolean value from string with various formats
fn parse_bool(s: &str) -> Option<bool> {
    match s.to_lowercase().as_str() {
        "1" | "true" | "yes" | "on" | "enable" | "enabled" => Some(true),
        "0" | "false" | "no" | "off" | "disable" | "disabled" => Some(false),
        "" => Some(false),
        _ => None,
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use tempfile::TempDir;

    #[test]
    fn test_config_defaults() {
        let config = RunMatConfig::default();
        assert_eq!(config.runtime.timeout, 300);
        assert!(config.jit.enabled);
        assert_eq!(config.jit.threshold, 10);
        assert_eq!(config.plotting.mode, PlotMode::Auto);
    }

    #[test]
    fn test_yaml_serialization() {
        let config = RunMatConfig::default();
        let yaml = serde_yaml::to_string(&config).unwrap();
        let parsed: RunMatConfig = serde_yaml::from_str(&yaml).unwrap();

        assert_eq!(parsed.runtime.timeout, config.runtime.timeout);
        assert_eq!(parsed.jit.enabled, config.jit.enabled);
    }

    #[test]
    fn test_json_serialization() {
        let config = RunMatConfig::default();
        let json = serde_json::to_string_pretty(&config).unwrap();
        let parsed: RunMatConfig = serde_json::from_str(&json).unwrap();

        assert_eq!(parsed.runtime.timeout, config.runtime.timeout);
        assert_eq!(parsed.plotting.mode, config.plotting.mode);
    }

    #[test]
    fn test_file_loading() {
        let temp_dir = TempDir::new().unwrap();
        let config_path = temp_dir.path().join(".runmat.yaml");

        let mut config = RunMatConfig::default();
        config.runtime.timeout = 600;
        config.jit.threshold = 20;

        ConfigLoader::save_to_file(&config, &config_path).unwrap();
        let loaded = ConfigLoader::load_from_file(&config_path).unwrap();

        assert_eq!(loaded.runtime.timeout, 600);
        assert_eq!(loaded.jit.threshold, 20);
    }

    #[test]
    fn test_bool_parsing() {
        assert_eq!(parse_bool("true"), Some(true));
        assert_eq!(parse_bool("1"), Some(true));
        assert_eq!(parse_bool("yes"), Some(true));
        assert_eq!(parse_bool("false"), Some(false));
        assert_eq!(parse_bool("0"), Some(false));
        assert_eq!(parse_bool("invalid"), None);
    }
}