brinkhaustools/
settings.rs

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
use std::env;
use std::fs;
use std::io::Write as IoWrite;
use std::path::{Path, PathBuf};
use std::sync::RwLock;

use chrono::Utc;
use serde::de::DeserializeOwned;
use serde::Serialize;
use serde_json::{Map, Value};
use sha2::{Digest, Sha256};

use crate::error::Result;

/// Reserved key at the root of the stored dict carrying a SHA256 trailer
/// over the canonical form of everything else.  Lets us detect silent
/// truncation that still parses as JSON.
pub const INTEGRITY_KEY: &str = "__integrity__";

/// Integrity algorithm identifier written into the trailer.
pub const INTEGRITY_ALGO: &str = "sha256-v1";

/// Reserved key at the root that signals a data-loss event.  Written
/// when `reload` finds all on-disk files unusable; survives reboots and
/// is the trigger for application-level self-diagnosis until an
/// operator calls `clear_data_loss_flag`.
pub const DATA_LOSS_KEY: &str = "__data_loss__";

/// Library-controlled keys.  Stripped from payloads delivered via
/// `load_json` and hidden from `raw_data` callers.
const RESERVED_KEYS: &[&str] = &[INTEGRITY_KEY, DATA_LOSS_KEY];

/// Where `reload` sourced its data from.
///
/// Matches the Python `RECOVERED_*` constants.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RecoveredFrom {
    /// Primary file loaded cleanly.
    Primary,
    /// Primary unreadable; loaded from first-generation backup.
    Bak,
    /// Primary and first backup unreadable; loaded from second-generation backup.
    Bak2,
    /// No file existed anywhere — first run, not a data-loss event.
    Fresh,
    /// At least one file existed but all were unreadable — data loss.
    EmptyFallback,
    /// `reload` has not been run yet (in-memory only).
    Unloaded,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum LoadStatus {
    Ok,
    Missing,
    Corrupt,
}

/// Thread-safe JSON settings with hierarchical key access and atomic persistence.
///
/// Supports dot-notation keys (`"section.key.0"`) where numeric segments
/// become array indices. Atomic writes with two-generation backup ensure
/// crash safety; a SHA256 integrity trailer catches silent truncation;
/// a `__data_loss__` breadcrumb is persisted when reload finds all
/// on-disk files unusable, so application-level self-diagnosis can
/// surface the data-loss event until an operator clears it.
pub struct Settings {
    data: RwLock<Value>,
    file_path: Option<PathBuf>,
    recovered_from: RwLock<RecoveredFrom>,
    pub auto_save: bool,
}

impl Settings {
    /// Create settings backed by a file. Loads existing data on creation.
    pub fn new(file_path: impl Into<PathBuf>) -> Self {
        let path = file_path.into();
        let settings = Self {
            data: RwLock::new(Value::Object(Map::new())),
            file_path: Some(path),
            recovered_from: RwLock::new(RecoveredFrom::Unloaded),
            auto_save: true,
        };
        settings.reload_internal();
        settings
    }

    /// Create in-memory-only settings (no file persistence).
    pub fn in_memory() -> Self {
        Self {
            data: RwLock::new(Value::Object(Map::new())),
            file_path: None,
            recovered_from: RwLock::new(RecoveredFrom::Unloaded),
            auto_save: false,
        }
    }

    /// Get a value at the given key path with a default fallback.
    ///
    /// If the key doesn't exist, it is created with the default value.
    /// If the stored type is incompatible with the default's type, the default is returned.
    pub fn get<T: DeserializeOwned + Serialize + Clone>(&self, key: &str, default: T) -> T {
        let segments = Self::parse_key(key);
        let mut data = self.data.write().unwrap();

        match Self::navigate(&data, &segments) {
            Some(val) => {
                // Type compatibility check: try to deserialize as T
                match serde_json::from_value::<T>(val.clone()) {
                    Ok(v) => v,
                    Err(_) => {
                        // Incompatible type — return default (matches Python behavior)
                        default
                    }
                }
            }
            None => {
                // Key doesn't exist — create with default and auto-save
                let json_val = serde_json::to_value(&default).unwrap();
                Self::set_at_path(&mut data, &segments, json_val);
                if self.auto_save {
                    if let Some(ref path) = self.file_path {
                        let _ = Self::save_to_disk(path, &data);
                    }
                }
                default
            }
        }
    }

    /// Set a value at the given key path. Creates intermediate nodes as needed.
    pub fn set<T: Serialize>(&self, key: &str, value: T) {
        let segments = Self::parse_key(key);
        let json_val = serde_json::to_value(value).unwrap();
        let mut data = self.data.write().unwrap();
        Self::set_at_path(&mut data, &segments, json_val);
        if self.auto_save {
            if let Some(ref path) = self.file_path {
                let _ = Self::save_to_disk(path, &data);
            }
        }
    }

    /// Check if a key path exists.
    pub fn exists(&self, key: &str) -> bool {
        let segments = Self::parse_key(key);
        let data = self.data.read().unwrap();
        Self::navigate(&data, &segments).is_some()
    }

    /// Return the length of an array or object at the given key, or -1 if missing.
    pub fn length(&self, key: &str) -> i64 {
        let segments = Self::parse_key(key);
        let data = self.data.read().unwrap();
        match Self::navigate(&data, &segments) {
            Some(Value::Array(arr)) => arr.len() as i64,
            Some(Value::Object(obj)) => obj.len() as i64,
            _ => -1,
        }
    }

    /// Delete a key. Returns `true` if the key existed.
    pub fn delete(&self, key: &str) -> bool {
        let segments = Self::parse_key(key);
        if segments.is_empty() {
            return false;
        }
        let mut data = self.data.write().unwrap();
        let (parent_segs, last) = segments.split_at(segments.len() - 1);
        let parent = if parent_segs.is_empty() {
            Some(&mut *data)
        } else {
            Self::navigate_mut(&mut data, parent_segs)
        };
        let removed = match parent {
            Some(Value::Object(map)) => {
                if let KeySegment::Named(name) = &last[0] {
                    map.remove(name).is_some()
                } else {
                    false
                }
            }
            Some(Value::Array(arr)) => {
                if let KeySegment::Index(idx) = &last[0] {
                    if *idx < arr.len() {
                        arr.remove(*idx);
                        true
                    } else {
                        false
                    }
                } else {
                    false
                }
            }
            _ => false,
        };
        if removed && self.auto_save {
            if let Some(ref path) = self.file_path {
                let _ = Self::save_to_disk(path, &data);
            }
        }
        removed
    }

    /// Move a value from one key to another. Returns `true` on success.
    pub fn move_key(&self, from: &str, to: &str) -> bool {
        let from_segments = Self::parse_key(from);
        let to_segments = Self::parse_key(to);
        let mut data = self.data.write().unwrap();

        // Extract value
        let val = match Self::navigate(&data, &from_segments) {
            Some(v) => v.clone(),
            None => return false,
        };

        // Remove from old location
        let (parent_segs, last) = from_segments.split_at(from_segments.len() - 1);
        let parent = if parent_segs.is_empty() {
            Some(&mut *data)
        } else {
            Self::navigate_mut(&mut data, parent_segs)
        };
        match parent {
            Some(Value::Object(map)) => {
                if let KeySegment::Named(name) = &last[0] {
                    map.remove(name);
                }
            }
            Some(Value::Array(arr)) => {
                if let KeySegment::Index(idx) = &last[0] {
                    if *idx < arr.len() {
                        arr.remove(*idx);
                    }
                }
            }
            _ => return false,
        }

        // Set at new location
        Self::set_at_path(&mut data, &to_segments, val);

        if self.auto_save {
            if let Some(ref path) = self.file_path {
                let _ = Self::save_to_disk(path, &data);
            }
        }
        true
    }

    /// Persist settings to disk with atomic write and backup rotation.
    pub fn save(&self) -> Result<()> {
        let data = self.data.read().unwrap();
        if let Some(ref path) = self.file_path {
            Self::save_to_disk(path, &data)?;
        }
        Ok(())
    }

    /// Reload settings from disk. Falls back to .bak and .bak2, verifies
    /// integrity trailers, and writes a `__data_loss__` breadcrumb if all
    /// three files are unusable.
    pub fn reload(&self) -> Result<()> {
        // `reload` is public and may be called without a `&mut self`, so we
        // cannot take `self` by value.  The internal variant does all the
        // work via interior mutability on `data` / `recovered_from`.
        self.reload_internal();
        Ok(())
    }

    /// Serialize current settings to a JSON string.
    pub fn to_json(&self) -> String {
        let data = self.data.read().unwrap();
        serde_json::to_string_pretty(&*data).unwrap_or_else(|_| "{}".to_string())
    }

    /// Replace all settings with data from a JSON string.
    ///
    /// Reserved keys (`__integrity__`, `__data_loss__`) are stripped from
    /// the incoming payload — they are library-controlled and must not
    /// be set by clients.  Any existing `__data_loss__` breadcrumb is
    /// carried forward so a partial UI save cannot silently hide the
    /// warning; it is cleared only by `clear_data_loss_flag`.
    pub fn load_json(&self, json: &str) -> Result<()> {
        let mut parsed: Value = serde_json::from_str(json)?;
        if let Value::Object(ref mut map) = parsed {
            for reserved in RESERVED_KEYS {
                map.remove(*reserved);
            }
        }
        let mut data = self.data.write().unwrap();
        let carry_forward = if let Value::Object(ref map) = *data {
            map.get(DATA_LOSS_KEY).cloned()
        } else {
            None
        };
        *data = parsed;
        if let (Some(bc), Value::Object(ref mut map)) = (carry_forward, &mut *data) {
            map.insert(DATA_LOSS_KEY.to_string(), bc);
        }
        if self.auto_save {
            if let Some(ref path) = self.file_path {
                Self::save_to_disk(path, &data)?;
            }
        }
        Ok(())
    }

    /// Read from environment variable first, then fall back to settings key.
    pub fn get_from_env<T: DeserializeOwned + Serialize + Clone + std::str::FromStr>(
        &self,
        env_name: &str,
        key: &str,
        default: T,
    ) -> T {
        if let Ok(env_val) = env::var(env_name) {
            if let Ok(parsed) = env_val.parse::<T>() {
                return parsed;
            }
        }
        self.get(key, default)
    }

    /// Get raw JSON data (for testing and inspection).
    pub fn raw_data(&self) -> Value {
        self.data.read().unwrap().clone()
    }

    // ------------------------------------------------------------------
    // Recovery state + data-loss breadcrumb API
    // ------------------------------------------------------------------

    /// Where the last reload sourced its data from.
    pub fn recovered_from(&self) -> RecoveredFrom {
        *self.recovered_from.read().unwrap()
    }

    /// Return `true` while the `__data_loss__` breadcrumb is present.
    ///
    /// The breadcrumb is written on boot when all three settings files
    /// were unreadable and persists across reboots until
    /// [`Self::clear_data_loss_flag`] is called.  Use this as the
    /// trigger for a critical self-diagnosis message.
    pub fn has_data_loss_flag(&self) -> bool {
        let data = self.data.read().unwrap();
        matches!(&*data, Value::Object(map) if map.contains_key(DATA_LOSS_KEY))
    }

    /// Return a clone of the breadcrumb object if it is present.
    pub fn data_loss_info(&self) -> Option<Value> {
        let data = self.data.read().unwrap();
        match &*data {
            Value::Object(map) => map.get(DATA_LOSS_KEY).cloned(),
            _ => None,
        }
    }

    /// Remove the data-loss breadcrumb and persist.
    ///
    /// Call this after an operator has acknowledged the data-loss
    /// event.  Because `get` never auto-creates the breadcrumb, it
    /// stays cleared unless a fresh data-loss event occurs.  No-op if
    /// the flag is not set.
    pub fn clear_data_loss_flag(&self) -> Result<()> {
        let mut data = self.data.write().unwrap();
        let removed = match &mut *data {
            Value::Object(map) => map.remove(DATA_LOSS_KEY).is_some(),
            _ => false,
        };
        if removed {
            log::info!("Cleared __data_loss__ breadcrumb");
            if let Some(ref path) = self.file_path {
                Self::save_to_disk(path, &data)?;
            }
        }
        Ok(())
    }

    // --- Private helpers ---

    fn reload_internal(&self) {
        let Some(ref path) = self.file_path else {
            return;
        };

        let bak = PathBuf::from(format!("{}.bak", path.display()));
        let bak2 = PathBuf::from(format!("{}.bak2", path.display()));

        let (primary_data, primary_status) = Self::try_load(path);
        if primary_status == LoadStatus::Ok {
            *self.data.write().unwrap() = primary_data.unwrap();
            *self.recovered_from.write().unwrap() = RecoveredFrom::Primary;
            return;
        }

        let (bak_data, bak_status) = Self::try_load(&bak);
        if bak_status == LoadStatus::Ok {
            *self.data.write().unwrap() = bak_data.unwrap();
            *self.recovered_from.write().unwrap() = RecoveredFrom::Bak;
            log::warn!(
                "Loaded settings from first-generation backup {} — rebuilding main + backup chain",
                bak.display()
            );
            self.self_heal_after_backup_load();
            return;
        }

        let (bak2_data, bak2_status) = Self::try_load(&bak2);
        if bak2_status == LoadStatus::Ok {
            *self.data.write().unwrap() = bak2_data.unwrap();
            *self.recovered_from.write().unwrap() = RecoveredFrom::Bak2;
            log::warn!(
                "Loaded settings from second-generation backup {} — rebuilding main + backup chain",
                bak2.display()
            );
            self.self_heal_after_backup_load();
            return;
        }

        // All three unusable — either fresh start or data loss.
        *self.data.write().unwrap() = Value::Object(Map::new());

        let all_missing = primary_status == LoadStatus::Missing
            && bak_status == LoadStatus::Missing
            && bak2_status == LoadStatus::Missing;

        if all_missing {
            log::info!("No settings file at {} — starting fresh", path.display());
            *self.recovered_from.write().unwrap() = RecoveredFrom::Fresh;
            return;
        }

        log::error!(
            "All settings files unreadable ({}, .bak, .bak2) — starting with empty settings. \
             This is a data-loss event. Leaving __data_loss__ breadcrumb for self-diagnosis.",
            path.display()
        );
        *self.recovered_from.write().unwrap() = RecoveredFrom::EmptyFallback;

        let breadcrumb = serde_json::json!({
            "detected_at": Utc::now().format("%Y-%m-%dT%H:%M:%SZ").to_string(),
            "main_status": status_str(primary_status),
            "bak_status": status_str(bak_status),
            "bak2_status": status_str(bak2_status),
        });
        if let Value::Object(ref mut map) = *self.data.write().unwrap() {
            map.insert(DATA_LOSS_KEY.to_string(), breadcrumb);
        }
        // Persist immediately so the breadcrumb survives a further crash
        // before the first get/set.
        let data = self.data.read().unwrap();
        if let Err(e) = Self::save_to_disk(path, &data) {
            log::warn!(
                "Could not persist __data_loss__ breadcrumb: {} — will retry on next save",
                e
            );
        }
    }

    fn self_heal_after_backup_load(&self) {
        if let Some(ref path) = self.file_path {
            let data = self.data.read().unwrap();
            if let Err(e) = Self::save_to_disk(path, &data) {
                log::warn!(
                    "Self-heal save failed for {}: {} — chain remains degraded",
                    path.display(),
                    e
                );
            }
        }
    }

    fn parse_key(key: &str) -> Vec<KeySegment> {
        key.split('.')
            .map(|s| {
                if let Ok(idx) = s.parse::<usize>() {
                    KeySegment::Index(idx)
                } else {
                    KeySegment::Named(s.to_string())
                }
            })
            .collect()
    }

    fn navigate<'a>(data: &'a Value, segments: &[KeySegment]) -> Option<&'a Value> {
        let mut current = data;
        for seg in segments {
            match seg {
                KeySegment::Named(name) => {
                    current = current.get(name)?;
                }
                KeySegment::Index(idx) => {
                    current = current.get(idx)?;
                }
            }
        }
        Some(current)
    }

    fn navigate_mut<'a>(data: &'a mut Value, segments: &[KeySegment]) -> Option<&'a mut Value> {
        let mut current = data;
        for seg in segments {
            match seg {
                KeySegment::Named(name) => {
                    current = current.get_mut(name)?;
                }
                KeySegment::Index(idx) => {
                    current = current.get_mut(idx)?;
                }
            }
        }
        Some(current)
    }

    fn set_at_path(data: &mut Value, segments: &[KeySegment], value: Value) {
        if segments.is_empty() {
            *data = value;
            return;
        }

        let mut current = data;
        for (i, seg) in segments.iter().enumerate() {
            if i == segments.len() - 1 {
                // Last segment — set value
                match seg {
                    KeySegment::Named(name) => {
                        if !current.is_object() {
                            *current = Value::Object(Map::new());
                        }
                        current.as_object_mut().unwrap().insert(name.clone(), value);
                        return;
                    }
                    KeySegment::Index(idx) => {
                        if !current.is_array() {
                            *current = Value::Array(Vec::new());
                        }
                        let arr = current.as_array_mut().unwrap();
                        while arr.len() <= *idx {
                            arr.push(Value::Null);
                        }
                        arr[*idx] = value;
                        return;
                    }
                }
            } else {
                // Intermediate segment — ensure container exists
                let next_is_index = matches!(segments.get(i + 1), Some(KeySegment::Index(_)));
                match seg {
                    KeySegment::Named(name) => {
                        if !current.is_object() {
                            *current = Value::Object(Map::new());
                        }
                        let map = current.as_object_mut().unwrap();
                        if !map.contains_key(name) {
                            if next_is_index {
                                map.insert(name.clone(), Value::Array(Vec::new()));
                            } else {
                                map.insert(name.clone(), Value::Object(Map::new()));
                            }
                        }
                        current = map.get_mut(name).unwrap();
                    }
                    KeySegment::Index(idx) => {
                        if !current.is_array() {
                            *current = Value::Array(Vec::new());
                        }
                        let arr = current.as_array_mut().unwrap();
                        while arr.len() <= *idx {
                            if next_is_index {
                                arr.push(Value::Array(Vec::new()));
                            } else {
                                arr.push(Value::Object(Map::new()));
                            }
                        }
                        current = &mut arr[*idx];
                    }
                }
            }
        }
    }

    /// Attempt to load *path*, verifying the integrity trailer if present.
    ///
    /// On success the trailer is stripped before the value is returned.
    /// Returns `(None, Missing)` if the file doesn't exist,
    /// `(None, Corrupt)` on parse error or integrity mismatch.
    fn try_load(path: &Path) -> (Option<Value>, LoadStatus) {
        let contents = match fs::read_to_string(path) {
            Ok(s) => s,
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
                return (None, LoadStatus::Missing);
            }
            Err(e) => {
                log::warn!("Could not read {}: {}", path.display(), e);
                return (None, LoadStatus::Corrupt);
            }
        };

        let mut parsed: Value = match serde_json::from_str(&contents) {
            Ok(v) => v,
            Err(e) => {
                log::warn!("Could not parse {}: {}", path.display(), e);
                return (None, LoadStatus::Corrupt);
            }
        };

        if let Value::Object(ref mut map) = parsed {
            if let Some(trailer) = map.remove(INTEGRITY_KEY) {
                if !verify_trailer(map, &trailer, path) {
                    return (None, LoadStatus::Corrupt);
                }
            }
        }

        (Some(parsed), LoadStatus::Ok)
    }

    fn save_to_disk(path: &Path, data: &Value) -> Result<()> {
        // Ensure parent directory exists
        if let Some(parent) = path.parent() {
            fs::create_dir_all(parent)?;
        }

        let tmp_path = PathBuf::from(format!("{}.tmp", path.display()));
        let bak_path = PathBuf::from(format!("{}.bak", path.display()));
        let bak2_path = PathBuf::from(format!("{}.bak2", path.display()));

        // Build the payload with a fresh integrity trailer.
        let payload = with_integrity_trailer(data);

        // Write to temp file
        {
            let mut file = fs::File::create(&tmp_path)?;
            let json = serde_json::to_string_pretty(&payload)?;
            file.write_all(json.as_bytes())?;
            file.sync_all()?; // fsync the file
        }

        // Rotate backups: existing .bak → .bak2, then current file → .bak
        if bak_path.exists() {
            if bak2_path.exists() {
                let _ = fs::remove_file(&bak2_path);
            }
            let _ = fs::rename(&bak_path, &bak2_path);
        }
        if path.exists() {
            let _ = fs::rename(path, &bak_path);
        }

        // Temp → current
        fs::rename(&tmp_path, path)?;

        // fsync parent directory
        if let Some(parent) = path.parent() {
            if let Ok(dir) = fs::File::open(parent) {
                let _ = dir.sync_all();
            }
        }

        Ok(())
    }
}

#[derive(Debug, Clone)]
enum KeySegment {
    Named(String),
    Index(usize),
}

fn status_str(s: LoadStatus) -> &'static str {
    match s {
        LoadStatus::Ok => "ok",
        LoadStatus::Missing => "missing",
        LoadStatus::Corrupt => "corrupt",
    }
}

/// Canonical SHA256 over a JSON value, excluding the integrity key.
///
/// Keys are sorted (serde_json::Map preserves insertion order unless the
/// `preserve_order` feature is enabled — by default iteration is already
/// alphabetical).  We build a fresh sorted `BTreeMap` to be explicit and
/// robust against future feature changes.
fn canonical_hash(value: &Value) -> String {
    let canonical = to_canonical_string(value);
    let mut hasher = Sha256::new();
    hasher.update(canonical.as_bytes());
    format!("{:x}", hasher.finalize())
}

fn to_canonical_string(value: &Value) -> String {
    // Serialize with sorted keys, no whitespace — matches Python's
    // `json.dumps(..., sort_keys=True, separators=(",", ":"))`.
    let sorted = sort_value(value);
    serde_json::to_string(&sorted).unwrap_or_default()
}

fn sort_value(value: &Value) -> Value {
    match value {
        Value::Object(map) => {
            let mut btree = std::collections::BTreeMap::new();
            for (k, v) in map {
                btree.insert(k.clone(), sort_value(v));
            }
            let mut ordered = Map::new();
            for (k, v) in btree {
                ordered.insert(k, v);
            }
            Value::Object(ordered)
        }
        Value::Array(arr) => Value::Array(arr.iter().map(sort_value).collect()),
        other => other.clone(),
    }
}

/// Build the on-disk payload by appending an `__integrity__` trailer.
fn with_integrity_trailer(value: &Value) -> Value {
    let Value::Object(ref map) = value else {
        // Trailer only applies to dict roots; pass through otherwise.
        return value.clone();
    };
    let mut base = map.clone();
    // Exclude any prior trailer so round-trip is stable.
    base.remove(INTEGRITY_KEY);
    let base_val = Value::Object(base.clone());
    let trailer = serde_json::json!({
        "algo": INTEGRITY_ALGO,
        "sha256": canonical_hash(&base_val),
        "size": base.len(),
        "saved_at": Utc::now().format("%Y-%m-%dT%H:%M:%SZ").to_string(),
    });
    base.insert(INTEGRITY_KEY.to_string(), trailer);
    Value::Object(base)
}

/// Return `true` if *trailer* matches the hash of *payload*.
fn verify_trailer(payload: &Map<String, Value>, trailer: &Value, path: &Path) -> bool {
    let Value::Object(ref t) = *trailer else {
        log::warn!(
            "Integrity trailer in {} is not an object — treating file as corrupt",
            path.display()
        );
        return false;
    };
    let algo = t.get("algo").and_then(Value::as_str);
    let expected = t.get("sha256").and_then(Value::as_str);
    match (algo, expected) {
        (Some(a), Some(exp)) if a == INTEGRITY_ALGO => {
            let payload_val = Value::Object(payload.clone());
            let actual = canonical_hash(&payload_val);
            if actual != exp {
                log::warn!(
                    "Integrity check FAILED for {} (expected {}, got {}) — \
                     treating as corrupt, falling through to backup",
                    path.display(),
                    exp,
                    actual
                );
                return false;
            }
            true
        }
        _ => {
            // Unknown algorithm: accept rather than lose data for a
            // future-compatible format we don't understand yet.
            log::info!(
                "Integrity trailer in {} uses unknown algo {:?} — skipping verification",
                path.display(),
                algo
            );
            true
        }
    }
}

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

    fn make_settings(initial: Option<&Value>) -> (Settings, tempfile::NamedTempFile) {
        let file = tempfile::NamedTempFile::new().unwrap();
        if let Some(data) = initial {
            fs::write(file.path(), serde_json::to_string(data).unwrap()).unwrap();
        } else {
            // Remove the zero-byte file mkstemp creates so `new` sees a
            // genuine fresh-start scenario instead of a corrupt file.
            let _ = fs::remove_file(file.path());
        }
        let s = Settings::new(file.path());
        (s, file)
    }

    fn stripped(s: &Settings) -> Value {
        // Raw data minus reserved keys, so simple content assertions aren't
        // fooled by the trailer / breadcrumb that the crash-safety code
        // manages.
        let mut v = s.raw_data();
        if let Value::Object(ref mut map) = v {
            for k in RESERVED_KEYS {
                map.remove(*k);
            }
        }
        v
    }

    // ------------------------------------------------------------------
    // Pre-existing behaviour (kept from before the hardening).
    // ------------------------------------------------------------------

    #[test]
    fn test_get_creates_missing_key() {
        let (s, file) = make_settings(None);
        let val: String = s.get("section.key", "hello".to_string());
        assert_eq!(val, "hello");
        let contents: Value =
            serde_json::from_str(&fs::read_to_string(file.path()).unwrap()).unwrap();
        assert_eq!(contents["section"]["key"], "hello");
    }

    #[test]
    fn test_get_returns_existing_value() {
        let data = serde_json::json!({"section": {"key": "world"}});
        let (s, _file) = make_settings(Some(&data));
        let val: String = s.get("section.key", "default".to_string());
        assert_eq!(val, "world");
    }

    #[test]
    fn test_set_and_get() {
        let (s, _file) = make_settings(None);
        s.set("a.b", 42);
        let val: i64 = s.get("a.b", 0);
        assert_eq!(val, 42);
    }

    #[test]
    fn test_dot_notation() {
        let data = serde_json::json!({"level1": {"level2": "value"}});
        let (s, _file) = make_settings(Some(&data));
        let val: String = s.get("level1.level2", "x".to_string());
        assert_eq!(val, "value");
        s.set("level1.new_key", 123);
        let val2: i64 = s.get("level1.new_key", 0);
        assert_eq!(val2, 123);
    }

    #[test]
    fn test_array_access() {
        let data = serde_json::json!({"items": [{"name": "a"}, {"name": "b"}]});
        let (s, _file) = make_settings(Some(&data));
        let a: String = s.get("items.0.name", String::new());
        let b: String = s.get("items.1.name", String::new());
        assert_eq!(a, "a");
        assert_eq!(b, "b");
    }

    #[test]
    fn test_dot_notation_with_array_index() {
        let data = serde_json::json!({"items": ["a", "b", "c"]});
        let (s, _file) = make_settings(Some(&data));
        let val: String = s.get("items.1", String::new());
        assert_eq!(val, "b");
    }

    #[test]
    fn test_exist() {
        let data = serde_json::json!({"a": {"b": 1}});
        let (s, _file) = make_settings(Some(&data));
        assert!(s.exists("a.b"));
        assert!(!s.exists("a.c"));
    }

    #[test]
    fn test_length() {
        let data = serde_json::json!({"items": [1, 2, 3]});
        let (s, _file) = make_settings(Some(&data));
        assert_eq!(s.length("items"), 3);
        assert_eq!(s.length("nonexistent"), -1);
    }

    #[test]
    fn test_delete_key() {
        let data = serde_json::json!({"a": {"b": 1, "c": 2}});
        let (s, _file) = make_settings(Some(&data));
        assert!(s.delete("a.b"));
        assert!(!s.exists("a.b"));
        assert!(s.exists("a.c"));
    }

    #[test]
    fn test_move_key() {
        let data = serde_json::json!({"old": {"key": "val"}});
        let (s, _file) = make_settings(Some(&data));
        assert!(s.move_key("old.key", "new.key"));
        assert!(!s.exists("old.key"));
        let val: String = s.get("new.key", String::new());
        assert_eq!(val, "val");
    }

    #[test]
    fn test_reload() {
        let data = serde_json::json!({"x": 1});
        let (s, file) = make_settings(Some(&data));
        fs::write(file.path(), r#"{"x": 99}"#).unwrap();
        s.reload().unwrap();
        let val: i64 = s.get("x", 0);
        assert_eq!(val, 99);
    }

    #[test]
    fn test_to_json_and_load_json() {
        let data = serde_json::json!({"a": 1});
        let (s, _file) = make_settings(Some(&data));
        let j = s.to_json();
        let parsed: Value = serde_json::from_str(&j).unwrap();
        assert_eq!(parsed["a"], 1);

        s.load_json(r#"{"b": 2}"#).unwrap();
        let val: i64 = s.get("b", 0);
        assert_eq!(val, 2);
        assert!(!s.exists("a"));
    }

    #[test]
    fn test_type_compatibility() {
        let data = serde_json::json!({"val": 42});
        let (s, _file) = make_settings(Some(&data));
        let val: f64 = s.get("val", 0.0);
        assert_eq!(val, 42.0);
        let val2: String = s.get("val", "x".to_string());
        assert_eq!(val2, "x");
    }

    #[test]
    fn test_in_memory_only() {
        let s = Settings::in_memory();
        s.set("key", "value");
        let val: String = s.get("key", String::new());
        assert_eq!(val, "value");
    }

    #[test]
    fn test_get_value_from_env() {
        let (s, _file) = make_settings(None);
        env::set_var("BRINKHAUSTOOLS_TEST_VAR_123", "from_env");
        let val: String = s.get_from_env(
            "BRINKHAUSTOOLS_TEST_VAR_123",
            "env_key",
            "fallback".to_string(),
        );
        assert_eq!(val, "from_env");
        let val2: String = s.get_from_env(
            "NONEXISTENT_VAR_XYZ_999",
            "other_key",
            "default_val".to_string(),
        );
        assert_eq!(val2, "default_val");
        env::remove_var("BRINKHAUSTOOLS_TEST_VAR_123");
    }

    #[test]
    fn test_fallback_to_empty_when_both_corrupted() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("settings.json");
        fs::write(&path, "NOT VALID JSON").unwrap();
        fs::write(format!("{}.bak", path.display()), "NOT VALID JSON").unwrap();
        let s = Settings::new(&path);
        // Only the breadcrumb should be present; no user data.
        assert!(stripped(&s).as_object().unwrap().is_empty());
        assert_eq!(s.recovered_from(), RecoveredFrom::EmptyFallback);
    }

    #[test]
    fn test_fallback_to_bak2() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("settings.json");
        fs::write(&path, "NOT VALID JSON").unwrap();
        fs::write(format!("{}.bak", path.display()), "NOT VALID JSON").unwrap();
        fs::write(
            format!("{}.bak2", path.display()),
            r#"{"recovered": true}"#,
        )
        .unwrap();
        let s = Settings::new(&path);
        assert_eq!(s.raw_data()["recovered"], true);
        assert_eq!(s.recovered_from(), RecoveredFrom::Bak2);
    }

    #[test]
    fn test_two_backup_generations() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("settings.json");
        fs::write(&path, r#"{"v": 0}"#).unwrap();

        let mut s = Settings::new(&path);
        s.auto_save = false;
        s.load_json(r#"{"v": 1}"#).unwrap();
        s.save().unwrap(); // .bak = v0, main = v1

        s.load_json(r#"{"v": 2}"#).unwrap();
        s.save().unwrap(); // .bak2 = v0, .bak = v1, main = v2

        let bak2: Value = serde_json::from_str(
            &fs::read_to_string(format!("{}.bak2", path.display())).unwrap(),
        )
        .unwrap();
        assert_eq!(bak2["v"], 0);

        let bak: Value =
            serde_json::from_str(&fs::read_to_string(format!("{}.bak", path.display())).unwrap())
                .unwrap();
        assert_eq!(bak["v"], 1);

        let main: Value = serde_json::from_str(&fs::read_to_string(&path).unwrap()).unwrap();
        assert_eq!(main["v"], 2);
    }

    #[test]
    fn test_stale_tmp_ignored() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("settings.json");
        fs::write(&path, r#"{"v": "good"}"#).unwrap();
        fs::write(format!("{}.tmp", path.display()), "GARBAGE").unwrap();
        let s = Settings::new(&path);
        assert_eq!(s.raw_data()["v"], "good");
    }

    #[test]
    fn test_atomic_write_fsync() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("settings.json");
        let mut s = Settings::new(&path);
        s.auto_save = false;
        s.set("test", "value");
        s.save().unwrap();
        let contents: Value =
            serde_json::from_str(&fs::read_to_string(&path).unwrap()).unwrap();
        assert_eq!(contents["test"], "value");
    }

    #[test]
    fn test_concurrent_read_write() {
        use std::sync::Arc;
        use std::thread;

        let s = Arc::new(Settings::in_memory());
        let mut handles = vec![];
        for i in 0..10 {
            let s = s.clone();
            handles.push(thread::spawn(move || {
                let key = format!("key.{}", i);
                s.set(&key, i);
                let _: i64 = s.get(&key, 0);
            }));
        }
        for h in handles {
            h.join().unwrap();
        }
        for i in 0..10 {
            let key = format!("key.{}", i);
            assert!(s.exists(&key));
        }
    }

    // ------------------------------------------------------------------
    // Crash-safety hardening (2026-04-23): integrity trailer,
    // recovered_from, data-loss breadcrumb.
    // ------------------------------------------------------------------

    #[test]
    fn test_save_writes_integrity_trailer() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("settings.json");
        let s = Settings::new(&path);
        s.set("a", 1);
        s.set("b", serde_json::json!([1, 2, 3]));
        let stored: Value =
            serde_json::from_str(&fs::read_to_string(&path).unwrap()).unwrap();
        let trailer = &stored[INTEGRITY_KEY];
        assert_eq!(trailer["algo"], INTEGRITY_ALGO);
        let sha = trailer["sha256"].as_str().unwrap();
        assert_eq!(sha.len(), 64);
    }

    #[test]
    fn test_integrity_trailer_is_stripped_on_load() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("settings.json");
        {
            let s1 = Settings::new(&path);
            s1.set("real_key", "real_value");
        }
        let s2 = Settings::new(&path);
        let real: String = s2.get("real_key", String::new());
        assert_eq!(real, "real_value");
        // __integrity__ must not be accessible via normal keys.
        assert!(!s2.exists(INTEGRITY_KEY));
    }

    #[test]
    fn test_integrity_mismatch_falls_back_to_bak() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("settings.json");

        // Two saves so .bak is populated with a valid trailer.
        {
            let s = Settings::new(&path);
            s.set("good", "bak_value");
            s.set("good", "main_value"); // rotates: .bak = bak_value, main = main_value
        }

        // Tamper with the main file: keep JSON valid, change a value.
        let mut tampered: Value =
            serde_json::from_str(&fs::read_to_string(&path).unwrap()).unwrap();
        tampered["good"] = Value::String("TAMPERED".to_string());
        fs::write(&path, serde_json::to_string_pretty(&tampered).unwrap()).unwrap();

        let s2 = Settings::new(&path);
        let v: String = s2.get("good", String::new());
        assert_eq!(v, "bak_value");
        assert_eq!(s2.recovered_from(), RecoveredFrom::Bak);
    }

    #[test]
    fn test_file_without_trailer_is_accepted_for_backcompat() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("settings.json");
        // Pre-existing file without trailer (e.g. installed by image seed).
        fs::write(&path, r#"{"legacy": "ok"}"#).unwrap();
        let s = Settings::new(&path);
        let v: String = s.get("legacy", String::new());
        assert_eq!(v, "ok");
        assert_eq!(s.recovered_from(), RecoveredFrom::Primary);
    }

    #[test]
    fn test_fresh_start_does_not_set_data_loss_flag() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("settings.json");
        let s = Settings::new(&path);
        assert_eq!(s.recovered_from(), RecoveredFrom::Fresh);
        assert!(!s.has_data_loss_flag());
        // After a normal get with default, file appears but still no breadcrumb.
        let _: String = s.get("key", "hello".to_string());
        let stored: Value =
            serde_json::from_str(&fs::read_to_string(&path).unwrap()).unwrap();
        assert!(!stored.as_object().unwrap().contains_key(DATA_LOSS_KEY));
    }

    #[test]
    fn test_empty_fallback_writes_data_loss_breadcrumb_and_persists() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("settings.json");
        fs::write(&path, "CORRUPT").unwrap();
        fs::write(format!("{}.bak", path.display()), "CORRUPT").unwrap();

        let s = Settings::new(&path);
        assert_eq!(s.recovered_from(), RecoveredFrom::EmptyFallback);
        assert!(s.has_data_loss_flag());
        let info = s.data_loss_info().unwrap();
        assert_eq!(info["main_status"], "corrupt");
        assert_eq!(info["bak_status"], "corrupt");
        assert_eq!(info["bak2_status"], "missing");
        assert!(info["detected_at"].as_str().unwrap().ends_with('Z'));

        // Breadcrumb persisted immediately — no set() was called.
        let stored: Value =
            serde_json::from_str(&fs::read_to_string(&path).unwrap()).unwrap();
        assert!(stored.as_object().unwrap().contains_key(DATA_LOSS_KEY));
        assert!(stored.as_object().unwrap().contains_key(INTEGRITY_KEY));
    }

    #[test]
    fn test_data_loss_breadcrumb_survives_reboot() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("settings.json");
        fs::write(&path, "CORRUPT").unwrap();
        fs::write(format!("{}.bak", path.display()), "CORRUPT").unwrap();

        {
            let _s = Settings::new(&path); // first boot writes breadcrumb
        }
        // Second boot — the primary file is now the freshly-saved one.
        let s2 = Settings::new(&path);
        assert_eq!(s2.recovered_from(), RecoveredFrom::Primary);
        assert!(s2.has_data_loss_flag());
    }

    #[test]
    fn test_clear_data_loss_flag_removes_and_persists() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("settings.json");
        fs::write(&path, "CORRUPT").unwrap();
        fs::write(format!("{}.bak", path.display()), "CORRUPT").unwrap();
        let s = Settings::new(&path);
        assert!(s.has_data_loss_flag());

        s.clear_data_loss_flag().unwrap();
        assert!(!s.has_data_loss_flag());
        assert!(s.data_loss_info().is_none());

        let stored: Value =
            serde_json::from_str(&fs::read_to_string(&path).unwrap()).unwrap();
        assert!(!stored.as_object().unwrap().contains_key(DATA_LOSS_KEY));
    }

    #[test]
    fn test_get_with_default_does_not_resurrect_cleared_breadcrumb() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("settings.json");
        fs::write(&path, "CORRUPT").unwrap();
        fs::write(format!("{}.bak", path.display()), "CORRUPT").unwrap();
        let s = Settings::new(&path);
        s.clear_data_loss_flag().unwrap();

        // Normal app flow: get() calls with defaults — none touches
        // __data_loss__ at the root, so exists() stays false.
        let _: String = s.get("network.ip", "10.0.0.1".to_string());
        let _: String = s.get("mqtt.broker", "localhost".to_string());
        assert!(!s.has_data_loss_flag());
        assert!(!s.exists(DATA_LOSS_KEY));
    }

    #[test]
    fn test_load_json_preserves_existing_data_loss_breadcrumb() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("settings.json");
        fs::write(&path, "CORRUPT").unwrap();
        fs::write(format!("{}.bak", path.display()), "CORRUPT").unwrap();
        let s = Settings::new(&path);
        let original = s.data_loss_info().unwrap();

        // UI posts a partial settings payload.  The breadcrumb must survive.
        s.load_json(r#"{"network": {"ip": "10.0.0.1"}}"#).unwrap();
        assert!(s.has_data_loss_flag());
        assert_eq!(s.data_loss_info().unwrap(), original);
        let ip: String = s.get("network.ip", String::new());
        assert_eq!(ip, "10.0.0.1");
    }

    #[test]
    fn test_load_json_strips_reserved_keys_from_incoming_payload() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("settings.json");
        let s = Settings::new(&path);
        let payload = r#"{
            "app": "ok",
            "__data_loss__": {"detected_at": "malicious", "main_status": "corrupt"},
            "__integrity__": {"algo": "sha256-v1", "sha256": "bogus"}
        }"#;
        s.load_json(payload).unwrap();

        let stored: Value =
            serde_json::from_str(&fs::read_to_string(&path).unwrap()).unwrap();
        assert_eq!(stored["app"], "ok");
        // Neither reserved key leaks in from the client.
        assert!(!stored.as_object().unwrap().contains_key(DATA_LOSS_KEY));
        // __integrity__ is re-added by save() with the correct hash.
        assert!(stored.as_object().unwrap().contains_key(INTEGRITY_KEY));
        assert_ne!(stored[INTEGRITY_KEY]["sha256"], "bogus");
    }

    #[test]
    fn test_auto_save_stays_enabled_after_empty_fallback() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("settings.json");
        fs::write(&path, "CORRUPT").unwrap();
        fs::write(format!("{}.bak", path.display()), "CORRUPT").unwrap();
        let s = Settings::new(&path);
        // auto_save must not be blocked — edge devices are headless and
        // nobody is there to "acknowledge" in the moment.
        assert!(s.auto_save);
    }

    #[test]
    fn test_trailer_hash_stable_for_same_content() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("settings.json");
        {
            let s = Settings::new(&path);
            s.set("a", 1);
            s.set("b", serde_json::json!({"c": [1, 2, 3]}));
        }
        let first: Value =
            serde_json::from_str(&fs::read_to_string(&path).unwrap()).unwrap();
        // Another save with identical content (via reload + save) → same hash.
        let s2 = Settings::new(&path);
        s2.save().unwrap();
        let second: Value =
            serde_json::from_str(&fs::read_to_string(&path).unwrap()).unwrap();
        assert_eq!(first[INTEGRITY_KEY]["sha256"], second[INTEGRITY_KEY]["sha256"]);
    }

    #[test]
    fn test_trailer_hash_changes_when_content_changes() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("settings.json");
        let s = Settings::new(&path);
        s.set("v", 1);
        let stored1: Value =
            serde_json::from_str(&fs::read_to_string(&path).unwrap()).unwrap();
        let sha1 = stored1[INTEGRITY_KEY]["sha256"].as_str().unwrap().to_string();
        s.set("v", 2);
        let stored2: Value =
            serde_json::from_str(&fs::read_to_string(&path).unwrap()).unwrap();
        let sha2 = stored2[INTEGRITY_KEY]["sha256"].as_str().unwrap().to_string();
        assert_ne!(sha1, sha2);
    }

    #[test]
    fn test_self_heal_after_bak_recovery_rebuilds_chain() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("settings.json");

        // Seed a valid (trailer-bearing) .bak; garbage main; no .bak2.
        {
            let seed_path = dir.path().join("seed.json");
            let seed = Settings::new(&seed_path);
            seed.set("seeded", true);
            fs::rename(&seed_path, format!("{}.bak", path.display())).unwrap();
        }
        fs::write(&path, "GARBAGE NOT JSON").unwrap();

        let s = Settings::new(&path);
        assert_eq!(s.recovered_from(), RecoveredFrom::Bak);
        let v: bool = s.get("seeded", false);
        assert!(v);

        // Self-heal wrote a valid primary again.
        let restored: Value =
            serde_json::from_str(&fs::read_to_string(&path).unwrap()).unwrap();
        assert_eq!(restored["seeded"], true);
        assert!(restored.as_object().unwrap().contains_key(INTEGRITY_KEY));
    }

    #[test]
    fn test_canonical_hash_is_order_independent() {
        // Ensure the canonical form sorts keys, so object-order changes
        // don't break integrity verification.
        let a = serde_json::json!({"a": 1, "b": 2});
        let b = serde_json::json!({"b": 2, "a": 1});
        assert_eq!(canonical_hash(&a), canonical_hash(&b));
    }

    #[test]
    fn test_recovered_from_primary_on_clean_load() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("settings.json");
        {
            let s = Settings::new(&path);
            s.set("x", 1);
        }
        let s2 = Settings::new(&path);
        assert_eq!(s2.recovered_from(), RecoveredFrom::Primary);
        assert!(!s2.has_data_loss_flag());
    }
}