runmat-config 0.3.2

Shared configuration schema and loaders for RunMat
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
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
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
//! 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};

const MIN_QUEUE_SIZE: usize = 8;
const CONFIG_FILENAMES: &[&str] = &[
    ".runmat",
    ".runmat.toml",
    ".runmat.yaml",
    ".runmat.yml",
    ".runmat.json",
    "runmat.config.toml",
    "runmat.config.yaml",
    "runmat.config.yml",
    "runmat.config.json",
];

/// Main RunMat configuration
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct RunMatConfig {
    /// Runtime configuration
    pub runtime: RuntimeConfig,
    /// Acceleration configuration
    #[serde(default)]
    pub accelerate: AccelerateConfig,
    /// Language compatibility configuration
    #[serde(default)]
    pub language: LanguageConfig,
    /// Telemetry configuration
    #[serde(default)]
    pub telemetry: TelemetryConfig,
    /// 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,
    /// Maximum number of call stack frames to record
    #[serde(default = "default_callstack_limit")]
    pub callstack_limit: usize,
    /// Namespace prefix for runtime/semantic error identifiers
    #[serde(default = "default_error_namespace")]
    pub error_namespace: String,
    /// Enable verbose output
    #[serde(default)]
    pub verbose: bool,
    /// Snapshot file to preload
    pub snapshot_path: Option<PathBuf>,
}

#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct LanguageConfig {
    /// Compatibility mode for MATLAB command syntax and legacy behaviors.
    /// Default: "runmat" (RunMat identifiers with MATLAB-compatible command syntax).
    /// "strict" disables command syntax; require `hold(\"on\")` style.
    #[serde(default)]
    pub compat: LanguageCompatMode,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, ValueEnum)]
#[serde(rename_all = "kebab-case")]
pub enum LanguageCompatMode {
    #[serde(rename = "runmat", alias = "run-mat")]
    #[value(name = "runmat")]
    RunMat,
    Matlab,
    Strict,
}

impl Default for LanguageCompatMode {
    fn default() -> Self {
        Self::RunMat
    }
}

pub fn error_namespace_for_language_compat(mode: LanguageCompatMode) -> &'static str {
    match mode {
        LanguageCompatMode::Matlab => "MATLAB",
        LanguageCompatMode::RunMat | LanguageCompatMode::Strict => "RunMat",
    }
}

/// Acceleration (GPU) configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AccelerateConfig {
    /// Enable acceleration subsystem
    #[serde(default = "default_true")]
    pub enabled: bool,
    /// Preferred provider (auto, wgpu, inprocess)
    #[serde(default)]
    pub provider: AccelerateProviderPreference,
    /// Allow automatic fallback to the in-process provider when hardware backend fails
    #[serde(default = "default_true")]
    pub allow_inprocess_fallback: bool,
    /// Preferred WGPU power profile
    #[serde(default)]
    pub wgpu_power_preference: AccelPowerPreference,
    /// Force use of WGPU fallback adapter even if a high-performance adapter exists
    #[serde(default)]
    pub wgpu_force_fallback_adapter: bool,
    /// Auto-offload planner configuration
    #[serde(default)]
    pub auto_offload: AutoOffloadConfig,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, ValueEnum)]
#[serde(rename_all = "kebab-case")]
pub enum AccelerateProviderPreference {
    Auto,
    Wgpu,
    InProcess,
}

impl Default for AccelerateProviderPreference {
    fn default() -> Self {
        Self::Wgpu
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, ValueEnum)]
#[serde(rename_all = "kebab-case")]
pub enum AccelPowerPreference {
    Auto,
    HighPerformance,
    LowPower,
}

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

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, ValueEnum, Default)]
#[serde(rename_all = "kebab-case")]
pub enum AutoOffloadLogLevel {
    Off,
    Info,
    #[default]
    Trace,
}

/// Telemetry configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TelemetryConfig {
    /// Enable runtime telemetry
    #[serde(default = "default_true")]
    pub enabled: bool,
    /// Echo each payload to stdout for transparency
    #[serde(default)]
    pub show_payloads: bool,
    /// Optional HTTP endpoint override
    pub http_endpoint: Option<String>,
    /// Optional UDP endpoint override (host:port)
    pub udp_endpoint: Option<String>,
    /// Bounded queue size for async delivery
    #[serde(default = "default_telemetry_queue")]
    pub queue_size: usize,
    /// Require ingestion key (self-built binaries default to false)
    #[serde(default = "default_true")]
    pub require_ingestion_key: bool,
}

impl Default for TelemetryConfig {
    fn default() -> Self {
        Self {
            enabled: true,
            show_payloads: false,
            http_endpoint: None,
            udp_endpoint: Some("udp.telemetry.runmat.com:7846".to_string()),
            queue_size: default_telemetry_queue(),
            require_ingestion_key: true,
        }
    }
}

impl Default for AccelerateConfig {
    fn default() -> Self {
        Self {
            enabled: true,
            provider: AccelerateProviderPreference::Wgpu,
            allow_inprocess_fallback: true,
            wgpu_power_preference: AccelPowerPreference::Auto,
            wgpu_force_fallback_adapter: false,
            auto_offload: AutoOffloadConfig::default(),
        }
    }
}

fn default_telemetry_queue() -> usize {
    256
}

/// Auto-offload planner configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AutoOffloadConfig {
    #[serde(default = "default_true")]
    pub enabled: bool,
    #[serde(default = "default_true")]
    pub calibrate: bool,
    pub profile_path: Option<PathBuf>,
    #[serde(default)]
    pub log_level: AutoOffloadLogLevel,
}

impl Default for AutoOffloadConfig {
    fn default() -> Self {
        Self {
            enabled: true,
            calibrate: true,
            profile_path: None,
            log_level: AutoOffloadLogLevel::Trace,
        }
    }
}

/// 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>,
    /// Target scatter point budget for GPU decimation overrides
    #[serde(default)]
    pub scatter_target_points: Option<u32>,
    /// Surface vertex budget override for LOD selection
    #[serde(default)]
    pub surface_vertex_budget: Option<u64>,
}

/// 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.com)
    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_callstack_limit() -> usize {
    200
}

fn default_error_namespace() -> String {
    "".to_string()
}
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.com".to_string(),
    }]
}

impl Default for RuntimeConfig {
    fn default() -> Self {
        Self {
            timeout: default_timeout(),
            callstack_limit: default_callstack_limit(),
            error_namespace: default_error_namespace(),
            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()),
            scatter_target_points: None,
            surface_vertex_budget: None,
        }
    }
}

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::Warn,
            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.is_dir() {
                info!(
                    "Ignoring config directory path (expected file): {}",
                    path.display()
                );
                continue;
            }
            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 Some(config_path) = env_value("RUNMAT_CONFIG", &[]) {
            paths.push(PathBuf::from(config_path));
        }

        // 2. Current directory
        if let Ok(current_dir) = env::current_dir() {
            for name in CONFIG_FILENAMES {
                paths.push(current_dir.join(name));
            }
        }

        // 3. Home directory
        if let Some(home_dir) = dirs::home_dir() {
            for name in CONFIG_FILENAMES {
                paths.push(home_dir.join(name));
            }
            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
    }

    /// Walk up from the provided directory looking for the first config file.
    pub fn discover_config_path_from(start: &Path) -> Option<PathBuf> {
        let mut current = if start.is_dir() {
            start.to_path_buf()
        } else {
            start.parent().map(Path::to_path_buf)?
        };
        loop {
            for name in CONFIG_FILENAMES {
                let candidate = current.join(name);
                if candidate.is_file() {
                    return Some(candidate);
                }
            }
            if !current.pop() {
                break;
            }
        }
        None
    }

    /// 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 Some(timeout) = env_value("RUNMAT_TIMEOUT", &[]) {
            if let Ok(timeout) = timeout.parse() {
                config.runtime.timeout = timeout;
            }
        }

        if let Some(limit) = env_value("RUNMAT_CALLSTACK_LIMIT", &[]) {
            if let Ok(limit) = limit.parse() {
                config.runtime.callstack_limit = limit;
            }
        }

        if let Some(namespace) = env_value("RUNMAT_ERROR_NAMESPACE", &[]) {
            let trimmed = namespace.trim();
            if !trimmed.is_empty() {
                config.runtime.error_namespace = trimmed.to_string();
            }
        }

        if let Some(verbose) = env_bool("RUNMAT_VERBOSE", &[]) {
            config.runtime.verbose = verbose;
        }

        if let Some(snapshot) = env_value("RUNMAT_SNAPSHOT_PATH", &[]) {
            config.runtime.snapshot_path = Some(PathBuf::from(snapshot));
        }

        // Telemetry settings
        if let Some(flag) = env_bool("RUNMAT_TELEMETRY", &[]) {
            config.telemetry.enabled = flag;
        }
        if let Some(flag) = env_bool("RUNMAT_NO_TELEMETRY", &[]) {
            if flag {
                config.telemetry.enabled = false;
            }
        }
        if let Some(show) = env_bool("RUNMAT_TELEMETRY_SHOW", &[]) {
            config.telemetry.show_payloads = show;
        }
        if let Some(endpoint) = env_value(
            "RUNMAT_TELEMETRY_ENDPOINT",
            &["RUNMAT_TELEMETRY_HTTP_ENDPOINT"],
        ) {
            let trimmed = endpoint.trim();
            if trimmed.is_empty() {
                config.telemetry.http_endpoint = None;
            } else {
                config.telemetry.http_endpoint = Some(trimmed.to_string());
            }
        }
        if let Some(udp) = env_value("RUNMAT_TELEMETRY_UDP_ENDPOINT", &[]) {
            let trimmed = udp.trim();
            if trimmed.is_empty() || trimmed == "0" || trimmed.eq_ignore_ascii_case("off") {
                config.telemetry.udp_endpoint = None;
            } else {
                config.telemetry.udp_endpoint = Some(trimmed.to_string());
            }
        }
        if let Some(queue) = env_value("RUNMAT_TELEMETRY_QUEUE_SIZE", &[]) {
            if let Ok(parsed) = queue.parse::<usize>() {
                config.telemetry.queue_size = parsed.max(MIN_QUEUE_SIZE);
            }
        }

        // Acceleration settings
        if let Some(accel) = env_value("RUNMAT_ACCEL_ENABLE", &[]) {
            if let Some(flag) = parse_bool(&accel) {
                config.accelerate.enabled = flag;
            }
        }

        if let Some(provider) = env_value("RUNMAT_ACCEL_PROVIDER", &[]) {
            if let Some(pref) = parse_provider_preference(&provider) {
                config.accelerate.provider = pref;
            }
        }

        if let Some(force_inprocess) = env_bool("RUNMAT_ACCEL_FORCE_INPROCESS", &[]) {
            if force_inprocess {
                config.accelerate.provider = AccelerateProviderPreference::InProcess;
            }
        }

        if let Some(wgpu_toggle) = env_bool("RUNMAT_ACCEL_WGPU", &[]) {
            config.accelerate.provider = if wgpu_toggle {
                AccelerateProviderPreference::Wgpu
            } else {
                AccelerateProviderPreference::InProcess
            };
        }

        if let Some(fallback) = env_bool("RUNMAT_ACCEL_DISABLE_FALLBACK", &[]) {
            config.accelerate.allow_inprocess_fallback = !fallback;
        }

        if let Some(force_fallback) = env_bool("RUNMAT_ACCEL_WGPU_FORCE_FALLBACK", &[]) {
            config.accelerate.wgpu_force_fallback_adapter = force_fallback;
        }

        if let Some(power) = env_value("RUNMAT_ACCEL_WGPU_POWER", &[]) {
            if let Some(pref) = parse_power_preference(&power) {
                config.accelerate.wgpu_power_preference = pref;
            }
        }

        if let Some(auto_enabled) = env_bool("RUNMAT_ACCEL_AUTO_OFFLOAD", &[]) {
            config.accelerate.auto_offload.enabled = auto_enabled;
        }

        if let Some(auto_calibrate) = env_bool("RUNMAT_ACCEL_CALIBRATE", &[]) {
            config.accelerate.auto_offload.calibrate = auto_calibrate;
        }

        if let Some(profile_path) = env_value("RUNMAT_ACCEL_PROFILE", &[]) {
            config.accelerate.auto_offload.profile_path = Some(PathBuf::from(profile_path));
        }

        if let Some(auto_log) = env_value("RUNMAT_ACCEL_AUTO_LOG", &[]) {
            if let Some(level) = parse_auto_offload_log_level(&auto_log) {
                config.accelerate.auto_offload.log_level = level;
            }
        }

        // JIT settings
        if let Some(jit_enabled) = env_bool("RUNMAT_JIT_ENABLE", &[]) {
            config.jit.enabled = jit_enabled;
        }

        if let Some(jit_disabled) = env_bool("RUNMAT_JIT_DISABLE", &[]) {
            if jit_disabled {
                config.jit.enabled = false;
            }
        }

        if let Some(threshold) = env_value("RUNMAT_JIT_THRESHOLD", &[]) {
            if let Ok(threshold) = threshold.parse() {
                config.jit.threshold = threshold;
            }
        }

        if let Some(opt_level) = env_value("RUNMAT_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 Some(preset) = env_value("RUNMAT_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 Some(young_size) = env_value("RUNMAT_GC_YOUNG_SIZE", &[]) {
            if let Ok(young_size) = young_size.parse() {
                config.gc.young_size_mb = Some(young_size);
            }
        }

        if let Some(threads) = env_value("RUNMAT_GC_THREADS", &[]) {
            if let Ok(threads) = threads.parse() {
                config.gc.threads = Some(threads);
            }
        }

        if let Some(stats) = env_bool("RUNMAT_GC_STATS", &[]) {
            config.gc.collect_stats = stats;
        }

        // Plotting settings
        if let Some(plot_mode) = env_value("RUNMAT_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 Some(headless) = env_bool("RUNMAT_PLOT_HEADLESS", &[]) {
            config.plotting.force_headless = headless;
        }

        if let Some(backend) = env_value("RUNMAT_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 Some(debug) = env_bool("RUNMAT_DEBUG", &[]) {
            config.logging.debug = debug;
        }

        if let Some(log_level) = env_value("RUNMAT_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 Some(ip) = env_value("RUNMAT_KERNEL_IP", &[]) {
            config.kernel.ip = ip;
        }

        if let Some(key) = env_value("RUNMAT_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,
    }
}

fn parse_auto_offload_log_level(value: &str) -> Option<AutoOffloadLogLevel> {
    match value.trim().to_ascii_lowercase().as_str() {
        "off" => Some(AutoOffloadLogLevel::Off),
        "info" => Some(AutoOffloadLogLevel::Info),
        "trace" => Some(AutoOffloadLogLevel::Trace),
        _ => None,
    }
}

fn parse_provider_preference(value: &str) -> Option<AccelerateProviderPreference> {
    match value.trim().to_ascii_lowercase().as_str() {
        "auto" => Some(AccelerateProviderPreference::Auto),
        "wgpu" => Some(AccelerateProviderPreference::Wgpu),
        "inprocess" | "cpu" | "host" => Some(AccelerateProviderPreference::InProcess),
        _ => None,
    }
}

fn parse_power_preference(value: &str) -> Option<AccelPowerPreference> {
    match value.trim().to_ascii_lowercase().as_str() {
        "auto" => Some(AccelPowerPreference::Auto),
        "high" | "highperformance" | "performance" => Some(AccelPowerPreference::HighPerformance),
        "low" | "lowpower" | "battery" => Some(AccelPowerPreference::LowPower),
        _ => None,
    }
}

fn env_value(primary: &str, aliases: &[&str]) -> Option<String> {
    env::var(primary)
        .ok()
        .or_else(|| aliases.iter().find_map(|alias| env::var(alias).ok()))
}

fn env_bool(primary: &str, aliases: &[&str]) -> Option<bool> {
    env_value(primary, aliases).and_then(|value| parse_bool(&value))
}

#[cfg(feature = "accelerate")]
mod accelerate_bridge {
    use super::{
        AccelPowerPreference, AccelerateConfig, AccelerateProviderPreference, AutoOffloadConfig,
        AutoOffloadLogLevel,
    };
    use runmat_accelerate::{
        AccelPowerPreference as RuntimePowerPreference, AccelerateInitOptions,
        AccelerateProviderPreference as RuntimeProviderPreference,
        AutoOffloadLogLevel as RuntimeAutoLogLevel, AutoOffloadOptions,
    };

    impl From<AccelPowerPreference> for RuntimePowerPreference {
        fn from(pref: AccelPowerPreference) -> Self {
            match pref {
                AccelPowerPreference::Auto => RuntimePowerPreference::Auto,
                AccelPowerPreference::HighPerformance => RuntimePowerPreference::HighPerformance,
                AccelPowerPreference::LowPower => RuntimePowerPreference::LowPower,
            }
        }
    }

    impl From<AccelerateProviderPreference> for RuntimeProviderPreference {
        fn from(pref: AccelerateProviderPreference) -> Self {
            match pref {
                AccelerateProviderPreference::Auto => RuntimeProviderPreference::Auto,
                AccelerateProviderPreference::Wgpu => RuntimeProviderPreference::Wgpu,
                AccelerateProviderPreference::InProcess => RuntimeProviderPreference::InProcess,
            }
        }
    }

    impl From<AutoOffloadLogLevel> for RuntimeAutoLogLevel {
        fn from(level: AutoOffloadLogLevel) -> Self {
            match level {
                AutoOffloadLogLevel::Off => RuntimeAutoLogLevel::Off,
                AutoOffloadLogLevel::Info => RuntimeAutoLogLevel::Info,
                AutoOffloadLogLevel::Trace => RuntimeAutoLogLevel::Trace,
            }
        }
    }

    impl From<&AutoOffloadConfig> for AutoOffloadOptions {
        fn from(cfg: &AutoOffloadConfig) -> Self {
            AutoOffloadOptions {
                enabled: cfg.enabled,
                calibrate: cfg.calibrate,
                profile_path: cfg.profile_path.clone(),
                log_level: cfg.log_level.into(),
            }
        }
    }

    impl From<&AccelerateConfig> for AccelerateInitOptions {
        fn from(cfg: &AccelerateConfig) -> Self {
            AccelerateInitOptions {
                enabled: cfg.enabled,
                provider: cfg.provider.into(),
                allow_inprocess_fallback: cfg.allow_inprocess_fallback,
                wgpu_power_preference: cfg.wgpu_power_preference.into(),
                wgpu_force_fallback_adapter: cfg.wgpu_force_fallback_adapter,
                auto_offload: AutoOffloadOptions::from(&cfg.auto_offload),
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use once_cell::sync::Lazy;
    use std::sync::Mutex;
    use tempfile::TempDir;

    static ENV_GUARD: Lazy<Mutex<()>> = Lazy::new(|| Mutex::new(()));

    #[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);
        assert!(matches!(config.language.compat, LanguageCompatMode::RunMat));
        assert_eq!(config.runtime.error_namespace, "");
    }

    #[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);
        assert_eq!(parsed.accelerate.provider, config.accelerate.provider);
    }

    #[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);
        assert_eq!(parsed.accelerate.enabled, config.accelerate.enabled);
    }

    #[test]
    fn test_parse_auto_offload_log_level_cases() {
        assert_eq!(
            parse_auto_offload_log_level("off"),
            Some(AutoOffloadLogLevel::Off)
        );
        assert_eq!(
            parse_auto_offload_log_level("INFO"),
            Some(AutoOffloadLogLevel::Info)
        );
        assert_eq!(
            parse_auto_offload_log_level("trace"),
            Some(AutoOffloadLogLevel::Trace)
        );
        assert_eq!(parse_auto_offload_log_level("unknown"), None);
    }

    #[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);
    }

    #[test]
    fn telemetry_env_overrides_respect_empty_values() {
        let _lock = ENV_GUARD.lock().unwrap();
        std::env::set_var("RUNMAT_TELEMETRY_ENDPOINT", "https://custom.example/ingest");
        std::env::set_var("RUNMAT_TELEMETRY_UDP_ENDPOINT", "off");
        let mut config = RunMatConfig::default();
        ConfigLoader::apply_environment_variables(&mut config).unwrap();
        assert_eq!(
            config.telemetry.http_endpoint.as_deref(),
            Some("https://custom.example/ingest")
        );
        assert!(config.telemetry.udp_endpoint.is_none());
        std::env::remove_var("RUNMAT_TELEMETRY_ENDPOINT");
        std::env::remove_var("RUNMAT_TELEMETRY_UDP_ENDPOINT");
    }
}