trail-config 0.3.1

Simple library to help with reading (and formatting) values from config files
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
use std::{collections::HashMap, error::Error, fmt, fs, io};
use serde_yaml_bw::{Value, from_str};
use strfmt::strfmt;

/// Custom error type for Trail Config operations
#[derive(Debug)]
pub enum ConfigError {
    /// File I/O error (file not found, permission denied, etc.)
    IoError(io::Error),
    /// YAML parsing error
    YamlError(String),
    /// Path not found in configuration
    PathNotFound(String),
    /// String formatting error
    FormatError(String),
}

impl fmt::Display for ConfigError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            ConfigError::IoError(e) => write!(f, "IO error: {}", e),
            ConfigError::YamlError(msg) => write!(f, "YAML parse error: {}", msg),
            ConfigError::PathNotFound(path) => write!(f, "Path not found in config: {}", path),
            ConfigError::FormatError(msg) => write!(f, "Format error: {}", msg),
        }
    }
}

impl Error for ConfigError {}

impl From<io::Error> for ConfigError {
    fn from(err: io::Error) -> Self {
        ConfigError::IoError(err)
    }
}

#[derive(Debug, Clone)]
pub struct Config {
    content: Value,
    filename: String,
    separator: String,
    environment: Option<String>
}

impl Default for Config {
    /// Creates a Config, attempting to load from `config.yaml` if it exists.
    ///
    /// If `config.yaml` is found and valid, it will be loaded. If the file doesn't exist
    /// or fails to parse, this returns an empty config without panicking.
    ///
    /// # Example
    /// ```
    /// # use trail_config::Config;
    /// let config = Config::default(); // Loads config.yaml if it exists, or returns empty config
    /// // Always succeeds - never panics
    /// ```
    fn default() -> Self {
        Self::new("config.yaml", "/", None)
            .unwrap_or_else(|_| Config {
                content: Value::Null(None),
                filename: String::new(),
                separator: "/".to_string(),
                environment: None
            })
    }
}

impl Config {
    /// Creates a new Config from a YAML file.
    ///
    /// # Arguments
    /// * `filename` - Path to the config file (can contain `{env}` placeholder)
    /// * `sep` - Path separator for accessing nested values
    /// * `env` - Optional environment name to substitute in filename
    ///
    /// # Returns
    /// Returns `Ok(Config)` on success, or `Err(ConfigError)` on failure
    ///
    /// # Errors
    /// Returns `ConfigError::IoError` if the file cannot be read
    /// Returns `ConfigError::YamlError` if the YAML cannot be parsed
    pub fn new(filename: &str, sep: &str, env: Option<&str>) -> Result<Config, ConfigError> {
        // Validate separator
        if sep.is_empty() {
            return Err(ConfigError::FormatError("Separator cannot be empty".to_string()));
        }

        let (file, env) = Self::get_file(filename, env)?;

        match Self::load(&file) {
            Ok(yaml) => Ok(Config {
                content: yaml,
                filename: file,
                separator: sep.to_string(),
                environment: env
            }),
            Err(e) => Err(e)
        }
    }

    /// Creates a new Config from a required YAML file.
    ///
    /// This method is intended for production environments where a missing configuration
    /// file is a critical error. Unlike `default()` which gracefully falls back to an
    /// empty config, this method will return an error if the file is missing or invalid.
    ///
    /// # Arguments
    /// * `filename` - Path to the config file (can contain `{env}` placeholder)
    /// * `sep` - Path separator for accessing nested values
    /// * `env` - Optional environment name to substitute in filename
    ///
    /// # Returns
    /// Returns `Ok(Config)` if the file is found and valid YAML, or `Err(ConfigError)` otherwise
    ///
    /// # Errors
    /// Returns `ConfigError::IoError` if the file is missing or cannot be read (permission denied, etc.)
    /// Returns `ConfigError::YamlError` if the YAML cannot be parsed
    /// Returns `ConfigError::FormatError` if the separator is empty or filename template is invalid
    ///
    /// # Example
    /// ```no_run
    /// # use trail_config::Config;
    /// // In production, require config.yaml to exist
    /// let config = Config::load_required("config.yaml", "/", None)
    ///     .expect("Failed to load required config.yaml");
    /// ```
    pub fn load_required(filename: &str, sep: &str, env: Option<&str>) -> Result<Config, ConfigError> {
        if filename.is_empty() {
            return Err(ConfigError::IoError(io::Error::new(
                io::ErrorKind::InvalidInput,
                "load_required: filename cannot be empty",
            )));
        }
        Self::new(filename, sep, env)
    }

    pub fn environment(&self) -> Option<&str> {
        match &self.environment {
            Some(v) => Some(v),
            None => None
        }
    }

    /// Returns the filename of the loaded config file
    pub fn get_filename(&self) -> &str {
        &self.filename
    }

    /// Reloads the configuration from disk
    ///
    /// This allows you to update the config without creating a new Config instance.
    /// Useful for detecting configuration changes at runtime (hot reload).
    ///
    /// # Returns
    /// Returns `Ok(())` on success, or `Err(ConfigError)` if the file cannot be read or is invalid YAML
    ///
    /// # Errors
    /// Returns `ConfigError::IoError` if the file is missing or cannot be read
    /// Returns `ConfigError::YamlError` if the YAML cannot be parsed
    ///
    /// # Note
    /// If reloading fails (e.g. the file contains invalid YAML or has been deleted), the
    /// existing configuration is preserved unchanged. The error is returned but the config
    /// remains valid and usable.
    ///
    /// # Example
    /// ```no_run
    /// # use trail_config::Config;
    /// let mut config = Config::default();
    /// // ... use config ...
    /// // Later, reload updated config from disk
    /// config.reload().expect("Failed to reload config");
    /// ```
    pub fn reload(&mut self) -> Result<(), ConfigError> {
        if self.filename.is_empty() {
            return Err(ConfigError::FormatError("Cannot reload: config was loaded from YAML string, not a file".to_string()));
        }
        
        let yaml = Self::load(&self.filename)?;
        self.content = yaml;
        Ok(())
    }

    /// Reloads the configuration from a different file
    ///
    /// Changes the config's filename and reloads from the new file.
    /// The separator and environment settings remain the same.
    ///
    /// # Arguments
    /// * `filename` - New config file to load
    ///
    /// # Returns
    /// Returns `Ok(())` on success, or `Err(ConfigError)` if the file cannot be read or is invalid YAML
    ///
    /// # Errors
    /// Returns `ConfigError::IoError` if the file is missing or cannot be read
    /// Returns `ConfigError::YamlError` if the YAML cannot be parsed
    ///
    /// # Example
    /// ```no_run
    /// # use trail_config::Config;
    /// let mut config = Config::default();
    /// // Switch to loading from a different config file
    /// config.reload_from("other_config.yaml").expect("Failed to load");
    /// ```
    pub fn reload_from(&mut self, filename: &str) -> Result<(), ConfigError> {
        let yaml = Self::load(filename)?;
        self.filename = filename.to_string();
        self.content = yaml;
        Ok(())
    }

    /// Gets a value at the specified path
    ///
    /// # Arguments
    /// * `path` - Dot-separated path to the value (e.g., "db/redis/port")
    ///
    /// # Returns
    /// Returns `Some(Value)` if found, `None` otherwise
    pub fn get(&self, path: &str) -> Option<Value> {
        self.get_strict(path).ok()
    }

    /// Gets a value as a string at the specified path
    ///
    /// # Arguments
    /// * `path` - Dot-separated path to the value
    ///
    /// # Returns
    /// Returns the string representation of the value, or empty string if not found or not convertible
    pub fn str(&self, path: &str) -> String {
        self.str_strict(path).unwrap_or_else(|_| String::new())
    }

    /// Gets a value as a list of strings at the specified path
    ///
    /// # Arguments
    /// * `path` - Dot-separated path to the sequence value
    ///
    /// # Returns
    /// Returns a `Vec<String>` with the sequence elements, or empty vec if not found or not a sequence
    pub fn list(&self, path: &str) -> Vec<String> {
        self.list_strict(path).unwrap_or_else(|_| vec![])
    }

    /// Checks if a path exists in the configuration
    ///
    /// # Arguments
    /// * `path` - Dot-separated path to check
    ///
    /// # Returns
    /// Returns `true` if the path exists, `false` otherwise
    pub fn contains(&self, path: &str) -> bool {
        Self::get_leaf(&self.content, path, &self.separator).is_some()
    }

    /// Gets a value at the specified path, returning an error if not found
    ///
    /// # Arguments
    /// * `path` - Dot-separated path to the value (e.g., "db/redis/port")
    ///
    /// # Returns
    /// Returns `Ok(Value)` if found, or `Err(ConfigError::PathNotFound)` if not found
    ///
    /// # Example
    /// ```
    /// # use trail_config::Config;
    /// # let yaml = "db:\n  redis:\n    port: 6379";
    /// # let config = Config::load_yaml(yaml, "/").unwrap();
    /// let value = config.get_strict("db/redis/port").unwrap();
    /// ```
    pub fn get_strict(&self, path: &str) -> Result<Value, ConfigError> {
        Self::get_leaf(&self.content, path, &self.separator)
            .ok_or_else(|| ConfigError::PathNotFound(path.to_string()))
    }

    /// Gets a value as a string at the specified path, returning an error if not found
    ///
    /// # Arguments
    /// * `path` - Dot-separated path to the value
    ///
    /// # Returns
    /// Returns `Ok(String)` with the string representation, or `Err(ConfigError::PathNotFound)` if not found
    ///
    /// # Example
    /// ```
    /// # use trail_config::Config;
    /// # let yaml = "app:\n  port: 8080";
    /// # let config = Config::load_yaml(yaml, "/").unwrap();
    /// let port = config.str_strict("app/port").unwrap();
    /// assert_eq!(port, "8080");
    /// ```
    pub fn str_strict(&self, path: &str) -> Result<String, ConfigError> {
        let value = Self::get_leaf(&self.content, path, &self.separator)
            .ok_or_else(|| ConfigError::PathNotFound(path.to_string()))?;
        Ok(Self::to_string(&value))
    }

    /// Gets a value as a list of strings at the specified path, returning an error if not found
    ///
    /// # Arguments
    /// * `path` - Dot-separated path to the sequence value
    ///
    /// # Returns
    /// Returns `Ok(Vec<String>)` if found and is a sequence, or `Err(ConfigError::PathNotFound)` if not found
    ///
    /// # Example
    /// ```
    /// # use trail_config::Config;
    /// # let yaml = "items:\n  - first\n  - second";
    /// # let config = Config::load_yaml(yaml, "/").unwrap();
    /// let list = config.list_strict("items").unwrap();
    /// assert_eq!(list.len(), 2);
    /// ```
    pub fn list_strict(&self, path: &str) -> Result<Vec<String>, ConfigError> {
        let value = Self::get_leaf(&self.content, path, &self.separator)
            .ok_or_else(|| ConfigError::PathNotFound(path.to_string()))?;
        Ok(Self::to_list(&value))
    }

    /// Gets a value as an integer at the specified path
    ///
    /// # Arguments
    /// * `path` - Dot-separated path to the value
    ///
    /// # Returns
    /// Returns `Some(i64)` if the value is a number, `None` otherwise
    ///
    /// # Example
    /// ```
    /// # use trail_config::Config;
    /// # let yaml = "app:\n  port: 8080";
    /// # let config = Config::load_yaml(yaml, "/").unwrap();
    /// let port = config.get_int("app/port");
    /// assert_eq!(port, Some(8080));
    /// ```
    pub fn get_int(&self, path: &str) -> Option<i64> {
        self.get_int_strict(path).ok()
    }

    /// Gets a value as an integer at the specified path, returning an error if not found or not a number
    ///
    /// # Arguments
    /// * `path` - Dot-separated path to the value
    ///
    /// # Returns
    /// Returns `Ok(i64)` if found and is a number, or `Err(ConfigError)` otherwise
    pub fn get_int_strict(&self, path: &str) -> Result<i64, ConfigError> {
        let value = Self::get_leaf(&self.content, path, &self.separator)
            .ok_or_else(|| ConfigError::PathNotFound(path.to_string()))?;
        
        match &value {
            Value::Number(num, _) => {
                num.as_i64()
                    .ok_or_else(|| ConfigError::FormatError(format!("Cannot convert {} to i64", num)))
            },
            _ => Err(ConfigError::FormatError(format!("Value at {} is not a number", path)))
        }
    }

    /// Gets a value as a floating-point number at the specified path
    ///
    /// # Arguments
    /// * `path` - Dot-separated path to the value
    ///
    /// # Returns
    /// Returns `Some(f64)` if the value is a number, `None` otherwise
    ///
    /// # Example
    /// ```
    /// # use trail_config::Config;
    /// # let yaml = "app:\n  timeout: 3.14";
    /// # let config = Config::load_yaml(yaml, "/").unwrap();
    /// let timeout = config.get_float("app/timeout");
    /// assert!(timeout.is_some());
    /// ```
    pub fn get_float(&self, path: &str) -> Option<f64> {
        self.get_float_strict(path).ok()
    }

    /// Gets a value as a floating-point number at the specified path, returning an error if not found or not a number
    ///
    /// # Arguments
    /// * `path` - Dot-separated path to the value
    ///
    /// # Returns
    /// Returns `Ok(f64)` if found and is a number, or `Err(ConfigError)` otherwise
    pub fn get_float_strict(&self, path: &str) -> Result<f64, ConfigError> {
        let value = Self::get_leaf(&self.content, path, &self.separator)
            .ok_or_else(|| ConfigError::PathNotFound(path.to_string()))?;
        
        match &value {
            Value::Number(num, _) => {
                num.as_f64()
                    .ok_or_else(|| ConfigError::FormatError(format!("Cannot convert {} to f64", num)))
            },
            _ => Err(ConfigError::FormatError(format!("Value at {} is not a number", path)))
        }
    }

    /// Gets a value as a boolean at the specified path
    ///
    /// # Arguments
    /// * `path` - Dot-separated path to the value
    ///
    /// # Returns
    /// Returns `Some(bool)` if the value is a boolean, `None` otherwise
    ///
    /// # Example
    /// ```
    /// # use trail_config::Config;
    /// # let yaml = "app:\n  debug: true";
    /// # let config = Config::load_yaml(yaml, "/").unwrap();
    /// let debug = config.get_bool("app/debug");
    /// assert_eq!(debug, Some(true));
    /// ```
    pub fn get_bool(&self, path: &str) -> Option<bool> {
        self.get_bool_strict(path).ok()
    }

    /// Gets a value as a boolean at the specified path, returning an error if not found or not a boolean
    ///
    /// # Arguments
    /// * `path` - Dot-separated path to the value
    ///
    /// # Returns
    /// Returns `Ok(bool)` if found and is a boolean, or `Err(ConfigError)` otherwise
    pub fn get_bool_strict(&self, path: &str) -> Result<bool, ConfigError> {
        let value = Self::get_leaf(&self.content, path, &self.separator)
            .ok_or_else(|| ConfigError::PathNotFound(path.to_string()))?;
        
        match &value {
            Value::Bool(b, _) => Ok(*b),
            _ => Err(ConfigError::FormatError(format!("Value at {} is not a boolean", path)))
        }
    }

    /// Formats a string template with values from the config
    ///
    /// # Arguments
    /// * `format` - Format string with `{}` placeholders
    /// * `path` - Dot-separated path with multiple attributes joined by `+` (e.g., "db/redis/server+port")
    ///
    /// # Returns
    /// Returns the formatted string, or empty string if any referenced value is not found
    /// 
    /// # Example
    /// ```
    /// # use trail_config::Config;
    /// # let yaml = "db:\n  redis:\n    server: 127.0.0.1\n    port: 6379";
    /// # let config = Config::load_yaml(yaml, "/").unwrap();
    /// let result = config.fmt("{}:{}", "db/redis/server+port");
    /// assert_eq!(result, "127.0.0.1:6379");
    /// ```
    pub fn fmt(&self, format: &str, path: &str) -> String {
        self.fmt_strict(format, path).unwrap_or_else(|_| String::new())
    }

    /// Parses a YAML string into a Config object
    ///
    /// # Arguments
    /// * `yaml` - YAML content as a string
    /// * `sep` - Path separator for accessing nested values (cannot be empty)
    ///
    /// # Returns
    /// Returns `Ok(Config)` on success, or `Err(ConfigError)` on failure
    ///
    /// # Errors
    /// Returns `ConfigError::FormatError` if separator is empty
    /// Returns `ConfigError::YamlError` if YAML parsing fails
    pub fn load_yaml(yaml: &str, sep: &str) -> Result<Config, ConfigError> {
        // Validate separator
        if sep.is_empty() {
            return Err(ConfigError::FormatError("Separator cannot be empty".to_string()));
        }

        let parsed = from_str(yaml)
            .map_err(|e| ConfigError::YamlError(e.to_string()))?;

        Ok(Config {
            content: parsed,
            filename: String::new(),
            separator: sep.to_string(),
            environment: None
        })
    }

    /// Formats a string template with values from the config, returning an error if any value is missing
    ///
    /// # Arguments
    /// * `format` - Format string with `{}` placeholders
    /// * `path` - Dot-separated path with multiple attributes joined by `+` (e.g., "db/redis/server+port")
    ///
    /// # Returns
    /// Returns `Ok(String)` with the formatted result, or `Err(ConfigError)` if any value is not found or formatting fails
    ///
    /// # Example
    /// ```
    /// # use trail_config::Config;
    /// # let yaml = "db:\n  redis:\n    server: 127.0.0.1\n    port: 6379";
    /// # let config = Config::load_yaml(yaml, "/").unwrap();
    /// let result = config.fmt_strict("{}:{}", "db/redis/server+port").unwrap();
    /// assert_eq!(result, "127.0.0.1:6379");
    /// ```
    pub fn fmt_strict(&self, format: &str, path: &str) -> Result<String, ConfigError> {
        let mut content = &self.content;
        let mut parts = path.split(&self.separator).collect::<Vec<&str>>();
        let last = parts.pop();
    
        for item in parts.iter() {
            match content.get(item) {
                Some(v) => { content = v; },
                None => return Err(ConfigError::PathNotFound(path.to_string()))
            }
        }

        match last {
            Some(v) => {
                let attributes = v.split('+').collect::<Vec<&str>>();
                let mut fmt = format.to_string();
                let mut vars = HashMap::new();

                for item in attributes.iter() {
                    match content.get(item) {
                        Some(v) => {
                            fmt = fmt.replacen("{}", &format!("{{{}}}", item), 1);
                            vars.insert(item.to_string(), Self::to_string(v));
                        },
                        None => return Err(ConfigError::PathNotFound(path.to_string()))
                    }
                }

                match strfmt(&fmt, &vars) {
                    Ok(r) => Ok(r),
                    Err(e) => Err(ConfigError::FormatError(e.to_string()))
                }
            },
            None => Err(ConfigError::PathNotFound(path.to_string()))
        }
    }

    fn get_leaf(mut content: &Value, path: &str, separator: &str) -> Option<Value> {
        // Validate inputs
        if path.is_empty() {
            return None;
        }
        if separator.is_empty() {
            return None;
        }

        let parts = Self::parse_path(path, separator);
    
        for item in parts.iter() {
            if item.is_empty() {
                // Skip empty parts (e.g., from leading/trailing separators)
                continue;
            }
            match content.get(item) {
                Some(v) => { content = v; },
                None => return None
            }
        }

        Some(content.clone())
    }

    /// Parses a path with escape sequence support.
    /// 
    /// Allows keys containing the separator by escaping them:
    /// - `\/` becomes a literal separator character in the key
    /// - `\\` becomes a literal backslash in the key
    /// 
    /// # Example
    /// With separator `/`, path `database/host\\/port` navigates to:
    /// 1. Key "database"
    /// 2. Key "host/port" (the separator is escaped)
    ///
    /// # Note on multi-character separators
    /// Escape detection is based on the *first character* of the separator only.
    /// For example, with separator `::`, the escape `\:` will be treated as an
    /// escaped separator even if the second `:` is absent. This means separators
    /// that share a first character with another valid separator may behave
    /// unexpectedly in escape sequences.
    fn parse_path(path: &str, separator: &str) -> Vec<String> {
        let mut parts = Vec::new();
        let mut current = String::new();
        let mut chars = path.chars().peekable();
        let sep_first_char = separator.chars().next().unwrap_or('/');

        while let Some(ch) = chars.next() {
            if ch == '\\' {
                if let Some(&next) = chars.peek() {
                    if next == '\\' {
                        // Escaped backslash
                        current.push('\\');
                        chars.next();
                    } else if next == sep_first_char {
                        // Escaped separator
                        current.push(next);
                        chars.next();
                    } else {
                        // Keep backslash as-is
                        current.push(ch);
                    }
                } else {
                    current.push(ch);
                }
            } else if ch == sep_first_char {
                // Check if this is the actual separator (for multi-char separators)
                let remaining: String = chars.clone().collect();
                let expected_rest = &separator[1..];
                if remaining.starts_with(expected_rest) {
                    // This is the real separator
                    parts.push(current.clone());
                    current.clear();
                    // Consume the rest of the separator
                    for _ in 1..separator.len() {
                        chars.next();
                    }
                } else {
                    // Just a matching char, not the full separator
                    current.push(ch);
                }
            } else {
                current.push(ch);
            }
        }

        parts.push(current);
        parts
    }

    fn get_file(filename: &str, env: Option<&str>) -> Result<(String, Option<String>), ConfigError> {
        match env {
            Some(v) => {
                let mut vars = HashMap::new();
                vars.insert(String::from("env"), v);
                let file = strfmt(filename, &vars)
                    .map_err(|e| ConfigError::FormatError(format!("Invalid filename template: {}", e)))?;
                Ok((file, Some(v.to_string())))
            },
            None => Ok((String::from(filename), None))
        }
    }

    fn load(filename: &str) -> Result<Value, ConfigError> {
        let yaml = fs::read_to_string(filename)?;
        let parsed = from_str(&yaml)
            .map_err(|e| ConfigError::YamlError(e.to_string()))?;
        
        Ok(parsed)
    }
    
    fn to_string(value: &Value) -> String {
        match value {
            Value::String(v, _) => v.to_string(),
            Value::Number(v, _) => v.to_string(),
            Value::Bool(v, _) => v.to_string(),
            _ => String::new()
        }
    }

    fn to_list(value: &Value) -> Vec<String> {
        match value {
            Value::Sequence(v) => v.iter().map(Self::to_string).collect::<Vec<String>>(),
            _ => vec![]
        }
    }
}

#[cfg(test)]
mod tests {
    use super::{from_str, Config, Value, ConfigError};
    use serde_yaml_bw::Number;

    const YAML: &str = "
db:
    redis:
        server: 127.0.0.1
        port: 6379
        key_expiry: 3600
    sql:
        driver: SQL Server
        server: 127.0.0.1
        database: my_db
        username: user
        password: Pa$$w0rd!
sources:
    - one
    - two
    - three
app:
    debug: true
    max_retries: 5
    timeout: 2.5
";

    #[test]
    fn get_int_success() {
        let config = Config::load_yaml(YAML, "/").unwrap();
        
        let port = config.get_int("db/redis/port");
        assert_eq!(port, Some(6379));

        let max_retries = config.get_int("app/max_retries");
        assert_eq!(max_retries, Some(5));
    }

    #[test]
    fn get_int_not_found() {
        let config = Config::load_yaml(YAML, "/").unwrap();
        
        let value = config.get_int("db/nonexistent");
        assert_eq!(value, None);
    }

    #[test]
    fn get_int_strict_success() {
        let config = Config::load_yaml(YAML, "/").unwrap();
        
        let result = config.get_int_strict("db/redis/port");
        assert!(result.is_ok());
        assert_eq!(result.unwrap(), 6379);
    }

    #[test]
    fn get_int_strict_not_found() {
        let config = Config::load_yaml(YAML, "/").unwrap();
        
        let result = config.get_int_strict("db/nonexistent");
        assert!(result.is_err());
        match result {
            Err(ConfigError::PathNotFound(_)) => (),
            _ => panic!("Expected PathNotFound"),
        }
    }

    #[test]
    fn get_int_strict_wrong_type() {
        let config = Config::load_yaml(YAML, "/").unwrap();
        
        let result = config.get_int_strict("db/redis/server");
        assert!(result.is_err());
        match result {
            Err(ConfigError::FormatError(_)) => (),
            _ => panic!("Expected FormatError"),
        }
    }

    #[test]
    fn get_float_success() {
        let config = Config::load_yaml(YAML, "/").unwrap();
        
        let timeout = config.get_float("app/timeout");
        assert!(timeout.is_some());
        assert!((timeout.unwrap() - 2.5).abs() < 0.001);
    }

    #[test]
    fn get_float_not_found() {
        let config = Config::load_yaml(YAML, "/").unwrap();
        
        let value = config.get_float("app/missing_timeout");
        assert_eq!(value, None);
    }

    #[test]
    fn get_float_strict_success() {
        let config = Config::load_yaml(YAML, "/").unwrap();
        
        let result = config.get_float_strict("app/timeout");
        assert!(result.is_ok());
        assert!((result.unwrap() - 2.5).abs() < 0.001);
    }

    #[test]
    fn get_float_strict_not_found() {
        let config = Config::load_yaml(YAML, "/").unwrap();
        
        let result = config.get_float_strict("app/missing");
        assert!(result.is_err());
        match result {
            Err(ConfigError::PathNotFound(_)) => (),
            _ => panic!("Expected PathNotFound"),
        }
    }

    #[test]
    fn get_float_strict_wrong_type() {
        let config = Config::load_yaml(YAML, "/").unwrap();
        
        let result = config.get_float_strict("app/debug");
        assert!(result.is_err());
        match result {
            Err(ConfigError::FormatError(_)) => (),
            _ => panic!("Expected FormatError"),
        }
    }

    #[test]
    fn get_bool_success() {
        let config = Config::load_yaml(YAML, "/").unwrap();
        
        let debug = config.get_bool("app/debug");
        assert_eq!(debug, Some(true));
    }

    #[test]
    fn get_bool_not_found() {
        let config = Config::load_yaml(YAML, "/").unwrap();
        
        let value = config.get_bool("app/missing_bool");
        assert_eq!(value, None);
    }

    #[test]
    fn get_bool_strict_success() {
        let config = Config::load_yaml(YAML, "/").unwrap();
        
        let result = config.get_bool_strict("app/debug");
        assert!(result.is_ok());
        assert_eq!(result.unwrap(), true);
    }

    #[test]
    fn get_bool_strict_not_found() {
        let config = Config::load_yaml(YAML, "/").unwrap();
        
        let result = config.get_bool_strict("app/missing");
        assert!(result.is_err());
        match result {
            Err(ConfigError::PathNotFound(_)) => (),
            _ => panic!("Expected PathNotFound"),
        }
    }

    #[test]
    fn get_bool_strict_wrong_type() {
        let config = Config::load_yaml(YAML, "/").unwrap();
        
        let result = config.get_bool_strict("app/max_retries");
        assert!(result.is_err());
        match result {
            Err(ConfigError::FormatError(_)) => (),
            _ => panic!("Expected FormatError"),
        }
    }

    #[test]
    fn fmt_test()  {
        let parsed: Config = Config::load_yaml(YAML, "/").unwrap();
        let formatted = parsed.fmt("{}:{}", "db/sql/database+username");

        assert_eq!(formatted, String::from("my_db:user"));
    }

    #[test]
    fn get_leaf_test()  {
        let parsed: Value = from_str(YAML).unwrap();
        let value1 = Config::get_leaf(&parsed, "db/redis/port", "/");
        let value2 = Config::get_leaf(&parsed, "db/redis/username", "/");
        
        assert_eq!(value1, Some(Value::Number(Number::from(6379), None)));
        assert_eq!(value2, None);
    }

    #[test]
    fn get_file_test() {
        let result = Config::get_file("config_{env}.yaml", Some("dev"));

        assert!(result.is_ok());
        let (file, env) = result.unwrap();
        assert_eq!(env, Some(String::from("dev")));
        assert_eq!(file, "config_dev.yaml");
    }

    #[test]
    fn get_file_invalid_template() {
        let result = Config::get_file("config_{invalid.yaml", Some("dev"));

        assert!(result.is_err());
        match result {
            Err(ConfigError::FormatError(_)) => (),
            _ => panic!("Expected FormatError for invalid template"),
        }
    }

    #[test]
    fn to_string_test() {
        let parsed: Value = from_str(YAML).unwrap();
        let value = Config::get_leaf(&parsed, "db/redis/port", "/").unwrap();
        let str_value = Config::to_string(&value);

        assert_eq!(str_value, "6379");
    }

    #[test]
    fn to_list_test()  {
        let parsed: Value = from_str(YAML).unwrap();
        let value = Config::get_leaf(&parsed, "sources", "/").unwrap();
        let list = Config::to_list(&value);

        let mut vec = Vec::new();        
        vec.push(String::from("one"));
        vec.push(String::from("two"));
        vec.push(String::from("three"));

        assert_eq!(list, vec);
    }

    #[test]
    fn contains_test() {
        let config = Config::load_yaml(YAML, "/").unwrap();
        
        assert!(config.contains("db/redis/port"));
        assert!(config.contains("db/redis/server"));
        assert!(!config.contains("db/redis/nonexistent"));
        assert!(!config.contains("nonexistent/path"));
    }

    #[test]
    fn yaml_parse_error() {
        let invalid_yaml = "invalid: [unclosed";
        let result = Config::load_yaml(invalid_yaml, "/");
        
        assert!(result.is_err());
        match result {
            Err(ConfigError::YamlError(_)) => (),
            _ => panic!("Expected YamlError"),
        }
    }

    #[test]
    fn file_not_found_error() {
        let result = Config::new("nonexistent_file_12345.yaml", "/", None);
        
        assert!(result.is_err());
        match result {
            Err(ConfigError::IoError(_)) => (),
            _ => panic!("Expected IoError for missing file"),
        }
    }

    #[test]
    fn invalid_yaml_formats() {
        let test_cases = vec![
            "invalid: {unclosed",      // unclosed mapping
            "- item1\n - item2\n- item3\n : invalid",  // invalid key colon
            ": invalid_key",           // invalid key starting with colon
        ];

        for invalid_yaml in test_cases {
            let result = Config::load_yaml(invalid_yaml, "/");
            assert!(result.is_err(), "Expected error for: {}", invalid_yaml);
            
            match result {
                Err(ConfigError::YamlError(_)) => (),
                _ => panic!("Expected YamlError for: {}", invalid_yaml),
            }
        }
    }

    #[test]
    fn error_display_messages() {
        // Test IoError display
        let io_err = ConfigError::IoError(std::io::Error::new(
            std::io::ErrorKind::NotFound,
            "test file not found",
        ));
        assert!(io_err.to_string().contains("IO error"));

        // Test YamlError display
        let yaml_err = ConfigError::YamlError("invalid syntax".to_string());
        assert!(yaml_err.to_string().contains("YAML parse error"));

        // Test PathNotFound display
        let path_err = ConfigError::PathNotFound("db/missing/key".to_string());
        assert!(path_err.to_string().contains("Path not found"));

        // Test FormatError display
        let fmt_err = ConfigError::FormatError("invalid format".to_string());
        assert!(fmt_err.to_string().contains("Format error"));
    }

    #[test]
    fn empty_yaml() {
        let empty_yaml = "";
        let result = Config::load_yaml(empty_yaml, "/");
        
        // Empty YAML should parse but result in empty config
        assert!(result.is_ok());
        let config = result.unwrap();
        assert!(!config.contains("any/path"));
    }

    #[test]
    fn get_strict_found() {
        let config = Config::load_yaml(YAML, "/").unwrap();
        let result = config.get_strict("db/redis/port");
        
        assert!(result.is_ok());
    }

    #[test]
    fn get_strict_not_found() {
        let config = Config::load_yaml(YAML, "/").unwrap();
        let result = config.get_strict("db/redis/nonexistent");
        
        assert!(result.is_err());
        match result {
            Err(ConfigError::PathNotFound(path)) => assert_eq!(path, "db/redis/nonexistent"),
            _ => panic!("Expected PathNotFound error"),
        }
    }

    #[test]
    fn str_strict_found() {
        let config = Config::load_yaml(YAML, "/").unwrap();
        let result = config.str_strict("db/redis/port");
        
        assert!(result.is_ok());
        assert_eq!(result.unwrap(), "6379");
    }

    #[test]
    fn str_strict_not_found() {
        let config = Config::load_yaml(YAML, "/").unwrap();
        let result = config.str_strict("app/nonexistent");
        
        assert!(result.is_err());
        match result {
            Err(ConfigError::PathNotFound(_)) => (),
            _ => panic!("Expected PathNotFound error"),
        }
    }

    #[test]
    fn list_strict_found() {
        let config = Config::load_yaml(YAML, "/").unwrap();
        let result = config.list_strict("sources");
        
        assert!(result.is_ok());
        let list = result.unwrap();
        assert_eq!(list.len(), 3);
        assert_eq!(list[0], "one");
    }

    #[test]
    fn list_strict_not_found() {
        let config = Config::load_yaml(YAML, "/").unwrap();
        let result = config.list_strict("nonexistent/list");
        
        assert!(result.is_err());
        match result {
            Err(ConfigError::PathNotFound(_)) => (),
            _ => panic!("Expected PathNotFound error"),
        }
    }

    #[test]
    fn fmt_strict_success() {
        let config = Config::load_yaml(YAML, "/").unwrap();
        let result = config.fmt_strict("{}:{}", "db/redis/server+port");
        
        assert!(result.is_ok());
        assert_eq!(result.unwrap(), "127.0.0.1:6379");
    }

    #[test]
    fn fmt_strict_missing_path() {
        let config = Config::load_yaml(YAML, "/").unwrap();
        let result = config.fmt_strict("{}:{}", "db/redis/nonexistent+port");
        
        assert!(result.is_err());
        match result {
            Err(ConfigError::PathNotFound(_)) => (),
            _ => panic!("Expected PathNotFound error"),
        }
    }

    #[test]
    fn fmt_strict_missing_attribute() {
        let config = Config::load_yaml(YAML, "/").unwrap();
        let result = config.fmt_strict("{}:{}", "db/redis/server+nonexistent");
        
        assert!(result.is_err());
        match result {
            Err(ConfigError::PathNotFound(_)) => (),
            _ => panic!("Expected PathNotFound error"),
        }
    }

    #[test]
    fn empty_separator_in_new() {
        let result = Config::new("config.yaml", "", None);
        
        assert!(result.is_err());
        match result {
            Err(ConfigError::FormatError(msg)) => assert!(msg.contains("empty")),
            _ => panic!("Expected FormatError for empty separator"),
        }
    }

    #[test]
    fn empty_separator_in_load_yaml() {
        let result = Config::load_yaml(YAML, "");
        
        assert!(result.is_err());
        match result {
            Err(ConfigError::FormatError(msg)) => assert!(msg.contains("empty")),
            _ => panic!("Expected FormatError for empty separator"),
        }
    }

    #[test]
    fn empty_path() {
        let config = Config::load_yaml(YAML, "/").unwrap();
        
        let result = config.get("");
        assert!(result.is_none());

        let result = config.str("");
        assert_eq!(result, "");

        let result = config.list("");
        assert_eq!(result.len(), 0);
    }

    #[test]
    fn path_with_only_separator() {
        let config = Config::load_yaml(YAML, "/").unwrap();
        
        // "/" is the root path - should return the root content
        let result = config.get("/");
        assert!(result.is_some());

        // "//" results in empty strings which are skipped, also returns root
        let result = config.get("//");
        assert!(result.is_some());
    }

    #[test]
    fn path_with_leading_trailing_separator() {
        let config = Config::load_yaml(YAML, "/").unwrap();
        
        // "/db/redis/port/" should skip empty parts and find "port"
        let result = config.get("/db/redis/port/");
        assert!(result.is_some());
    }

    #[test]
    fn load_required_file_not_found() {
        let result = Config::load_required("nonexistent_file_xyz.yaml", "/", None);
        
        assert!(result.is_err());
        match result {
            Err(ConfigError::IoError(_)) => (),
            _ => panic!("Expected IoError for missing file"),
        }
    }

    #[test]
    fn load_required_with_env() {
        // This will fail because config_dev.yaml doesn't exist, 
        // but it tests that the method attempts to load with env substitution
        let result = Config::load_required("config_{env}.yaml", "/", Some("dev"));
        
        assert!(result.is_err());
        match result {
            Err(ConfigError::IoError(_)) => (),
            _ => panic!("Expected IoError for missing file"),
        }
    }

    #[test]
    fn load_required_rejects_empty_filename() {
        // load_required enforces a non-empty filename, unlike Config::new
        let config = Config::load_required("", "/", None);
        
        // Empty filename is rejected with IoError
        assert!(config.is_err());
        match config {
            Err(ConfigError::IoError(_)) => (),
            _ => panic!("Expected IoError for empty filename"),
        }
    }

    #[test]
    fn escaped_separator_in_key() {
        let yaml = "
database:
  host/port: localhost:5432
  server: db.example.com
";
        let config = Config::load_yaml(yaml, "/").unwrap();
        
        // Access key with escaped separator
        let value = config.get("database/host\\/port");
        assert!(value.is_some());
        assert_eq!(config.str("database/host\\/port"), "localhost:5432");
    }

    #[test]
    fn escaped_backslash_in_key() {
        let yaml = "
paths:
  'file\\path': C:\\Users\\data
  'normal': value
";
        let config = Config::load_yaml(yaml, "/").unwrap();
        
        // Access key with escaped backslash (literal backslash in key)
        let value = config.get("paths/file\\\\path");
        assert!(value.is_some());
    }

    #[test]
    fn mixed_escaped_and_normal_separators() {
        let yaml = "
config:
  app/version: 1.0
  'db/host:port': localhost:5432
";
        let config = Config::load_yaml(yaml, "/").unwrap();
        
        // Key with slash requires escaping
        let value1 = config.get("config/app\\/version");
        assert!(value1.is_some());
        assert_eq!(config.str("config/app\\/version"), "1.0");
        
        // Escaped separator in second key
        let value2 = config.get("config/db\\/host:port");
        assert!(value2.is_some());
    }

    #[test]
    fn escape_sequences_in_strict_methods() {
        let yaml = "
database:
  'user/pass': myuser/mypass
";
        let config = Config::load_yaml(yaml, "/").unwrap();
        
        // Test that escape sequences work with strict methods too
        let result = config.get_strict("database/user\\/pass");
        assert!(result.is_ok());
        
        let result = config.str_strict("database/user\\/pass");
        assert!(result.is_ok());
        assert_eq!(result.unwrap(), "myuser/mypass");
    }

    #[test]
    fn parse_path_basic() {
        let parts = Config::parse_path("a/b/c", "/");
        assert_eq!(parts, vec!["a", "b", "c"]);
    }

    #[test]
    fn parse_path_with_escaped_separator() {
        let parts = Config::parse_path("a/b\\/c/d", "/");
        assert_eq!(parts, vec!["a", "b/c", "d"]);
    }

    #[test]
    fn parse_path_with_escaped_backslash() {
        let parts = Config::parse_path("a/b\\\\c/d", "/");
        assert_eq!(parts, vec!["a", "b\\c", "d"]);
    }

    #[test]
    fn parse_path_multiple_escapes() {
        let parts = Config::parse_path("a\\/b\\/c/d", "/");
        assert_eq!(parts, vec!["a/b/c", "d"]);
    }

    #[test]
    fn parse_path_with_custom_separator() {
        let parts = Config::parse_path("a::b\\::c::d", "::");
        assert_eq!(parts, vec!["a", "b::c", "d"]);
    }

    #[test]
    fn reload_from_same_file() {
        use std::fs::{self, File};
        use std::io::Write;
        
        // Create a temporary test file
        let test_file = "test_reload_config.yaml";
        let mut file = File::create(test_file).unwrap();
        writeln!(file, "app:\n  port: 8080\n  debug: false").unwrap();
        drop(file);
        
        // Load initial config
        let mut config = Config::new(test_file, "/", None).unwrap();
        assert_eq!(config.str("app/port"), "8080");
        assert_eq!(config.str("app/debug"), "false");
        
        // Modify the file
        let mut file = File::create(test_file).unwrap();
        writeln!(file, "app:\n  port: 9090\n  debug: true").unwrap();
        drop(file);
        
        // Reload the config
        config.reload().unwrap();
        assert_eq!(config.str("app/port"), "9090");
        assert_eq!(config.str("app/debug"), "true");
        
        // Cleanup
        fs::remove_file(test_file).ok();
    }

    #[test]
    fn reload_from_different_file() {
        use std::fs::{self, File};
        use std::io::Write;
        
        let file1 = "test_reload_file1.yaml";
        let file2 = "test_reload_file2.yaml";
        
        // Create first file
        let mut file = File::create(file1).unwrap();
        writeln!(file, "config:\n  name: first\n  value: 100").unwrap();
        drop(file);
        
        // Create second file
        let mut file = File::create(file2).unwrap();
        writeln!(file, "config:\n  name: second\n  value: 200").unwrap();
        drop(file);
        
        // Load from first file
        let mut config = Config::new(file1, "/", None).unwrap();
        assert_eq!(config.str("config/name"), "first");
        assert_eq!(config.str("config/value"), "100");
        assert_eq!(config.get_filename(), file1);
        
        // Reload from second file
        config.reload_from(file2).unwrap();
        assert_eq!(config.str("config/name"), "second");
        assert_eq!(config.str("config/value"), "200");
        assert_eq!(config.get_filename(), file2);
        
        // Cleanup
        fs::remove_file(file1).ok();
        fs::remove_file(file2).ok();
    }

    #[test]
    fn reload_preserves_separator() {
        use std::fs::{self, File};
        use std::io::Write;
        
        let test_file = "test_reload_sep.yaml";
        let mut file = File::create(test_file).unwrap();
        writeln!(file, "db:\n  host: localhost\n  port: 5432").unwrap();
        drop(file);
        
        let mut config = Config::new(test_file, "::", None).unwrap();
        assert_eq!(config.str("db::host"), "localhost");
        
        // Modify file
        let mut file = File::create(test_file).unwrap();
        writeln!(file, "db:\n  host: remote\n  port: 3306").unwrap();
        drop(file);
        
        config.reload().unwrap();
        
        // Separator should still be "::"
        assert_eq!(config.str("db::host"), "remote");
        
        // Cleanup
        fs::remove_file(test_file).ok();
    }

    #[test]
    fn reload_from_string_config_fails() {
        let yaml = "test: value";
        let mut config = Config::load_yaml(yaml, "/").unwrap();
        
        let result = config.reload();
        assert!(result.is_err());
        match result {
            Err(ConfigError::FormatError(msg)) => {
                assert!(msg.contains("YAML string"));
            },
            _ => panic!("Expected FormatError"),
        }
    }

    #[test]
    fn reload_from_invalid_yaml_fails() {
        use std::fs::{self, File};
        use std::io::Write;
        
        let test_file = "test_reload_invalid.yaml";
        let mut file = File::create(test_file).unwrap();
        writeln!(file, "valid:\n  yaml: content").unwrap();
        drop(file);
        
        let mut config = Config::new(test_file, "/", None).unwrap();
        
        // Overwrite with invalid YAML
        let mut file = File::create(test_file).unwrap();
        writeln!(file, "invalid: [unclosed").unwrap();
        drop(file);
        
        let result = config.reload();
        assert!(result.is_err());
        
        // Original config still intact
        assert_eq!(config.str("valid/yaml"), "content");
        
        // Cleanup
        fs::remove_file(test_file).ok();
    }
}